diff --git a/.gitignore b/.gitignore index d2ff201..e495200 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ /node_modules /oh_modules +/common/oh_modules +/features/mainLayout/oh_modules/@ohos/common/oh_modules /local.properties /.idea **/build @@ -9,4 +11,4 @@ /.clang-format /.clang-tidy **/.test -/.appanalyzer \ No newline at end of file +/.appanalyzer diff --git a/build-profile.json5 b/build-profile.json5 index 7da6232..9975f2a 100644 --- a/build-profile.json5 +++ b/build-profile.json5 @@ -5,13 +5,13 @@ "name": "release", "type": "HarmonyOS", "material": { + "storeFile": "D:/Developer/signature_config/harmony/rabbit/hmos.p12", + "storePassword": "00000018765013CD387F74CCFB6A27394F23D18FE0B2D659FB6FFD034EF55AC49A469D1972205C77", "keyAlias": "__uni__1be0b2f", + "keyPassword": "00000018DEFC4DEBF1B3CEDD0D5F3BB2D14B0408EC8D4080E5A70016B053CADC4148ECA51C5B6695", "signAlg": "SHA256withECDSA", - "storeFile": "D:/Developer/signature_config/harmony/hmos.p12", - "keyPassword": "000000188D653F4B8748579F0084CAC913B6D6AB6FF60084FB0F318CC52AC425A874B607DD8261F9", - "storePassword": "00000018779445CEA4B7EA75CB8F722F9DA76CBDBC5CE7C083CE8B5E1973141BF17E654C7237F5EF", - "certpath": "D:/Developer/signature_config/harmony/cer/release.cer", - "profile": "D:/Developer/signature_config/harmony/p7b/rabbit_releaseRelease.p7b" + "profile": "D:/Developer/signature_config/harmony/rabbit/rabbit_releaseRelease.p7b", + "certpath": "D:/Developer/signature_config/harmony/rabbit/release.cer" } }, { @@ -20,11 +20,11 @@ "material": { "keyAlias": "__uni__1be0b2f", "signAlg": "SHA256withECDSA", - "storeFile": "D:/Developer/signature_config/harmony/hmos.p12", - "keyPassword": "000000188D653F4B8748579F0084CAC913B6D6AB6FF60084FB0F318CC52AC425A874B607DD8261F9", - "storePassword": "00000018779445CEA4B7EA75CB8F722F9DA76CBDBC5CE7C083CE8B5E1973141BF17E654C7237F5EF", - "certpath": "D:/Developer/signature_config/harmony/cer/debug.cer", - "profile": "D:/Developer/signature_config/harmony/p7b/rabbit_debugDebug.p7b" + "storeFile": "D:/Developer/signature_config/harmony/rabbit/hmos.p12", + "keyPassword": "00000018DEFC4DEBF1B3CEDD0D5F3BB2D14B0408EC8D4080E5A70016B053CADC4148ECA51C5B6695", + "storePassword": "00000018765013CD387F74CCFB6A27394F23D18FE0B2D659FB6FFD034EF55AC49A469D1972205C77", + "profile": "D:/Developer/signature_config/harmony/rabbit/rabbit_debugDebug.p7b", + "certpath": "D:/Developer/signature_config/harmony/rabbit/debug.cer" } } ], @@ -43,12 +43,12 @@ "arkOptions": { "buildProfileFields": { "CHANNEL": "harmony", - "BUILD_TIME": "2605180938" + "BUILD_TIME": "2611021826" } } }, "output": { - "artifactName": "rabbit_harmony_debug_v1.0.1_2605180938" + "artifactName": "rabbit_harmony_debug_v1.0.1_2611021826" } } ], diff --git a/common/BuildProfile.ets b/common/BuildProfile.ets index 71d2b16..2dc1785 100644 --- a/common/BuildProfile.ets +++ b/common/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2605180937'; +export const BUILD_TIME = '2611021826'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/common/build-profile.json5 b/common/build-profile.json5 index 4f2a475..2e60238 100644 --- a/common/build-profile.json5 +++ b/common/build-profile.json5 @@ -1,6 +1,10 @@ { "apiType": "stageMode", "buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "abiFilters": ["arm64-v8a", "x86_64"] + }, "resOptions": { "copyCodeResource": { "enable": false diff --git a/common/oh-package.json5 b/common/oh-package.json5 index f2d0749..2493086 100644 --- a/common/oh-package.json5 +++ b/common/oh-package.json5 @@ -5,5 +5,7 @@ "main": "Index.ets", "author": "", "license": "Apache-2.0", - "dependencies": {} -} \ No newline at end of file + "dependencies": { + "libunimp_archive.so": "file:./src/main/cpp/types/libunimp_archive" + } +} diff --git a/common/src/main/cpp/CMakeLists.txt b/common/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..f7dbaf2 --- /dev/null +++ b/common/src/main/cpp/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.5.0) +project(unimp_archive) + +set(CMAKE_CXX_STANDARD 17) +set(MINIZIP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../../../oh_modules/@ohos/minizip") +add_library(minizip_runtime SHARED IMPORTED) +set_target_properties(minizip_runtime PROPERTIES + IMPORTED_LOCATION "${MINIZIP_ROOT}/libs/${OHOS_ARCH}/libminizip_ng.so") + +add_library(unimp_archive SHARED unimp_archive.cpp) +target_link_libraries(unimp_archive PRIVATE minizip_runtime libace_napi.z.so) diff --git a/common/src/main/cpp/types/libunimp_archive/index.d.ts b/common/src/main/cpp/types/libunimp_archive/index.d.ts new file mode 100644 index 0000000..097e829 --- /dev/null +++ b/common/src/main/cpp/types/libunimp_archive/index.d.ts @@ -0,0 +1 @@ +export const extract: (source: string, target: string, password: string) => number; diff --git a/common/src/main/cpp/types/libunimp_archive/oh-package.json5 b/common/src/main/cpp/types/libunimp_archive/oh-package.json5 new file mode 100644 index 0000000..e3cddca --- /dev/null +++ b/common/src/main/cpp/types/libunimp_archive/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libunimp_archive.so", + "version": "1.0.0", + "types": "./index.d.ts", + "description": "UniMP ZIP extraction with checked CRC/AES authentication" +} diff --git a/common/src/main/cpp/unimp_archive.cpp b/common/src/main/cpp/unimp_archive.cpp new file mode 100644 index 0000000..f39813d --- /dev/null +++ b/common/src/main/cpp/unimp_archive.cpp @@ -0,0 +1,74 @@ +#include +#include +#include +#include + +// Public C ABI of minizip-ng 4.2.2 bundled by pinned @ohos/minizip 1.0.6. +// https://github.com/zlib-ng/minizip-ng/blob/4.2.2/mz_zip_rw.h +// Use save_all's checked entry close (CRC/AES authentication). The package's +// ExtractFileToJS binding can return bytes even when final authentication fails. +extern "C" { +void *mz_zip_reader_create(void); +void mz_zip_reader_delete(void **handle); +int32_t mz_zip_reader_open_file(void *handle, const char *path); +void mz_zip_reader_set_password(void *handle, const char *password); +void mz_zip_reader_set_encoding(void *handle, int32_t encoding); +int32_t mz_zip_reader_save_all(void *handle, const char *directory); +} + +namespace { +struct ReaderDeleter { + void operator()(void *reader) const { mz_zip_reader_delete(&reader); } +}; + +bool ReadString(napi_env env, napi_value value, std::string &result) { + size_t length = 0; + if (napi_get_value_string_utf8(env, value, nullptr, 0, &length) != napi_ok) return false; + result.resize(length); + if (napi_get_value_string_utf8(env, value, result.data(), length + 1, &length) != napi_ok) return false; + return result.find('\0') == std::string::npos; +} + +napi_value Extract(napi_env env, napi_callback_info info) { + try { + size_t argc = 3; + napi_value argv[3]; + std::string source, target, password; + if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok || argc != 3 || + !ReadString(env, argv[0], source) || !ReadString(env, argv[1], target) || + !ReadString(env, argv[2], password) || source.empty() || target.empty()) { + napi_throw_type_error(env, nullptr, "Invalid WGT extraction arguments"); + return nullptr; + } + std::unique_ptr reader(mz_zip_reader_create()); + if (!reader) { + napi_throw_error(env, nullptr, "Cannot create WGT reader"); + return nullptr; + } + mz_zip_reader_set_encoding(reader.get(), 65001); + mz_zip_reader_set_password(reader.get(), password.c_str()); + int32_t result = mz_zip_reader_open_file(reader.get(), source.c_str()); + if (result == 0) result = mz_zip_reader_save_all(reader.get(), target.c_str()); + napi_value value; + napi_create_int32(env, result, &value); + return value; + } catch (...) { + napi_throw_error(env, nullptr, "WGT native extraction failed"); + return nullptr; + } +} + +napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor property = { + "extract", nullptr, Extract, nullptr, nullptr, nullptr, napi_default, nullptr + }; + napi_define_properties(env, exports, 1, &property); + return exports; +} + +napi_module module = {1, 0, nullptr, Init, "unimp_archive", nullptr, {0}}; +} + +extern "C" __attribute__((constructor)) void RegisterUniMpArchive() { + napi_module_register(&module); +} diff --git a/common/src/main/ets/utils/HuaweiAuth.ets b/common/src/main/ets/utils/HuaweiAuth.ets new file mode 100644 index 0000000..4d83e43 --- /dev/null +++ b/common/src/main/ets/utils/HuaweiAuth.ets @@ -0,0 +1,24 @@ +import { BusinessError } from '@kit.BasicServicesKit'; + +export const HUAWEI_AUTH_AGREEMENT_URL = + 'https://privacy.consumer.huawei.com/legal/id/authentication-terms.htm?code=CN&language=zh-CN'; + +/** 对齐 weiquan-har 的 HuaweiAuthService,授权交给官方快速登录按钮。 */ +export class HuaweiAuth { + static getErrorMessage(error: BusinessError): string { + switch (error.code) { + case 1001502001: + return '请先在系统设置中登录华为账号,或使用短信验证码登录'; + case 1001502012: + return '已取消华为账号授权'; + case 1001502005: + return '网络异常,请检查网络后重试'; + case 1001500002: + return '正在进行华为账号授权,请稍候'; + case 1005300001: + return '请先阅读并同意用户协议、隐私协议和华为账号用户认证协议'; + default: + return '华为账号授权失败,请重试或使用短信验证码登录'; + } + } +} diff --git a/common/src/main/ets/utils/KVManager.ets b/common/src/main/ets/utils/KVManager.ets index dd6bba9..8516f91 100644 --- a/common/src/main/ets/utils/KVManager.ets +++ b/common/src/main/ets/utils/KVManager.ets @@ -3,6 +3,9 @@ import { UNIMP_DATA_VERSION, WX_AUTH_CODE } from '../constants/AppConstants' import { UniMpLocalVersion } from '../viewmodel/LocalBean'; import { KVStore } from './KVStore' import { StringUtils } from './StringUtils'; +import { fileIo as fs } from '@kit.CoreFileKit'; + +let uniMpVersionWrite: Promise = Promise.resolve(); /** * 判断小程序是否需要下载(跳转指定路径) @@ -29,11 +32,11 @@ export async function isUniMpNeedDownloadForPath(uniId: string): Promise { - if(!targetVersion){ - true - } let uniMpVersions = await getUniMpNeedDownload(); let uniMpVersion = uniMpVersions.find(item => {return item.id === uniId}); + if (!uniMpVersion || !isUniMpPackageAvailable(uniMpVersion.path)) { + return true; + } if(!StringUtils.checkVersionLegal(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0') || !StringUtils.isNewVersionAvailable(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0')){ return false; }else{ @@ -47,26 +50,67 @@ export async function getUniMpNeedDownload(): Promise { let storeJson = await KVStore.getInstance() .get(UNIMP_DATA_VERSION, defaultJson); - let uniMpVersions = JSON.parse(storeJson) as UniMpLocalVersion[]; - return uniMpVersions + try { + const versions = JSON.parse(storeJson) as UniMpLocalVersion[]; + return Array.isArray(versions) ? versions : []; + } catch (_) { + return []; + } } -export async function setUniMpNeedDownload(id: string, type: string, version: string, path: string): Promise { - let uniMpVersions = await getUniMpNeedDownload(); +export function isUniMpPackageAvailable(path: string): boolean { + try { + return path.length > 0 && fs.accessSync(path) && fs.statSync(path).size > 0; + } catch (_) { + return false; + } +} + +export function setUniMpNeedDownload(id: string, type: string, version: string, path: string, + released: boolean = false): Promise { + // 串行读改写,避免微信和支付宝同时完成时互相覆盖版本列表。 + const write = uniMpVersionWrite.then(() => saveUniMpVersion(id, type, version, path, released)); + uniMpVersionWrite = write.catch(() => {}); + return write; +} + +async function saveUniMpVersion(id: string, type: string, version: string, path: string, + released: boolean): Promise { + let uniMpVersions = getUniMpVersionsSync(); let uniMpVersion = uniMpVersions.find(item => {return item.id === id}); if(uniMpVersion){ uniMpVersion.type = type; uniMpVersion.version = version; uniMpVersion.path = path; + uniMpVersion.released = released; }else{ uniMpVersions.push({ id: id, type: type, version: version, - path: path + path: path, + released: released }); } - KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(uniMpVersions)) + await KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(uniMpVersions)) +} + +function getUniMpVersionsSync(): UniMpLocalVersion[] { + try { + const versions = JSON.parse(KVStore.getInstance().getSync(UNIMP_DATA_VERSION, '[]')) as UniMpLocalVersion[]; + return Array.isArray(versions) ? versions : []; + } catch (_) { + return []; + } +} + +export function clearUniMpVersion(id: string): Promise { + const write = uniMpVersionWrite.then(async () => { + const versions = getUniMpVersionsSync().filter((item: UniMpLocalVersion) => item.id !== id); + await KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(versions)); + }); + uniMpVersionWrite = write.catch(() => {}); + return write; } export function setWechatAuthCode(wechatCode: string): void { @@ -75,4 +119,4 @@ export function setWechatAuthCode(wechatCode: string): void { export async function getWechatAuthCode(): Promise { return await KVStore.getInstance().get(WX_AUTH_CODE, '') -} \ No newline at end of file +} diff --git a/common/src/main/ets/utils/StringUtils.ets b/common/src/main/ets/utils/StringUtils.ets index e2ad63e..a248f35 100644 --- a/common/src/main/ets/utils/StringUtils.ets +++ b/common/src/main/ets/utils/StringUtils.ets @@ -1,6 +1,5 @@ import { pasteboard } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; -import { promptAction } from '@kit.ArkUI'; import { Logger } from './Logger'; import { ToastUtils } from '../dialog/ToastUtils'; diff --git a/common/src/main/ets/utils/UniMpArchive.ets b/common/src/main/ets/utils/UniMpArchive.ets new file mode 100644 index 0000000..ac5ddb9 --- /dev/null +++ b/common/src/main/ets/utils/UniMpArchive.ets @@ -0,0 +1,41 @@ +import { MinizipNative } from '@ohos/minizip'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { extract } from 'libunimp_archive.so'; + +// Native 解密/解压与文件写入在 TaskPool 中执行,不阻塞首页。 +@Concurrent +export function extractUniMpArchive(wgtPath: string, directory: string, password: string, appId: string): void { + const archive = new MinizipNative(wgtPath); + // Android Zip4JUtil.upZipFileWithPassword 同样明确使用 UTF-8。 + archive.SetCharEncoding(65001); + const code = archive.Open(); + if (code !== 0) { + throw new Error('WGT资源包打开失败,错误码: ' + code); + } + const entries = archive.GetEntryNames(); + if (entries.length === 0) { + throw new Error('WGT资源包为空'); + } + // 在写入任何条目前检查全部路径。 + for (const entry of entries) { + const parts = entry.split('/'); + if (!entry || entry.startsWith('/') || entry.includes('\\') || entry.includes(':') || entry.includes('\0') || + parts.some((part: string) => part === '..' || part === '.') || + parts.slice(0, -1).some((part: string) => part.length === 0)) { + throw new Error('WGT资源包包含非法文件路径'); + } + } + // 直接调用原生 save_all 并检查返回值,不能使用丢失 CRC/AES 校验错误的 ExtractFileToJS。 + const result = extract(wgtPath, directory, password); + if (result !== 0) { + throw new Error('WGT解压失败:密码错误、资源包损坏或写入失败,错误码: ' + result); + } + const manifestPath = directory + '/manifest.json'; + if (!fs.accessSync(manifestPath)) { + throw new Error('WGT资源包缺少manifest.json'); + } + const manifest = JSON.parse(fs.readTextSync(manifestPath)) as Record; + if (manifest['id'] !== appId) { + throw new Error('WGT资源包的应用ID与配置不一致'); + } +} diff --git a/common/src/main/ets/utils/UniMpDownloader.ets b/common/src/main/ets/utils/UniMpDownloader.ets new file mode 100644 index 0000000..dcf6fb9 --- /dev/null +++ b/common/src/main/ets/utils/UniMpDownloader.ets @@ -0,0 +1,134 @@ +import { request } from '@kit.BasicServicesKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { UniVersionEntity } from '../viewmodel/DataBean'; +import { isUniMpPackageAvailable } from './KVManager'; +import { getUniMpUrls } from './UniMpPolicy'; +import { reportUniMp } from './UniMpReporter'; +import { Logger } from './Logger'; + +const DOWNLOAD_TIMEOUT = 60000; + +export function removeUniMpPackage(path: string): void { + if (fs.accessSync(path)) { + fs.unlinkSync(path); + } +} + +async function downloadAttempt(context: Context, url: string, path: string, + onProgress: (progress: number) => void): Promise { + removeUniMpPackage(path); + const config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: url, + saveas: path, + mode: request.agent.Mode.FOREGROUND, + overwrite: true, + retry: false + }; + const task = await request.agent.create(context, config); + try { + await new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + fail('下载超时(60秒)'); + }, DOWNLOAD_TIMEOUT); + const fail = (reason: string): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + reject(new Error(reason)); + }; + task.on('progress', (progress: request.agent.Progress) => { + if (!settled && progress.sizes.length > 0 && progress.sizes[0] > 0) { + onProgress(Math.min(99, Math.floor(progress.processed * 100 / progress.sizes[0]))); + } + }); + task.on('completed', () => { + if (!settled) { + settled = true; + clearTimeout(timer); + resolve(); + } + }); + task.on('failed', (info: request.agent.Progress) => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + // failed 事件只携带进度,查询任务才能取得真实网络错误码和原因。 + request.agent.show(task.tid).then((detail: request.agent.TaskInfo) => { + reject(new Error(detail.reason || `下载失败,错误码: ${detail.faults}`)); + }).catch(() => reject(new Error(`下载失败: ${JSON.stringify(info)}`))); + }); + try { + task.start().catch((error: Error) => fail(error.message)); + } catch (error) { + fail((error as Error).message); + } + }); + } finally { + // 停止写入后才允许下一地址重用临时文件。 + try { + await task.stop(); + } catch (_) { + // 完成/失败的任务已经停止。 + } + await request.agent.remove(task.tid); + } +} + +export async function downloadUniMp(context: Context, entity: UniVersionEntity, + onProgress: (progress: number) => void): Promise { + const id = entity.unimp_id ?? ''; + const target = `${context.filesDir}/${id}.wgt`; + const temporary = `${context.filesDir}/${id}_cache.wgt`; + const urls = getUniMpUrls(entity); + let maxProgress = 0; + onProgress(0); + if (urls.length === 0) { + reportUniMp('error', 'client.download.unimp.error', 'url为空!', '上报原因:未配置下载地址'); + throw new Error('未配置下载地址'); + } + for (const url of urls) { + const start = Date.now(); + try { + await downloadAttempt(context, url, temporary, (progress: number) => { + maxProgress = Math.max(maxProgress, progress); + onProgress(maxProgress); + }); + if (!isUniMpPackageAvailable(temporary)) { + throw new Error('下载资源包为空'); + } + } catch (error) { + const reason = (error as Error).message || 'Url连接错误'; + const time = ((Date.now() - start) / 1000).toFixed(2); + reportUniMp('error', 'client.download.unimp.error', reason, + `下载地址:${url} 持续时间:${time}秒 上报原因:${reason}`); + try { + removeUniMpPackage(temporary); + } catch (cleanupError) { + Logger.info('UniMp', `清理临时包失败: ${(cleanupError as Error).message}`); + throw new Error((cleanupError as Error).message); + } + continue; + } + const time = ((Date.now() - start) / 1000).toFixed(2); + try { + // 下载过程中保留旧包,完整下载后才替换;SDK 所需文件名必须为 appId.wgt。 + removeUniMpPackage(target); + fs.renameSync(temporary, target); + } catch (error) { + reportUniMp('error', 'client.download.unimp.error', '复制资源包失败', + `下载地址:${url} 持续时间:${time}秒 上报原因:下载完成,复制资源包失败!`); + throw new Error((error as Error).message); + } + onProgress(100); + reportUniMp('click', 'client.download.unimp.success', `下载时间:${time}s`, + `下载地址:${url} 持续时间:${time}秒 上报原因:下载完成。`); + return target; + } + throw new Error('所有下载地址均失败'); +} diff --git a/common/src/main/ets/utils/UniMpManager.ets b/common/src/main/ets/utils/UniMpManager.ets index 072ba43..d900815 100644 --- a/common/src/main/ets/utils/UniMpManager.ets +++ b/common/src/main/ets/utils/UniMpManager.ets @@ -1,199 +1,263 @@ -import { openUniMP, releaseWgtToRunPath, UniMP } from '@dcloudio/uni-app-runtime' -import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN } from '../constants/AppConstants' -import { ToastUtils } from '../dialog/ToastUtils' -import { UniVersionEntity,TradeData, UniIconEntity } from '../viewmodel/DataBean' -import { downloadFile } from './DownloaderUtils' -import { isUniMpNeedDownload, isUniMpNeedDownloadForPath, setUniMpNeedDownload } from './KVManager' -import { KVStore } from './KVStore' -import { Logger } from './Logger' -import { bundleManager, common } from '@kit.AbilityKit' -import { DeviceUtil } from '@pura/harmony-utils' -import { deviceInfo } from '@kit.BasicServicesKit' -import { CHANNEL } from '../../../../BuildProfile' -import { CommonService } from '../viewmodel/CommonService' +import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime'; +import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants'; +import { ToastUtils } from '../dialog/ToastUtils'; +import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean'; +import { clearUniMpVersion, getUniMpNeedDownload, isUniMpPackageAvailable, setUniMpNeedDownload } from './KVManager'; +import { KVStore } from './KVStore'; +import { Logger } from './Logger'; +import { bundleManager, common } from '@kit.AbilityKit'; +import { AppUtil, DeviceUtil } from '@pura/harmony-utils'; +import { deviceInfo } from '@kit.BasicServicesKit'; +import { CHANNEL } from '../../../../BuildProfile'; +import { CommonService } from '../viewmodel/CommonService'; +import { routerLogin } from '../router/RouterManager'; +import { downloadUniMp, removeUniMpPackage } from './UniMpDownloader'; +import { getUniMpReleasePassword, getUniMpUpdate, UniMpUpdate } from './UniMpPolicy'; +import { reportUniMp } from './UniMpReporter'; +import { releaseUniMpWgt } from './UniMpRelease'; +import { UniMpRuntimeCompat } from './UniMpRuntimeCompat'; -/** - * 下载并启动模拟器 - * @param context - * @param entity - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function downStartUp(context: UIContext, entity: UniVersionEntity, callback: (status: number, progress: number, path?: string) => void) { - let uniMpId = entity.unimp_id;//'__UNI__D535736'; - let uniMpType = entity.unimp_type; - let uniMpUrl = entity.url;//'https://cdn.batiao8.com/flaunt/uni_mp/wgt/alipay/__UNI__D535736_2026-4-20-test4.wgt'; - let uniVersion = entity.version??'0.0.0'; - if(uniMpId){ - isUniMpNeedDownload(uniMpId, uniVersion).then(res => { - if(res == true){ - callback(1, 0) - //需要更新,则删除旧文件,重新下载wgt文件 - if(!uniMpId){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); +// 保留原有状态值,所有入口共享同一下载、解压和启动流程。 +export enum UniMpStatus { + FAILURE = -1, + IDLE = 0, + DOWNLOADING = 1, + DOWNLOADED = 2, + STARTED = 3, + RELEASED = 4, + RELEASE_FAILURE = 5, + RELEASING = 6, + BUSY = 7, + LOGIN = 8, + UPDATE_PROMPT = 9, + OPENING = 10 +} +type UniMpCallback = (status: number, progress: number, path?: string) => void; +const runningApps = new Map(); +const pendingApps = new Set(); - callback(-1, 0); - return - } - - //下载模拟器 - downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => { - if(status == 2){ - callback(status, progress, path); - //已下载完成,释放并启动 - releaseRunUniMp(context, uniMpId??'', '', (status) => { - callback(status, progress, path); - }) - }else if(status == -1){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); - callback(status, progress, path); - }else{ - callback(status, progress, path); - } - Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress); - }) - }else{ - //不需要更新,已释放则直接打开模拟器,否则先释放,再打开 - runUniMp(context, uniMpId??'', '', (status) => { - callback(status, 100); - }) - } - }); - } - Logger.info('UniMp','uniMpId:'+uniMpId+ ', uniMpType:' + uniMpType + ', uniMpUrl:' + uniMpUrl + ', uniMpVersion:' + uniVersion); +export function downStartUp(context: UIContext, entity: UniVersionEntity, callback: UniMpCallback): void { + startOpenUniMp(context, entity, '', 'home', callback); } -export function downStartUpForPath(context: UIContext, uniMpVersions: UniVersionEntity[], uniIconEntity: UniIconEntity, callback: (status: number, progress: number, path?: string) => void) { - const uniMpType = uniIconEntity.type - const uniMpEntity = uniMpVersions.find((item: UniVersionEntity) => { - return item.unimp_type === uniMpType; - }); +export function downStartUpForPath(context: UIContext, versions: UniVersionEntity[], icon: UniIconEntity, + callback: UniMpCallback): void { + if (!icon.enable) { + callback(UniMpStatus.IDLE, 0); + return; + } + const entity = versions.find((item: UniVersionEntity) => item.unimp_type === icon.type); + if (!entity) { + failWithToast(context, callback); + return; + } + startOpenUniMp(context, entity, icon.url ?? '', icon.text ?? '', callback); +} - const targetPath = uniIconEntity.url??''; - const uniMpUrl = uniMpEntity?.url??''; - const uniMpId = uniMpEntity?.unimp_id??''; - const uniMpVersion = uniMpEntity?.version??''; - isUniMpNeedDownloadForPath(uniMpId).then(res => { - if(res == true){ - // 已释放,直接运行 - runUniMp(context, uniMpId??'', '', (status) => { - callback(status, 100); - }) - }else{ - // 未下载,先下载释放,再运行 - downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => { - if(status == 2){ - // 设置下载的版本信信 - setUniMpNeedDownload(uniMpId??'', uniMpType??'', uniMpVersion??'', path??''); - callback(status, progress, path); - // 已下载完成,释放并启动 - releaseRunUniMp(context, uniMpId??'', targetPath, (status) => { - callback(status, progress, path); - }) - }else if(status == -1){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!') - callback(status, progress, path); - }else{ - callback(status, progress, path); - } - Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress); - }) +async function startOpenUniMp(context: UIContext, entity: UniVersionEntity, targetPath: string, itemName: string, + callback: UniMpCallback): Promise { + const id = entity.unimp_id ?? ''; + if (!/^[A-Za-z0-9_-]+$/.test(id)) { + reportUniMp('error', 'client.uni.fail', id, '上报原因:小程序ID为空或无效'); + failWithToast(context, callback); + return; + } + const profile = AppStorage.get(USER_PROFILE); + if (profile?.config?.forceUniLogin && !KVStore.getInstance().getSync(TOKEN_LOGIN, '')) { + callback(UniMpStatus.LOGIN, 0); + routerLogin('unimp', false); + return; + } + reportUniMp('click', entity.unimp_type === 'wx' ? 'event_client_open_wx_unimp' : 'event_client_open_alipay_unimp', itemName); + if (pendingApps.has(id)) { + callback(UniMpStatus.BUSY, 0); + ToastUtils.showToast(context, '请等待模拟器更新完毕!'); + return; + } + pendingApps.add(id); + try { + const running = runningApps.get(id); + if (running) { + try { + running.show(); + running.sendUniMPEvent('token', KVStore.getInstance().getSync(TOKEN, '')); + running.sendUniMPEvent('jump', targetPath); + callback(UniMpStatus.STARTED, 100); + return; + } catch (error) { + runningApps.delete(id); + try { running.close(); } catch (_) {} + Logger.info('UniMp', '恢复小程序失败,重新启动: ' + (error as Error).message); + } + } + const path = getContext().filesDir + '/' + id + '.wgt'; + const versions = await getUniMpNeedDownload(); + const local = versions.find((item) => item.id === id); + const update = getUniMpUpdate(entity, local?.version ?? '0.0.0', isUniMpPackageAvailable(path)); + let shouldDownload = update === UniMpUpdate.REQUIRED; + if (update === UniMpUpdate.OPTIONAL) { + callback(UniMpStatus.UPDATE_PROMPT, 0); + shouldDownload = await confirmUpdate(context); + reportUniMp('click', shouldDownload ? 'client.confirm.download.unimp' : 'client.cancel.download.unimp', + '', JSON.stringify(entity)); + } + if (shouldDownload) { + try { + await downloadUniMp(getContext(), entity, (progress: number) => callback(UniMpStatus.DOWNLOADING, progress)); + await setUniMpNeedDownload(id, entity.unimp_type ?? '', entity.version ?? '', path, false); + } catch (error) { + Logger.info('UniMp', '下载失败: ' + (error as Error).message); + failWithToast(context, callback); + return; + } + callback(UniMpStatus.DOWNLOADED, 100, path); + } + // 取消更新时使用旧版本,页面不能再写入远端版本。 + const version = shouldDownload ? entity.version ?? '' : local?.version ?? '0.0.0'; + await releaseAndOpen(context, entity, targetPath, path, version, + shouldDownload || local?.released !== true, callback); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.fail', id, '上报原因:启动小程序异常 ' + (error as Error).message); + failWithToast(context, callback); + } finally { + pendingApps.delete(id); + } +} + +async function confirmUpdate(context: UIContext): Promise { + try { + const result = await context.getPromptAction().showDialog({ + title: '资源包更新', + message: '是否确定更新资源包', + buttons: [{ text: '取消', color: '#666666' }, { text: '确定', color: '#4F8AF6' }] + }); + return result.index === 1; + } catch (_) { + // 返回键或点击遮罩与取消按钮一致,继续打开本地版本。 + return false; + } +} + +async function releaseAndOpen(context: UIContext, entity: UniVersionEntity, targetPath: string, path: string, + version: string, forceRelease: boolean, callback: UniMpCallback): Promise { + const id = entity.unimp_id ?? ''; + if (forceRelease || !isExistsUniMP(id)) { + callback(UniMpStatus.RELEASING, 100, path); + try { + if (!isUniMpPackageAvailable(path)) { + throw new Error('本地资源包不存在或为空'); + } + const config = AppStorage.get(USER_PROFILE)?.config; + const password = getUniMpReleasePassword(config?.wgtPassword ?? '', config?.uniPassword ?? ''); + await releaseUniMpWgt(id, path, password); + await setUniMpNeedDownload(id, entity.unimp_type ?? '', version, path, true); + callback(UniMpStatus.RELEASED, 100, path); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.release.wgt', id, (error as Error).message); + failWithToast(context, callback, UniMpStatus.RELEASE_FAILURE); + return; + } + } + callback(UniMpStatus.OPENING, 100, path); + try { + // 已缓存/已解压的旧包也要处理,不能只在新包解压后修复。 + await UniMpRuntimeCompat.prepare(getContext() as common.Context, id); + const config = await uniMpConfig(context); + const mp = openUniMP(id, { + redirectPath: targetPath, + extraData: config, + showCapsuleButton: false, + showSplashScreen: true + }) as UniMP; + if (!mp) { + throw new Error('启动小程序失败'); + } + runningApps.set(id, mp); + registerEvents(id, mp); + // 与 Android 一致,获得实例就结束启动状态,show 事件不重复结束请求。 + callback(UniMpStatus.STARTED, 100, path); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.fail', id, '上报原因:启动小程序失败 ' + (error as Error).message); + failWithToast(context, callback); + } +} + +function registerEvents(id: string, mp: UniMP): void { + mp.on('close', () => { + if (runningApps.get(id) === mp) { + runningApps.delete(id); + } + Logger.info('UniMp', 'close: ' + id); + }); + mp.on('show', () => Logger.info('UniMp', 'show: ' + id)); + mp.on('hide', () => Logger.info('UniMp', 'hide: ' + id)); + mp.on('uniMPEvent', (event: string, data: object) => { + Logger.info('UniMp', 'uniMPEvent: ' + event); + try { + if (event === 'start_combo_pay') { + const trade = JSON.parse(typeof data === 'string' ? data : JSON.stringify(data)) as TradeData; + CommonService.startUniPay(getContext() as common.UIAbilityContext, trade.weixinMpOriId ?? '', trade.outTradeNo ?? ''); + } else if (event === 'closeUniAPP') { + runningApps.delete(id); + mp.close(); + } + } catch (error) { + reportUniMp('error', 'client.uni.fail', id, '小程序事件 ' + event + ' 处理异常: ' + (error as Error).message); } }); } -/** - * 运行模拟器 - * 1、如已释放,直接运行 - * 2、如未释放,先释放,再运行 - * @param uniMpId 小程序ID - * @param targetPath 跳转小程序路径 - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function runUniMp(context: UIContext, uniMpId: string, targetPath:string, callback: (status: number) => void){ - releaseRunUniMp(context, uniMpId, targetPath, callback) -} -/** - * 释放并运行,需要先释放,再运行 - * 1、删除旧文件 - * 2、先释放,再运行 - * @param uniMpId 小程序ID - * @param targetPath 跳转小程序路径 - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function releaseRunUniMp(context: UIContext, uniMpId: string, targetPath: string, callback: (status: number) => void){ - let path = getContext().filesDir + "/"+uniMpId+".wgt" - uniMpConfig().then(res => { - releaseWgtToRunPath(uniMpId, path, (code: 1 | -1, _) =>{ - if(code === 1){ - callback(4) - // 释放成功,运行 - const mp = openUniMP(uniMpId, { - redirectPath: targetPath, - extraData: res, - showCapsuleButton: false, - showSplashScreen: true, - }) as UniMP - - mp.on('close',()=>{ - console.log('UniMP-close') - }) - mp.on('show',()=>{ - console.log('UniMP-show') - callback(3) - }) - mp.on('hide',()=>{ - console.log('UniMP-hide') - }) - mp.on('uniMPEvent', (event: string, data: object, _notify: boolean) => { - Logger.info('UniMp', 'uniMPEvent:' + event + ', data:' + data) - - if(event === 'openUniAPP'){ - //渲染完成 - }else if(event === 'start_combo_pay'){ - const jsonStr = typeof data === 'string' ? data : JSON.stringify(data); - const obj = JSON.parse(jsonStr) as TradeData; - - const weixinMpOriId: string = obj.weixinMpOriId ?? ""; - const outTradeNo: string = obj.outTradeNo ?? ""; - CommonService.startUniPay(getContext() as common.UIAbilityContext, weixinMpOriId, outTradeNo) - }else if(event === 'closeUniAPP'){ - mp.close() - } - }) - }else{ - // 释放失败,提示用户 - ToastUtils.showToast(context, '加载失败,请重试或联系客服!') - callback(5) - } - }) - }) +async function invalidatePackage(id: string): Promise { + const mp = runningApps.get(id); + runningApps.delete(id); + try { mp?.close(); } catch (_) {} + try { + removeUniMpPackage(getContext().filesDir + '/' + id + '.wgt'); + } catch (error) { + Logger.info('UniMp', '清理资源包失败: ' + (error as Error).message); + } + await clearUniMpVersion(id); } -async function uniMpConfig(): Promise>{ - let extraData: Record = {}; +function failWithToast(context: UIContext, callback: UniMpCallback, status: UniMpStatus = UniMpStatus.FAILURE): void { + callback(status, 0); + ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); +} +export function closeUniMpApps(): void { + runningApps.forEach((mp: UniMP) => { + try { mp.close(); } catch (_) {} + }); + runningApps.clear(); +} + +async function uniMpConfig(context: UIContext): Promise> { const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); - const versionName = bundleInfo.versionName; - const bundleName = bundleInfo.name; - - const accessToken: string = KVStore.getInstance().getSync(TOKEN, ''); - const deviceId: string = DeviceUtil.getDeviceId(); - const brand: string = deviceInfo.brand; - const model: string = deviceInfo.productModel; - - extraData["x-token"] = accessToken; - extraData["x-version"] = versionName; - extraData["x-platform"] = PLATFORM; - extraData["x-device-id"] = deviceId; - extraData["x-mobile-brand"] = brand; - extraData["x-mobile-model"] = model; - extraData["x-channel"] = CHANNEL; - extraData["x-package"] = bundleName; - extraData["x-click-id"] = ''; - extraData["host"] = RELEASE_BASE_URL + '/'; - extraData["decrypt"] = AESDecrypt; - extraData["encrypt"] = Signature; - extraData["isCombo"] = 'ok'; - - return extraData -} \ No newline at end of file + let safeBottom = 0; + try { + safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight()))); + } catch (_) { + // 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。 + } + const extraData: Record = { + 'x-token': KVStore.getInstance().getSync(TOKEN, ''), + 'x-version': bundleInfo.versionName, + 'x-platform': PLATFORM, + 'x-device-id': DeviceUtil.getDeviceId(), + 'x-mobile-brand': deviceInfo.brand, + 'x-mobile-model': deviceInfo.productModel, + 'x-channel': CHANNEL, + 'x-package': bundleInfo.name, + 'x-click-id': '', + 'host': RELEASE_BASE_URL + '/', + 'decrypt': AESDecrypt, + 'encrypt': Signature, + 'isCombo': 'ok' + }; + // WGT 内部用 Number() 计算避让,并直接将该值传给 showModal.content,需提供字符串。 + extraData['safeBottom'] = String(safeBottom); + return extraData; +} diff --git a/common/src/main/ets/utils/UniMpPolicy.ets b/common/src/main/ets/utils/UniMpPolicy.ets new file mode 100644 index 0000000..a7a4570 --- /dev/null +++ b/common/src/main/ets/utils/UniMpPolicy.ets @@ -0,0 +1,39 @@ +import { UniVersionEntity } from '../viewmodel/DataBean'; + +export enum UniMpUpdate { + NONE, + OPTIONAL, + REQUIRED +} + +export function getUniMpUpdate(entity: UniVersionEntity, localVersion: string, hasPackage: boolean): UniMpUpdate { + if (!hasPackage || entity.force) { + return UniMpUpdate.REQUIRED; + } + const target = entity.version ?? ''; + // 与 Android UserUtils.checkVersion 一致,仅比较三段数字版本。 + if (!/^\d+\.\d+\.\d+$/.test(target) || !/^\d+\.\d+\.\d+$/.test(localVersion)) { + return UniMpUpdate.NONE; + } + const remote = target.split('.').map((part: string) => Number(part)); + const local = localVersion.split('.').map((part: string) => Number(part)); + for (let index = 0; index < 3; index++) { + if (remote[index] > local[index]) { + return UniMpUpdate.OPTIONAL; + } + if (remote[index] < local[index]) { + return UniMpUpdate.NONE; + } + } + return UniMpUpdate.NONE; +} + +export function getUniMpUrls(entity: UniVersionEntity): string[] { + // 新配置以 urls 的顺序为准;旧配置只有 url 时保持兼容。 + const urls = (entity.urls ?? []).filter((url: string) => url.trim().length > 0); + return urls.length > 0 ? urls : (entity.url ? [entity.url] : []); +} + +export function getUniMpReleasePassword(releasePassword: string, uniPassword: string): string { + return (releasePassword.length > 10 ? releasePassword.substring(10) : releasePassword) + uniPassword; +} diff --git a/common/src/main/ets/utils/UniMpRelease.ets b/common/src/main/ets/utils/UniMpRelease.ets new file mode 100644 index 0000000..ed278c9 --- /dev/null +++ b/common/src/main/ets/utils/UniMpRelease.ets @@ -0,0 +1,59 @@ +import { getUniMPRunPath } from '@dcloudio/uni-app-runtime'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { taskpool } from '@kit.ArkTS'; +import { extractUniMpArchive } from './UniMpArchive'; +import { Logger } from './Logger'; + +// SDK 自带接口没有 password 参数,直接将解密后的资源部署到它公开的运行目录。 +export async function releaseUniMpWgt(appId: string, wgtPath: string, password: string): Promise { + await deployUniMpWgt(appId, wgtPath, password, getUniMPRunPath(appId)); +} + +// 将目录部署与 SDK 上下文分开,真机测试可使用专用目录而不触碰用户的小程序数据。 +export async function deployUniMpWgt(appId: string, wgtPath: string, password: string, root: string): Promise { + if (!/^[A-Za-z0-9_-]+$/.test(appId)) { + throw new Error('小程序ID无效'); + } + const runtime = root + '/www'; + const staging = root + '/www.pending'; + const backup = root + '/www.previous'; + // 恢复上一次在替换运行目录时被中断的部署。 + if (fs.accessSync(backup) && !fs.accessSync(runtime)) { + fs.renameSync(backup, runtime); + } + if (fs.accessSync(backup)) { + await fs.rmdir(backup); + } + if (fs.accessSync(staging)) { + await fs.rmdir(staging); + } + await fs.mkdir(staging, true); + try { + const task = new taskpool.Task(extractUniMpArchive, wgtPath, staging, password, appId); + await taskpool.execute(task); + // 只替换 www,保留小程序的 _doc 等业务数据。 + if (fs.accessSync(runtime)) { + fs.renameSync(runtime, backup); + } + try { + fs.renameSync(staging, runtime); + } catch (error) { + if (fs.accessSync(backup)) { + fs.renameSync(backup, runtime); + } + throw new Error('WGT运行目录替换失败'); + } + } finally { + if (fs.accessSync(staging)) { + await fs.rmdir(staging); + } + } + // 新资源已经完整部署;旧目录的清理失败不能误报本次解压失败。 + try { + if (fs.accessSync(backup)) { + await fs.rmdir(backup); + } + } catch (_) { + Logger.info('UniMp', '旧资源目录将在下次部署时清理'); + } +} diff --git a/common/src/main/ets/utils/UniMpReporter.ets b/common/src/main/ets/utils/UniMpReporter.ets new file mode 100644 index 0000000..0d36a30 --- /dev/null +++ b/common/src/main/ets/utils/UniMpReporter.ets @@ -0,0 +1,24 @@ +import { PLATFORM } from '../constants/AppConstants'; +import { ApiManager } from '../provider/ApiManager'; +import { Logger } from './Logger'; + +interface UniMpReport { + source: string; + type: string; + key: string; + value: string; + extra: string; +} + +// 使用 Android 相同的接口、事件名称和字段,沿用宿主已有的 source/请求签名约定。 +export function reportUniMp(type: string, key: string, value: string = '', extra: string = ''): void { + const data: UniMpReport = { source: PLATFORM, type: type, key: key, value: value, extra: extra }; + try { + ApiManager.getInstance().request('/api/user/event', undefined, 'post', data).catch((error: Error) => { + // 上报失败不能影响下载、解压或启动,也不递归上报。 + Logger.info('UniMp', `事件上报失败 ${key}: ${error.message}`); + }); + } catch (error) { + Logger.info('UniMp', `事件上报失败 ${key}: ${(error as Error).message}`); + } +} diff --git a/common/src/main/ets/utils/UniMpRuntimeCompat.ets b/common/src/main/ets/utils/UniMpRuntimeCompat.ets new file mode 100644 index 0000000..096fbcb --- /dev/null +++ b/common/src/main/ets/utils/UniMpRuntimeCompat.ets @@ -0,0 +1,64 @@ +import { common } from '@kit.AbilityKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { util } from '@kit.ArkTS'; +import { getUniMPRunPath } from '@dcloudio/uni-app-runtime'; +import { Logger } from './Logger'; + +/** 修复旧 WGT 在鸿蒙启动时读取 plus.os.name 等缺失元数据导致的白屏。 */ +export class UniMpRuntimeCompat { + static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v3 */'; + + static async prepare(context: common.Context, appId: string): Promise { + const servicePath = getUniMPRunPath(appId) + '/www/app-service.js'; + let source = await fs.readText(servicePath); + if (source.startsWith(UniMpRuntimeCompat.MARKER)) { + return; + } + if (source.startsWith('/* rabbit-unimp-harmony-compat:v1 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v2 */')) { + const endMarker = '/* end-rabbit-unimp-harmony-compat */'; + const end = source.indexOf(endMarker); + if (end < 0) { + throw new Error('旧版小程序兼容脚本不完整'); + } + source = source.substring(end + endMarker.length).replace(/^\r?\n/, ''); + } + // 当前 WGT 留有无业务回调的 safeBottom 调试弹窗。只移除已确认的这一条语句, + // 不拦截 showModal API,也不修改其他提示、协议或确认逻辑。 + source = source.replace( + /uni\.showModal\(\{title:"safeBottom",showCancel:!1,content:[$\w]+\.safeBottom,success:function\([$\w]+\)\{\}\}\)/g, + 'void 0'); + if (!source.trim()) { + throw new Error('小程序启动脚本为空'); + } + const resource = await context.resourceManager.getRawFileContent('unimp-harmony-compat.js'); + const bootstrap = util.TextDecoder.create('utf-8').decodeWithStream(resource); + if (!bootstrap.startsWith(UniMpRuntimeCompat.MARKER)) { + throw new Error('小程序启动兼容资源无效'); + } + const temporary = servicePath + '.compat-tmp'; + try { + const file = await fs.open(temporary, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY | fs.OpenMode.TRUNC); + try { + const bytes = new util.TextEncoder().encodeInto(bootstrap + '\n' + source); + let written = 0; + while (written < bytes.byteLength) { + const count = await fs.write(file.fd, bytes.buffer.slice(written)); + if (count <= 0) { + throw new Error('小程序启动兼容脚本写入不完整'); + } + written += count; + } + } finally { + await fs.close(file); + } + // 只更新已解压的运行资源,原始 WGT 和用户数据不变。 + await fs.rename(temporary, servicePath); + Logger.info('UniMp', '已补齐鸿蒙启动元数据: ' + appId); + } finally { + if (fs.accessSync(temporary)) { + await fs.unlink(temporary); + } + } + } +} diff --git a/common/src/main/ets/viewmodel/CommonService.ets b/common/src/main/ets/viewmodel/CommonService.ets index e54bd7a..9704093 100644 --- a/common/src/main/ets/viewmodel/CommonService.ets +++ b/common/src/main/ets/viewmodel/CommonService.ets @@ -3,7 +3,7 @@ import deviceInfo from "@ohos.deviceInfo"; import { DeviceUtil } from "@pura/harmony-utils"; import { Logger } from "../utils/Logger"; import { ApiManager } from "../provider/ApiManager"; -import { DEVICE_OAID, LOGIN_PROFILE, TOKEN, TOKEN_LOGIN, USER_INFO, USER_PROFILE, +import { DEVICE_OAID, LOGIN_PROFILE, PLATFORM, TOKEN, TOKEN_LOGIN, USER_INFO, USER_PROFILE, WXAPPID} from "../constants/AppConstants"; import { KVStore } from "../utils/KVStore"; import { RequestCallback } from "../provider/Callback"; @@ -11,6 +11,7 @@ import { EVT_USER_INFO,EVT_USER_CONFIG_PROFILE } from "../constants/EventConstan import { emitter } from "@kit.BasicServicesKit"; import { AFAuthServiceResponse, AFService, AFServiceCenter, AFServiceParams, AFWantParams } from "@alipay/afservicesdk"; import { common } from "@kit.AbilityKit"; +import { loginComponentManager } from "@kit.AccountKit"; import { ToastUtils } from "../dialog/ToastUtils"; import * as wxopensdk from '@tencent/wechat_open_sdk'; @@ -67,7 +68,7 @@ export class CommonService { }; const result = await ApiManager.getInstance().request( - 'api/user/code', // api + '/api/user/code', // api undefined, // get请求参数,会拼接到url中 'post', // 请求方式 postParms // post请求参数 @@ -130,14 +131,16 @@ export class CommonService { ); if(result.code === 200 || result.code === 0){ - const token = result.data.token - if(token && token.length > 0){ - //将登录信息持久化(const savedProfile = JSON.parse(rawJson) as LoginProfile;) - const loginJson: string = JSON.stringify(result); - KVStore.getInstance().put(LOGIN_PROFILE, loginJson); //持久化登录信息 - KVStore.getInstance().put(TOKEN_LOGIN, token ?? ''); //持久化token - KVStore.getInstance().put(TOKEN, token ?? ''); //持久化token + const token = result.data?.token; + if (!token || token.length === 0) { + callback?.onFailure?.('登录失败,请重新登录'); + return; } + // 保存完成后再刷新用户信息,确保后续请求使用新 token。 + const loginJson: string = JSON.stringify(result); + await KVStore.getInstance().put(LOGIN_PROFILE, loginJson); + await KVStore.getInstance().put(TOKEN_LOGIN, token); + await KVStore.getInstance().put(TOKEN, token); if (callback && callback.onSuccess) { callback.onSuccess(result.data); } @@ -221,12 +224,60 @@ export class CommonService { } } + /** + * 对齐 weiquan-har LoginViewModel.loginByHuawei:type + bind + data.code。 + */ + static async huaweiLogin(credential: loginComponentManager.HuaweiIDCredential, + callback?: RequestCallback, bind: boolean = false): Promise { + if (!credential?.authorizationCode?.trim()) { + callback?.onFailure?.('华为账号未返回授权码,请重试或使用短信验证码登录'); + return; + } + const huaweiData: Record = { 'code': credential.authorizationCode }; + const postData: Record = { + 'type': 'huawei', + 'bind': bind ? true : '', + 'data': huaweiData + }; + try { + const result = await ApiManager.getInstance().request( + '/api/user/login', undefined, 'post', postData); + if (result.code !== 0) { + callback?.onFailure?.(result.message || '登录失败,请重试或使用短信验证码登录'); + return; + } + const token = result.data?.token; + if (!token?.trim()) { + callback?.onFailure?.('登录失败,请重试或使用短信验证码登录'); + return; + } + await KVStore.getInstance().put(LOGIN_PROFILE, JSON.stringify(result)); + await KVStore.getInstance().put(TOKEN_LOGIN, token); + await KVStore.getInstance().put(TOKEN, token); + // 与参考项目一致,使用新 token 刷新配置后才返回成功;刷新失败不撤销登录。 + try { + await CommonService.getUserProfile(); + } catch (_) { + Logger.info('HuaweiLogin', '登录成功,配置刷新失败,保留有效登录凭证'); + } + const report: Record = { + 'source': PLATFORM, 'type': 'click', 'key': 'client.login', 'value': 'huawei', 'extra': '' + }; + ApiManager.getInstance().request('/api/user/event', undefined, 'post', report).catch(() => { + Logger.info('HuaweiLogin', '登录事件上报失败'); + }); + callback?.onSuccess?.(result.data); + } catch (error) { + callback?.onError?.(error as Error); + } + } + /** * 获取支付宝登录参数 */ static async getAlipayLoginParams(): Promise { const result = await ApiManager.getInstance().request( - 'api/alipay/app_param', + '/api/alipay/app_param', undefined, undefined ); @@ -296,4 +347,4 @@ export class CommonService { WXApi.sendReq(context, req) } -} \ No newline at end of file +} diff --git a/common/src/main/ets/viewmodel/DataBean.ets b/common/src/main/ets/viewmodel/DataBean.ets index 62e50d8..81a2732 100644 --- a/common/src/main/ets/viewmodel/DataBean.ets +++ b/common/src/main/ets/viewmodel/DataBean.ets @@ -1,4 +1,5 @@ import ArrayList from "@ohos.util.ArrayList"; +import { HomeBannerEntity, visibleHomeBanners } from './HomeBannerEntity'; /** * UserProfile 的专属转换器 @@ -19,9 +20,13 @@ export const UserProfileMapper = (raw: Record): UserProfile => { export const ConfigMapper = (raw: Record): ConfigEntity => { return { versionEntity: (raw['client.version.upgrade'] as VersionEntity) ?? null, - uniVersionList: (raw['client.uni.version.upgrade'] as UniVersionEntity[]) ?? [], + uniVersionList: (raw['client.uni.upgrade.hmos'] as UniVersionEntity[]) ?? [], homeIconEntity: (raw['client.icon.uni.home'] as UniIconEntity[]) ?? [], + homeBanners: visibleHomeBanners(raw['client.banner.home']), wgtPassword: (raw['client.wgt.password'] as string) ?? null, + uniPassword: (raw['client.uni.pwd'] as string) ?? null, + forceUniLogin: (raw['client.user.force.login'] as boolean) ?? false, + agreementDialog: (raw['client.agreement.dialog'] as boolean) ?? true, isUniMpOpen: (raw['client.uni.open'] as boolean) ?? false }; }; @@ -40,7 +45,11 @@ export interface ConfigEntity { versionEntity: VersionEntity | null; uniVersionList: UniVersionEntity[]; homeIconEntity: UniIconEntity[]; + homeBanners?: HomeBannerEntity[]; wgtPassword: string | null; + uniPassword?: string | null; + forceUniLogin?: boolean; + agreementDialog?: boolean; isUniMpOpen: boolean | null; } @@ -57,6 +66,7 @@ export interface VersionEntity { // 用户配置(UniMp版本) export interface UniVersionEntity { + urls?: string[] | null; version: string | null; url: string | null; last_version_force: string | null; @@ -152,4 +162,4 @@ export interface UniMpItem { url: string; // 跳转路径 type: string; // 类型 enable: boolean; // 是否可用 -} \ No newline at end of file +} diff --git a/common/src/main/ets/viewmodel/HomeBannerEntity.ets b/common/src/main/ets/viewmodel/HomeBannerEntity.ets new file mode 100644 index 0000000..5adcb85 --- /dev/null +++ b/common/src/main/ets/viewmodel/HomeBannerEntity.ets @@ -0,0 +1,22 @@ +/** client.banner.home,与 Rabbit-android HomeBannerEntity 字段一致。 */ +export interface HomeBannerEntity { + img?: string | null; + url?: string | null; + type?: string | null; + enable?: boolean | null; + text?: string | null; +} + +export function visibleHomeBanners(value: Object | null | undefined): HomeBannerEntity[] { + if (!Array.isArray(value)) { + return []; + } + const result: HomeBannerEntity[] = []; + for (const item of value as (HomeBannerEntity | null)[]) { + if (item && item.enable === true && typeof item.img === 'string' && item.img.trim().length > 0 && + (item.type === 'wx' || item.type === 'alipay' || item.type === 'app' || item.type === 'web')) { + result.push(item); + } + } + return result; +} diff --git a/common/src/main/ets/viewmodel/LocalBean.ets b/common/src/main/ets/viewmodel/LocalBean.ets index b48fb09..1c81316 100644 --- a/common/src/main/ets/viewmodel/LocalBean.ets +++ b/common/src/main/ets/viewmodel/LocalBean.ets @@ -30,5 +30,6 @@ export class UniMpLocalVersion { type: string = ''; // wx:微信, alipay:阿里 version: string = ''; // 1.0.0 path: string = ''; // data/storage/el2/base/haps/app/files/__UNI__F1F2FC0.wgt + released?: boolean; // 下载完成与解压完成分开记录,防止中断后误用旧资源 } diff --git a/common/src/main/resources/rawfile/unimp-harmony-compat.js b/common/src/main/resources/rawfile/unimp-harmony-compat.js new file mode 100644 index 0000000..450e4fa --- /dev/null +++ b/common/src/main/resources/rawfile/unimp-harmony-compat.js @@ -0,0 +1,57 @@ +/* rabbit-unimp-harmony-compat:v3 */ +// Legacy WGT startup reads these properties before mounting its first page. +// Only fill metadata absent from the Harmony SDK; do not emulate native Android APIs. +(function () { + if (typeof plus !== 'object' || !plus || typeof uni !== 'object' || !uni) return; + + // WGT console forwarding stringifies its arguments. Vue component proxies can + // warn while being stringified, recursively re-entering that same logger. + if (typeof console === 'object' && console) { + ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) { + var descriptor = Object.getOwnPropertyDescriptor(console, level); + if (descriptor && descriptor.configurable === false) return; + function guard(fn) { + if (typeof fn !== 'function') return fn; + var active = false; + return function () { + if (active) return; + active = true; + try { return fn.apply(console, arguments); } finally { active = false; } + }; + } + var current = guard(console[level]); + Object.defineProperty(console, level, { + configurable: true, enumerable: true, + get: function () { return current; }, + set: function (fn) { current = guard(fn); } + }); + }); + } + + function systemInfo() { + try { return uni.getSystemInfoSync() || {}; } catch (_) { return {}; } + } + + function hostVersion() { + try { + var launch = uni.getLaunchOptionsSync(); + var extra = launch && launch.referrerInfo && launch.referrerInfo.extraData; + if (extra && extra['x-version']) return String(extra['x-version']); + } catch (_) {} + try { return String(uni.getAppBaseInfo().hostVersion || ''); } catch (_) { return ''; } + } + + if (!plus.os) { + var info = systemInfo(); + // Reporting Android here would select unsupported plus.android code paths. + plus.os = { name: 'HarmonyOS', version: info.osVersion || info.system || '', language: info.language || '' }; + } + if (!plus.device) { + var device = systemInfo(); + plus.device = { vendor: device.brand || '', model: device.model || '' }; + } + if (plus.runtime && !('version' in plus.runtime)) { + Object.defineProperty(plus.runtime, 'version', { configurable: true, enumerable: true, get: hostVersion }); + } +})(); +/* end-rabbit-unimp-harmony-compat */ diff --git a/features/mainLayout/BuildProfile.ets b/features/mainLayout/BuildProfile.ets index 3753c73..c386046 100644 --- a/features/mainLayout/BuildProfile.ets +++ b/features/mainLayout/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2605180937'; +export const BUILD_TIME = '2611021826'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/features/mainLayout/oh-package-lock.json5 b/features/mainLayout/oh-package-lock.json5 index 40bd91f..0cc9037 100644 --- a/features/mainLayout/oh-package-lock.json5 +++ b/features/mainLayout/oh-package-lock.json5 @@ -6,13 +6,23 @@ "lockfileVersion": 3, "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "specifiers": { - "@ohos/common@../../common": "@ohos/common@../../common" + "@ohos/common@../../common": "@ohos/common@../../common", + "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive": "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive" }, "packages": { "@ohos/common@../../common": { "name": "@ohos/common", "version": "0.0.1", "resolved": "../../common", + "registryType": "local", + "dependencies": { + "libunimp_archive.so": "file:./src/main/cpp/types/libunimp_archive" + } + }, + "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive": { + "name": "libunimp_archive.so", + "version": "1.0.0", + "resolved": "../../common/src/main/cpp/types/libunimp_archive", "registryType": "local" } } diff --git a/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets b/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets index 71d2b16..2dc1785 100644 --- a/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets +++ b/features/mainLayout/oh_modules/@ohos/common/BuildProfile.ets @@ -6,7 +6,7 @@ export const BUILD_MODE_NAME = 'debug'; export const DEBUG = true; export const TARGET_NAME = 'default'; export const CHANNEL = 'harmony'; -export const BUILD_TIME = '2605180937'; +export const BUILD_TIME = '2611021826'; /** * BuildProfile Class is used only for compatibility purposes. diff --git a/features/mainLayout/oh_modules/@ohos/common/build-profile.json5 b/features/mainLayout/oh_modules/@ohos/common/build-profile.json5 index 4f2a475..2e60238 100644 --- a/features/mainLayout/oh_modules/@ohos/common/build-profile.json5 +++ b/features/mainLayout/oh_modules/@ohos/common/build-profile.json5 @@ -1,6 +1,10 @@ { "apiType": "stageMode", "buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "abiFilters": ["arm64-v8a", "x86_64"] + }, "resOptions": { "copyCodeResource": { "enable": false diff --git a/features/mainLayout/oh_modules/@ohos/common/oh-package.json5 b/features/mainLayout/oh_modules/@ohos/common/oh-package.json5 index f2d0749..2493086 100644 --- a/features/mainLayout/oh_modules/@ohos/common/oh-package.json5 +++ b/features/mainLayout/oh_modules/@ohos/common/oh-package.json5 @@ -5,5 +5,7 @@ "main": "Index.ets", "author": "", "license": "Apache-2.0", - "dependencies": {} -} \ No newline at end of file + "dependencies": { + "libunimp_archive.so": "file:./src/main/cpp/types/libunimp_archive" + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/KVManager.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/KVManager.ets index dd6bba9..8516f91 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/KVManager.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/KVManager.ets @@ -3,6 +3,9 @@ import { UNIMP_DATA_VERSION, WX_AUTH_CODE } from '../constants/AppConstants' import { UniMpLocalVersion } from '../viewmodel/LocalBean'; import { KVStore } from './KVStore' import { StringUtils } from './StringUtils'; +import { fileIo as fs } from '@kit.CoreFileKit'; + +let uniMpVersionWrite: Promise = Promise.resolve(); /** * 判断小程序是否需要下载(跳转指定路径) @@ -29,11 +32,11 @@ export async function isUniMpNeedDownloadForPath(uniId: string): Promise { - if(!targetVersion){ - true - } let uniMpVersions = await getUniMpNeedDownload(); let uniMpVersion = uniMpVersions.find(item => {return item.id === uniId}); + if (!uniMpVersion || !isUniMpPackageAvailable(uniMpVersion.path)) { + return true; + } if(!StringUtils.checkVersionLegal(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0') || !StringUtils.isNewVersionAvailable(uniMpVersion?.version??'0.0.0', targetVersion??'0.0.0')){ return false; }else{ @@ -47,26 +50,67 @@ export async function getUniMpNeedDownload(): Promise { let storeJson = await KVStore.getInstance() .get(UNIMP_DATA_VERSION, defaultJson); - let uniMpVersions = JSON.parse(storeJson) as UniMpLocalVersion[]; - return uniMpVersions + try { + const versions = JSON.parse(storeJson) as UniMpLocalVersion[]; + return Array.isArray(versions) ? versions : []; + } catch (_) { + return []; + } } -export async function setUniMpNeedDownload(id: string, type: string, version: string, path: string): Promise { - let uniMpVersions = await getUniMpNeedDownload(); +export function isUniMpPackageAvailable(path: string): boolean { + try { + return path.length > 0 && fs.accessSync(path) && fs.statSync(path).size > 0; + } catch (_) { + return false; + } +} + +export function setUniMpNeedDownload(id: string, type: string, version: string, path: string, + released: boolean = false): Promise { + // 串行读改写,避免微信和支付宝同时完成时互相覆盖版本列表。 + const write = uniMpVersionWrite.then(() => saveUniMpVersion(id, type, version, path, released)); + uniMpVersionWrite = write.catch(() => {}); + return write; +} + +async function saveUniMpVersion(id: string, type: string, version: string, path: string, + released: boolean): Promise { + let uniMpVersions = getUniMpVersionsSync(); let uniMpVersion = uniMpVersions.find(item => {return item.id === id}); if(uniMpVersion){ uniMpVersion.type = type; uniMpVersion.version = version; uniMpVersion.path = path; + uniMpVersion.released = released; }else{ uniMpVersions.push({ id: id, type: type, version: version, - path: path + path: path, + released: released }); } - KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(uniMpVersions)) + await KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(uniMpVersions)) +} + +function getUniMpVersionsSync(): UniMpLocalVersion[] { + try { + const versions = JSON.parse(KVStore.getInstance().getSync(UNIMP_DATA_VERSION, '[]')) as UniMpLocalVersion[]; + return Array.isArray(versions) ? versions : []; + } catch (_) { + return []; + } +} + +export function clearUniMpVersion(id: string): Promise { + const write = uniMpVersionWrite.then(async () => { + const versions = getUniMpVersionsSync().filter((item: UniMpLocalVersion) => item.id !== id); + await KVStore.getInstance().put(UNIMP_DATA_VERSION, JSON.stringify(versions)); + }); + uniMpVersionWrite = write.catch(() => {}); + return write; } export function setWechatAuthCode(wechatCode: string): void { @@ -75,4 +119,4 @@ export function setWechatAuthCode(wechatCode: string): void { export async function getWechatAuthCode(): Promise { return await KVStore.getInstance().get(WX_AUTH_CODE, '') -} \ No newline at end of file +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/StringUtils.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/StringUtils.ets index e2ad63e..a248f35 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/StringUtils.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/StringUtils.ets @@ -1,6 +1,5 @@ import { pasteboard } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; -import { promptAction } from '@kit.ArkUI'; import { Logger } from './Logger'; import { ToastUtils } from '../dialog/ToastUtils'; diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets index 072ba43..d900815 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpManager.ets @@ -1,199 +1,263 @@ -import { openUniMP, releaseWgtToRunPath, UniMP } from '@dcloudio/uni-app-runtime' -import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN } from '../constants/AppConstants' -import { ToastUtils } from '../dialog/ToastUtils' -import { UniVersionEntity,TradeData, UniIconEntity } from '../viewmodel/DataBean' -import { downloadFile } from './DownloaderUtils' -import { isUniMpNeedDownload, isUniMpNeedDownloadForPath, setUniMpNeedDownload } from './KVManager' -import { KVStore } from './KVStore' -import { Logger } from './Logger' -import { bundleManager, common } from '@kit.AbilityKit' -import { DeviceUtil } from '@pura/harmony-utils' -import { deviceInfo } from '@kit.BasicServicesKit' -import { CHANNEL } from '../../../../BuildProfile' -import { CommonService } from '../viewmodel/CommonService' +import { isExistsUniMP, openUniMP, UniMP } from '@dcloudio/uni-app-runtime'; +import { AESDecrypt, PLATFORM, RELEASE_BASE_URL, Signature, TOKEN, TOKEN_LOGIN, USER_PROFILE } from '../constants/AppConstants'; +import { ToastUtils } from '../dialog/ToastUtils'; +import { UniVersionEntity, TradeData, UniIconEntity, UserProfile } from '../viewmodel/DataBean'; +import { clearUniMpVersion, getUniMpNeedDownload, isUniMpPackageAvailable, setUniMpNeedDownload } from './KVManager'; +import { KVStore } from './KVStore'; +import { Logger } from './Logger'; +import { bundleManager, common } from '@kit.AbilityKit'; +import { AppUtil, DeviceUtil } from '@pura/harmony-utils'; +import { deviceInfo } from '@kit.BasicServicesKit'; +import { CHANNEL } from '../../../../BuildProfile'; +import { CommonService } from '../viewmodel/CommonService'; +import { routerLogin } from '../router/RouterManager'; +import { downloadUniMp, removeUniMpPackage } from './UniMpDownloader'; +import { getUniMpReleasePassword, getUniMpUpdate, UniMpUpdate } from './UniMpPolicy'; +import { reportUniMp } from './UniMpReporter'; +import { releaseUniMpWgt } from './UniMpRelease'; +import { UniMpRuntimeCompat } from './UniMpRuntimeCompat'; -/** - * 下载并启动模拟器 - * @param context - * @param entity - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function downStartUp(context: UIContext, entity: UniVersionEntity, callback: (status: number, progress: number, path?: string) => void) { - let uniMpId = entity.unimp_id;//'__UNI__D535736'; - let uniMpType = entity.unimp_type; - let uniMpUrl = entity.url;//'https://cdn.batiao8.com/flaunt/uni_mp/wgt/alipay/__UNI__D535736_2026-4-20-test4.wgt'; - let uniVersion = entity.version??'0.0.0'; - if(uniMpId){ - isUniMpNeedDownload(uniMpId, uniVersion).then(res => { - if(res == true){ - callback(1, 0) - //需要更新,则删除旧文件,重新下载wgt文件 - if(!uniMpId){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); +// 保留原有状态值,所有入口共享同一下载、解压和启动流程。 +export enum UniMpStatus { + FAILURE = -1, + IDLE = 0, + DOWNLOADING = 1, + DOWNLOADED = 2, + STARTED = 3, + RELEASED = 4, + RELEASE_FAILURE = 5, + RELEASING = 6, + BUSY = 7, + LOGIN = 8, + UPDATE_PROMPT = 9, + OPENING = 10 +} +type UniMpCallback = (status: number, progress: number, path?: string) => void; +const runningApps = new Map(); +const pendingApps = new Set(); - callback(-1, 0); - return - } - - //下载模拟器 - downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => { - if(status == 2){ - callback(status, progress, path); - //已下载完成,释放并启动 - releaseRunUniMp(context, uniMpId??'', '', (status) => { - callback(status, progress, path); - }) - }else if(status == -1){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); - callback(status, progress, path); - }else{ - callback(status, progress, path); - } - Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress); - }) - }else{ - //不需要更新,已释放则直接打开模拟器,否则先释放,再打开 - runUniMp(context, uniMpId??'', '', (status) => { - callback(status, 100); - }) - } - }); - } - Logger.info('UniMp','uniMpId:'+uniMpId+ ', uniMpType:' + uniMpType + ', uniMpUrl:' + uniMpUrl + ', uniMpVersion:' + uniVersion); +export function downStartUp(context: UIContext, entity: UniVersionEntity, callback: UniMpCallback): void { + startOpenUniMp(context, entity, '', 'home', callback); } -export function downStartUpForPath(context: UIContext, uniMpVersions: UniVersionEntity[], uniIconEntity: UniIconEntity, callback: (status: number, progress: number, path?: string) => void) { - const uniMpType = uniIconEntity.type - const uniMpEntity = uniMpVersions.find((item: UniVersionEntity) => { - return item.unimp_type === uniMpType; - }); +export function downStartUpForPath(context: UIContext, versions: UniVersionEntity[], icon: UniIconEntity, + callback: UniMpCallback): void { + if (!icon.enable) { + callback(UniMpStatus.IDLE, 0); + return; + } + const entity = versions.find((item: UniVersionEntity) => item.unimp_type === icon.type); + if (!entity) { + failWithToast(context, callback); + return; + } + startOpenUniMp(context, entity, icon.url ?? '', icon.text ?? '', callback); +} - const targetPath = uniIconEntity.url??''; - const uniMpUrl = uniMpEntity?.url??''; - const uniMpId = uniMpEntity?.unimp_id??''; - const uniMpVersion = uniMpEntity?.version??''; - isUniMpNeedDownloadForPath(uniMpId).then(res => { - if(res == true){ - // 已释放,直接运行 - runUniMp(context, uniMpId??'', '', (status) => { - callback(status, 100); - }) - }else{ - // 未下载,先下载释放,再运行 - downloadFile(getContext(), uniMpUrl??'', uniMpId + '.wgt', (status, progress, path) => { - if(status == 2){ - // 设置下载的版本信信 - setUniMpNeedDownload(uniMpId??'', uniMpType??'', uniMpVersion??'', path??''); - callback(status, progress, path); - // 已下载完成,释放并启动 - releaseRunUniMp(context, uniMpId??'', targetPath, (status) => { - callback(status, progress, path); - }) - }else if(status == -1){ - ToastUtils.showToast(context, '加载失败,请重试或联系客服!') - callback(status, progress, path); - }else{ - callback(status, progress, path); - } - Logger.info('UniMp','downloadFile status:' + status + ', progress:' + progress); - }) +async function startOpenUniMp(context: UIContext, entity: UniVersionEntity, targetPath: string, itemName: string, + callback: UniMpCallback): Promise { + const id = entity.unimp_id ?? ''; + if (!/^[A-Za-z0-9_-]+$/.test(id)) { + reportUniMp('error', 'client.uni.fail', id, '上报原因:小程序ID为空或无效'); + failWithToast(context, callback); + return; + } + const profile = AppStorage.get(USER_PROFILE); + if (profile?.config?.forceUniLogin && !KVStore.getInstance().getSync(TOKEN_LOGIN, '')) { + callback(UniMpStatus.LOGIN, 0); + routerLogin('unimp', false); + return; + } + reportUniMp('click', entity.unimp_type === 'wx' ? 'event_client_open_wx_unimp' : 'event_client_open_alipay_unimp', itemName); + if (pendingApps.has(id)) { + callback(UniMpStatus.BUSY, 0); + ToastUtils.showToast(context, '请等待模拟器更新完毕!'); + return; + } + pendingApps.add(id); + try { + const running = runningApps.get(id); + if (running) { + try { + running.show(); + running.sendUniMPEvent('token', KVStore.getInstance().getSync(TOKEN, '')); + running.sendUniMPEvent('jump', targetPath); + callback(UniMpStatus.STARTED, 100); + return; + } catch (error) { + runningApps.delete(id); + try { running.close(); } catch (_) {} + Logger.info('UniMp', '恢复小程序失败,重新启动: ' + (error as Error).message); + } + } + const path = getContext().filesDir + '/' + id + '.wgt'; + const versions = await getUniMpNeedDownload(); + const local = versions.find((item) => item.id === id); + const update = getUniMpUpdate(entity, local?.version ?? '0.0.0', isUniMpPackageAvailable(path)); + let shouldDownload = update === UniMpUpdate.REQUIRED; + if (update === UniMpUpdate.OPTIONAL) { + callback(UniMpStatus.UPDATE_PROMPT, 0); + shouldDownload = await confirmUpdate(context); + reportUniMp('click', shouldDownload ? 'client.confirm.download.unimp' : 'client.cancel.download.unimp', + '', JSON.stringify(entity)); + } + if (shouldDownload) { + try { + await downloadUniMp(getContext(), entity, (progress: number) => callback(UniMpStatus.DOWNLOADING, progress)); + await setUniMpNeedDownload(id, entity.unimp_type ?? '', entity.version ?? '', path, false); + } catch (error) { + Logger.info('UniMp', '下载失败: ' + (error as Error).message); + failWithToast(context, callback); + return; + } + callback(UniMpStatus.DOWNLOADED, 100, path); + } + // 取消更新时使用旧版本,页面不能再写入远端版本。 + const version = shouldDownload ? entity.version ?? '' : local?.version ?? '0.0.0'; + await releaseAndOpen(context, entity, targetPath, path, version, + shouldDownload || local?.released !== true, callback); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.fail', id, '上报原因:启动小程序异常 ' + (error as Error).message); + failWithToast(context, callback); + } finally { + pendingApps.delete(id); + } +} + +async function confirmUpdate(context: UIContext): Promise { + try { + const result = await context.getPromptAction().showDialog({ + title: '资源包更新', + message: '是否确定更新资源包', + buttons: [{ text: '取消', color: '#666666' }, { text: '确定', color: '#4F8AF6' }] + }); + return result.index === 1; + } catch (_) { + // 返回键或点击遮罩与取消按钮一致,继续打开本地版本。 + return false; + } +} + +async function releaseAndOpen(context: UIContext, entity: UniVersionEntity, targetPath: string, path: string, + version: string, forceRelease: boolean, callback: UniMpCallback): Promise { + const id = entity.unimp_id ?? ''; + if (forceRelease || !isExistsUniMP(id)) { + callback(UniMpStatus.RELEASING, 100, path); + try { + if (!isUniMpPackageAvailable(path)) { + throw new Error('本地资源包不存在或为空'); + } + const config = AppStorage.get(USER_PROFILE)?.config; + const password = getUniMpReleasePassword(config?.wgtPassword ?? '', config?.uniPassword ?? ''); + await releaseUniMpWgt(id, path, password); + await setUniMpNeedDownload(id, entity.unimp_type ?? '', version, path, true); + callback(UniMpStatus.RELEASED, 100, path); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.release.wgt', id, (error as Error).message); + failWithToast(context, callback, UniMpStatus.RELEASE_FAILURE); + return; + } + } + callback(UniMpStatus.OPENING, 100, path); + try { + // 已缓存/已解压的旧包也要处理,不能只在新包解压后修复。 + await UniMpRuntimeCompat.prepare(getContext() as common.Context, id); + const config = await uniMpConfig(context); + const mp = openUniMP(id, { + redirectPath: targetPath, + extraData: config, + showCapsuleButton: false, + showSplashScreen: true + }) as UniMP; + if (!mp) { + throw new Error('启动小程序失败'); + } + runningApps.set(id, mp); + registerEvents(id, mp); + // 与 Android 一致,获得实例就结束启动状态,show 事件不重复结束请求。 + callback(UniMpStatus.STARTED, 100, path); + } catch (error) { + await invalidatePackage(id); + reportUniMp('error', 'client.uni.fail', id, '上报原因:启动小程序失败 ' + (error as Error).message); + failWithToast(context, callback); + } +} + +function registerEvents(id: string, mp: UniMP): void { + mp.on('close', () => { + if (runningApps.get(id) === mp) { + runningApps.delete(id); + } + Logger.info('UniMp', 'close: ' + id); + }); + mp.on('show', () => Logger.info('UniMp', 'show: ' + id)); + mp.on('hide', () => Logger.info('UniMp', 'hide: ' + id)); + mp.on('uniMPEvent', (event: string, data: object) => { + Logger.info('UniMp', 'uniMPEvent: ' + event); + try { + if (event === 'start_combo_pay') { + const trade = JSON.parse(typeof data === 'string' ? data : JSON.stringify(data)) as TradeData; + CommonService.startUniPay(getContext() as common.UIAbilityContext, trade.weixinMpOriId ?? '', trade.outTradeNo ?? ''); + } else if (event === 'closeUniAPP') { + runningApps.delete(id); + mp.close(); + } + } catch (error) { + reportUniMp('error', 'client.uni.fail', id, '小程序事件 ' + event + ' 处理异常: ' + (error as Error).message); } }); } -/** - * 运行模拟器 - * 1、如已释放,直接运行 - * 2、如未释放,先释放,再运行 - * @param uniMpId 小程序ID - * @param targetPath 跳转小程序路径 - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function runUniMp(context: UIContext, uniMpId: string, targetPath:string, callback: (status: number) => void){ - releaseRunUniMp(context, uniMpId, targetPath, callback) -} -/** - * 释放并运行,需要先释放,再运行 - * 1、删除旧文件 - * 2、先释放,再运行 - * @param uniMpId 小程序ID - * @param targetPath 跳转小程序路径 - * 注意:status: -1-失败, 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), 3-启动, 4-释放成功, 5-释放失败 - */ -export function releaseRunUniMp(context: UIContext, uniMpId: string, targetPath: string, callback: (status: number) => void){ - let path = getContext().filesDir + "/"+uniMpId+".wgt" - uniMpConfig().then(res => { - releaseWgtToRunPath(uniMpId, path, (code: 1 | -1, _) =>{ - if(code === 1){ - callback(4) - // 释放成功,运行 - const mp = openUniMP(uniMpId, { - redirectPath: targetPath, - extraData: res, - showCapsuleButton: false, - showSplashScreen: true, - }) as UniMP - - mp.on('close',()=>{ - console.log('UniMP-close') - }) - mp.on('show',()=>{ - console.log('UniMP-show') - callback(3) - }) - mp.on('hide',()=>{ - console.log('UniMP-hide') - }) - mp.on('uniMPEvent', (event: string, data: object, _notify: boolean) => { - Logger.info('UniMp', 'uniMPEvent:' + event + ', data:' + data) - - if(event === 'openUniAPP'){ - //渲染完成 - }else if(event === 'start_combo_pay'){ - const jsonStr = typeof data === 'string' ? data : JSON.stringify(data); - const obj = JSON.parse(jsonStr) as TradeData; - - const weixinMpOriId: string = obj.weixinMpOriId ?? ""; - const outTradeNo: string = obj.outTradeNo ?? ""; - CommonService.startUniPay(getContext() as common.UIAbilityContext, weixinMpOriId, outTradeNo) - }else if(event === 'closeUniAPP'){ - mp.close() - } - }) - }else{ - // 释放失败,提示用户 - ToastUtils.showToast(context, '加载失败,请重试或联系客服!') - callback(5) - } - }) - }) +async function invalidatePackage(id: string): Promise { + const mp = runningApps.get(id); + runningApps.delete(id); + try { mp?.close(); } catch (_) {} + try { + removeUniMpPackage(getContext().filesDir + '/' + id + '.wgt'); + } catch (error) { + Logger.info('UniMp', '清理资源包失败: ' + (error as Error).message); + } + await clearUniMpVersion(id); } -async function uniMpConfig(): Promise>{ - let extraData: Record = {}; +function failWithToast(context: UIContext, callback: UniMpCallback, status: UniMpStatus = UniMpStatus.FAILURE): void { + callback(status, 0); + ToastUtils.showToast(context, '加载失败,请重试或联系客服!'); +} +export function closeUniMpApps(): void { + runningApps.forEach((mp: UniMP) => { + try { mp.close(); } catch (_) {} + }); + runningApps.clear(); +} + +async function uniMpConfig(context: UIContext): Promise> { const bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); - const versionName = bundleInfo.versionName; - const bundleName = bundleInfo.name; - - const accessToken: string = KVStore.getInstance().getSync(TOKEN, ''); - const deviceId: string = DeviceUtil.getDeviceId(); - const brand: string = deviceInfo.brand; - const model: string = deviceInfo.productModel; - - extraData["x-token"] = accessToken; - extraData["x-version"] = versionName; - extraData["x-platform"] = PLATFORM; - extraData["x-device-id"] = deviceId; - extraData["x-mobile-brand"] = brand; - extraData["x-mobile-model"] = model; - extraData["x-channel"] = CHANNEL; - extraData["x-package"] = bundleName; - extraData["x-click-id"] = ''; - extraData["host"] = RELEASE_BASE_URL + '/'; - extraData["decrypt"] = AESDecrypt; - extraData["encrypt"] = Signature; - extraData["isCombo"] = 'ok'; - - return extraData -} \ No newline at end of file + let safeBottom = 0; + try { + safeBottom = Math.max(0, Math.round(context.px2vp(AppUtil.getNavigationIndicatorHeight()))); + } catch (_) { + // 无导航指示条或窗口尚未就绪时仍传有效值,避免旧 WGT 在 onLaunch 中读取 undefined。 + } + const extraData: Record = { + 'x-token': KVStore.getInstance().getSync(TOKEN, ''), + 'x-version': bundleInfo.versionName, + 'x-platform': PLATFORM, + 'x-device-id': DeviceUtil.getDeviceId(), + 'x-mobile-brand': deviceInfo.brand, + 'x-mobile-model': deviceInfo.productModel, + 'x-channel': CHANNEL, + 'x-package': bundleInfo.name, + 'x-click-id': '', + 'host': RELEASE_BASE_URL + '/', + 'decrypt': AESDecrypt, + 'encrypt': Signature, + 'isCombo': 'ok' + }; + // WGT 内部用 Number() 计算避让,并直接将该值传给 showModal.content,需提供字符串。 + extraData['safeBottom'] = String(safeBottom); + return extraData; +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/CommonService.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/CommonService.ets index e54bd7a..9704093 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/CommonService.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/CommonService.ets @@ -3,7 +3,7 @@ import deviceInfo from "@ohos.deviceInfo"; import { DeviceUtil } from "@pura/harmony-utils"; import { Logger } from "../utils/Logger"; import { ApiManager } from "../provider/ApiManager"; -import { DEVICE_OAID, LOGIN_PROFILE, TOKEN, TOKEN_LOGIN, USER_INFO, USER_PROFILE, +import { DEVICE_OAID, LOGIN_PROFILE, PLATFORM, TOKEN, TOKEN_LOGIN, USER_INFO, USER_PROFILE, WXAPPID} from "../constants/AppConstants"; import { KVStore } from "../utils/KVStore"; import { RequestCallback } from "../provider/Callback"; @@ -11,6 +11,7 @@ import { EVT_USER_INFO,EVT_USER_CONFIG_PROFILE } from "../constants/EventConstan import { emitter } from "@kit.BasicServicesKit"; import { AFAuthServiceResponse, AFService, AFServiceCenter, AFServiceParams, AFWantParams } from "@alipay/afservicesdk"; import { common } from "@kit.AbilityKit"; +import { loginComponentManager } from "@kit.AccountKit"; import { ToastUtils } from "../dialog/ToastUtils"; import * as wxopensdk from '@tencent/wechat_open_sdk'; @@ -67,7 +68,7 @@ export class CommonService { }; const result = await ApiManager.getInstance().request( - 'api/user/code', // api + '/api/user/code', // api undefined, // get请求参数,会拼接到url中 'post', // 请求方式 postParms // post请求参数 @@ -130,14 +131,16 @@ export class CommonService { ); if(result.code === 200 || result.code === 0){ - const token = result.data.token - if(token && token.length > 0){ - //将登录信息持久化(const savedProfile = JSON.parse(rawJson) as LoginProfile;) - const loginJson: string = JSON.stringify(result); - KVStore.getInstance().put(LOGIN_PROFILE, loginJson); //持久化登录信息 - KVStore.getInstance().put(TOKEN_LOGIN, token ?? ''); //持久化token - KVStore.getInstance().put(TOKEN, token ?? ''); //持久化token + const token = result.data?.token; + if (!token || token.length === 0) { + callback?.onFailure?.('登录失败,请重新登录'); + return; } + // 保存完成后再刷新用户信息,确保后续请求使用新 token。 + const loginJson: string = JSON.stringify(result); + await KVStore.getInstance().put(LOGIN_PROFILE, loginJson); + await KVStore.getInstance().put(TOKEN_LOGIN, token); + await KVStore.getInstance().put(TOKEN, token); if (callback && callback.onSuccess) { callback.onSuccess(result.data); } @@ -221,12 +224,60 @@ export class CommonService { } } + /** + * 对齐 weiquan-har LoginViewModel.loginByHuawei:type + bind + data.code。 + */ + static async huaweiLogin(credential: loginComponentManager.HuaweiIDCredential, + callback?: RequestCallback, bind: boolean = false): Promise { + if (!credential?.authorizationCode?.trim()) { + callback?.onFailure?.('华为账号未返回授权码,请重试或使用短信验证码登录'); + return; + } + const huaweiData: Record = { 'code': credential.authorizationCode }; + const postData: Record = { + 'type': 'huawei', + 'bind': bind ? true : '', + 'data': huaweiData + }; + try { + const result = await ApiManager.getInstance().request( + '/api/user/login', undefined, 'post', postData); + if (result.code !== 0) { + callback?.onFailure?.(result.message || '登录失败,请重试或使用短信验证码登录'); + return; + } + const token = result.data?.token; + if (!token?.trim()) { + callback?.onFailure?.('登录失败,请重试或使用短信验证码登录'); + return; + } + await KVStore.getInstance().put(LOGIN_PROFILE, JSON.stringify(result)); + await KVStore.getInstance().put(TOKEN_LOGIN, token); + await KVStore.getInstance().put(TOKEN, token); + // 与参考项目一致,使用新 token 刷新配置后才返回成功;刷新失败不撤销登录。 + try { + await CommonService.getUserProfile(); + } catch (_) { + Logger.info('HuaweiLogin', '登录成功,配置刷新失败,保留有效登录凭证'); + } + const report: Record = { + 'source': PLATFORM, 'type': 'click', 'key': 'client.login', 'value': 'huawei', 'extra': '' + }; + ApiManager.getInstance().request('/api/user/event', undefined, 'post', report).catch(() => { + Logger.info('HuaweiLogin', '登录事件上报失败'); + }); + callback?.onSuccess?.(result.data); + } catch (error) { + callback?.onError?.(error as Error); + } + } + /** * 获取支付宝登录参数 */ static async getAlipayLoginParams(): Promise { const result = await ApiManager.getInstance().request( - 'api/alipay/app_param', + '/api/alipay/app_param', undefined, undefined ); @@ -296,4 +347,4 @@ export class CommonService { WXApi.sendReq(context, req) } -} \ No newline at end of file +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/DataBean.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/DataBean.ets index 62e50d8..81a2732 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/DataBean.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/DataBean.ets @@ -1,4 +1,5 @@ import ArrayList from "@ohos.util.ArrayList"; +import { HomeBannerEntity, visibleHomeBanners } from './HomeBannerEntity'; /** * UserProfile 的专属转换器 @@ -19,9 +20,13 @@ export const UserProfileMapper = (raw: Record): UserProfile => { export const ConfigMapper = (raw: Record): ConfigEntity => { return { versionEntity: (raw['client.version.upgrade'] as VersionEntity) ?? null, - uniVersionList: (raw['client.uni.version.upgrade'] as UniVersionEntity[]) ?? [], + uniVersionList: (raw['client.uni.upgrade.hmos'] as UniVersionEntity[]) ?? [], homeIconEntity: (raw['client.icon.uni.home'] as UniIconEntity[]) ?? [], + homeBanners: visibleHomeBanners(raw['client.banner.home']), wgtPassword: (raw['client.wgt.password'] as string) ?? null, + uniPassword: (raw['client.uni.pwd'] as string) ?? null, + forceUniLogin: (raw['client.user.force.login'] as boolean) ?? false, + agreementDialog: (raw['client.agreement.dialog'] as boolean) ?? true, isUniMpOpen: (raw['client.uni.open'] as boolean) ?? false }; }; @@ -40,7 +45,11 @@ export interface ConfigEntity { versionEntity: VersionEntity | null; uniVersionList: UniVersionEntity[]; homeIconEntity: UniIconEntity[]; + homeBanners?: HomeBannerEntity[]; wgtPassword: string | null; + uniPassword?: string | null; + forceUniLogin?: boolean; + agreementDialog?: boolean; isUniMpOpen: boolean | null; } @@ -57,6 +66,7 @@ export interface VersionEntity { // 用户配置(UniMp版本) export interface UniVersionEntity { + urls?: string[] | null; version: string | null; url: string | null; last_version_force: string | null; @@ -152,4 +162,4 @@ export interface UniMpItem { url: string; // 跳转路径 type: string; // 类型 enable: boolean; // 是否可用 -} \ No newline at end of file +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/LocalBean.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/LocalBean.ets index b48fb09..1c81316 100644 --- a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/LocalBean.ets +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/LocalBean.ets @@ -30,5 +30,6 @@ export class UniMpLocalVersion { type: string = ''; // wx:微信, alipay:阿里 version: string = ''; // 1.0.0 path: string = ''; // data/storage/el2/base/haps/app/files/__UNI__F1F2FC0.wgt + released?: boolean; // 下载完成与解压完成分开记录,防止中断后误用旧资源 } diff --git a/features/mainLayout/src/main/ets/pages/SettingLayout.ets b/features/mainLayout/src/main/ets/pages/SettingLayout.ets index 818081b..0c0c0b3 100644 --- a/features/mainLayout/src/main/ets/pages/SettingLayout.ets +++ b/features/mainLayout/src/main/ets/pages/SettingLayout.ets @@ -1,4 +1,3 @@ -import { promptAction } from '@kit.ArkUI'; import { fileIo, storageStatistics } from '@kit.CoreFileKit'; import { TipsDialog } from '@ohos/common/src/main/ets/dialog/TipsDialog'; import { TitleBarComponent } from '../view/TitleBarComponent'; diff --git a/oh-package-lock.json5 b/oh-package-lock.json5 index 989a6a4..33c7fa6 100644 --- a/oh-package-lock.json5 +++ b/oh-package-lock.json5 @@ -12,24 +12,31 @@ "@candies/image_editor@^1.0.0": "@candies/image_editor@1.0.0", "@cashier_alipay/cashiersdk@15.8.24": "@cashier_alipay/cashiersdk@15.8.43", "@cashier_alipay/cashiersdk@^15.8.43": "@cashier_alipay/cashiersdk@15.8.43", - "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony": "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony", - "@dcloudio/uni-app-runtime@^4.75.2025071101": "@dcloudio/uni-app-runtime@4.84.2025110301", - "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk": "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk", + "@dcloudio/uni-app-framework@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/framework": "@dcloudio/uni-app-framework@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/framework", + "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony": "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony", + "@dcloudio/uni-app-modules@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/modules": "@dcloudio/uni-app-modules@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/modules", + "@dcloudio/uni-app-runtime@5.14.2026070201": "@dcloudio/uni-app-runtime@5.14.2026070201", + "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk": "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk", + "@ohos/aki@1.2.13": "@ohos/aki@1.2.13", "@ohos/axios@^2.2.8": "@ohos/axios@2.2.8", "@ohos/crypto-js@2.0.0": "@ohos/crypto-js@2.0.5", "@ohos/crypto-js@^2.0.4": "@ohos/crypto-js@2.0.5", "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0", "@ohos/hypium@1.0.25": "@ohos/hypium@1.0.25", - "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har": "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har", + "@ohos/minizip@1.0.6": "@ohos/minizip@1.0.6", + "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har": "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har", "@pura/harmony-utils@^1.4.0": "@pura/harmony-utils@1.4.0", "@pura/picker_utils@^1.0.2": "@pura/picker_utils@1.0.2", "@taobao-ohos/utdid_sdk@oh_modules/.ohpm/@cashier_alipay+cashiersdk@15.8.43/oh_modules/@cashier_alipay/cashiersdk/lib/utdid_sdk-1.2.5.har": "@taobao-ohos/utdid_sdk@oh_modules/.ohpm/@cashier_alipay+cashiersdk@15.8.43/oh_modules/@cashier_alipay/cashiersdk/lib/utdid_sdk-1.2.5.har", "@tencent/wechat_open_sdk@^1.0.16": "@tencent/wechat_open_sdk@1.0.16", "@uni_modules/uni-payment-alipay@^1.0.2": "@uni_modules/uni-payment-alipay@1.0.2", "libblueshield.so@oh_modules/.ohpm/@alipay+blueshieldsdk@qgf9fllog8tazdv8uop120fy3saz8l+7jb55+sipesk=/oh_modules/@alipay/blueshieldsdk/src/main/cpp/types/libblueshield": "libblueshield.so@oh_modules/.ohpm/@alipay+blueshieldsdk@qgf9fllog8tazdv8uop120fy3saz8l+7jb55+sipesk=/oh_modules/@alipay/blueshieldsdk/src/main/cpp/types/libblueshield", - "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime": "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime", + "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime": "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime", + "libminizip_ng.so@oh_modules/.ohpm/@ohos+minizip@1.0.6/oh_modules/@ohos/minizip/src/main/cpp/types/libminizip_ng": "libminizip_ng.so@oh_modules/.ohpm/@ohos+minizip@1.0.6/oh_modules/@ohos/minizip/src/main/cpp/types/libminizip_ng", + "libuni_modules__uni_crash_lib.so@oh_modules/.ohpm/uni_modules__uni_crash_lib@52lbsbiymmolbsgju3dusxipv9esdf4ryhndsun2mk8=/oh_modules/uni_modules__uni_crash_lib/src/main/cpp/types/libuni_modules__uni_crash_lib": "libuni_modules__uni_crash_lib.so@oh_modules/.ohpm/uni_modules__uni_crash_lib@52lbsbiymmolbsgju3dusxipv9esdf4ryhndsun2mk8=/oh_modules/uni_modules__uni_crash_lib/src/main/cpp/types/libuni_modules__uni_crash_lib", "libutdid_native.so@oh_modules/.ohpm/@taobao-ohos+utdid_sdk@ecjyoomnzz6zaipo1koz9+avemnpw7+togfp5uwrtiu=/oh_modules/@taobao-ohos/utdid_sdk/src/main/cpp/types/libutdid_native": "libutdid_native.so@oh_modules/.ohpm/@taobao-ohos+utdid_sdk@ecjyoomnzz6zaipo1koz9+avemnpw7+togfp5uwrtiu=/oh_modules/@taobao-ohos/utdid_sdk/src/main/cpp/types/libutdid_native", - "pako@^2.1.0": "pako@2.1.0" + "pako@^2.1.0": "pako@2.1.0", + "uni_modules__uni_crash_lib@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/uni_modules__uni_crash_lib.har": "uni_modules__uni_crash_lib@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/uni_modules__uni_crash_lib.har" }, "packages": { "@alipay/afservicesdk@libs/AFServiceSDK.har": { @@ -79,31 +86,53 @@ "pako": "^2.1.0" } }, - "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony": { - "name": "@dcloudio/uni-app-harmony", + "@dcloudio/uni-app-framework@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/framework": { + "name": "@dcloudio/uni-app-framework", "version": "1.0.0", - "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/framework", "registryType": "local" }, - "@dcloudio/uni-app-runtime@4.84.2025110301": { + "@dcloudio/uni-app-harmony@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony": { + "name": "@dcloudio/uni-app-harmony", + "version": "1.0.0", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-app-harmony", + "registryType": "local" + }, + "@dcloudio/uni-app-modules@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/modules": { + "name": "@dcloudio/uni-app-modules", + "version": "1.0.0", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/modules", + "registryType": "local" + }, + "@dcloudio/uni-app-runtime@5.14.2026070201": { "name": "@dcloudio/uni-app-runtime", - "version": "4.84.2025110301", - "integrity": "sha512-rvU2eXsjGYKQ9rdCh/fcOSI+61iTEpc8UWAzgq1291UTjpIVyM+gk2tc4GUyJpq+Kea44pSrohuetYtu5wQGFQ==", - "resolved": "https://ohpm.openharmony.cn/ohpm/@dcloudio/uni-app-runtime/-/uni-app-runtime-4.84.2025110301.har", + "version": "5.14.2026070201", + "integrity": "sha512-cUCI9NsbQW/YBKEAD1DSvBJpgd6m9n/bamwNK4A20ROW+6HthFpMVs6N6B7V77j8YuxY1yy8bzK3DjiWTt4Wyw==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@dcloudio/uni-app-runtime/-/uni-app-runtime-5.14.2026070201.har", "registryType": "ohpm", "dependencies": { "libjsruntime.so": "./src/main/cpp/types/libjsruntime", "@dcloudio/uni-app-harmony": "./src/main/ets/uni-app-harmony", + "@dcloudio/uni-app-modules": "./src/main/ets/modules", "@dcloudio/uni-mp-sdk": "./src/main/ets/uni-mp-sdk", - "@ohos/videocompressor": "file:./libs/videoCompressor.har" + "@dcloudio/uni-app-framework": "./src/main/ets/framework", + "@ohos/videocompressor": "file:./libs/videoCompressor.har", + "uni_modules__uni_crash_lib": "./libs/uni_modules__uni_crash_lib.har" } }, - "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk": { + "@dcloudio/uni-mp-sdk@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk": { "name": "@dcloudio/uni-mp-sdk", "version": "1.0.0", - "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/ets/uni-mp-sdk", "registryType": "local" }, + "@ohos/aki@1.2.13": { + "name": "@ohos/aki", + "version": "1.2.13", + "integrity": "sha512-lqETaoQC+K1e7h1gP6P31vsOGiB/T6jdcuPUz9b6nolu4Ij0lIyL6Pkp7Y+fbuls5kMBB1rQgxc/Ixg3pIklXA==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/aki/-/aki-1.2.13.har", + "registryType": "ohpm" + }, "@ohos/axios@2.2.8": { "name": "@ohos/axios", "version": "2.2.8", @@ -132,10 +161,21 @@ "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.25.har", "registryType": "ohpm" }, - "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har": { + "@ohos/minizip@1.0.6": { + "name": "@ohos/minizip", + "version": "1.0.6", + "integrity": "sha512-uRlxAPcR2grl+t48waIhDjiO598Tp+xUPCIV+9uvVRZsUwnjA/dKiLrIudQYDN66HsF3Sw9SQ1qspalcvnrlIQ==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/minizip/-/minizip-1.0.6.har", + "registryType": "ohpm", + "dependencies": { + "libminizip_ng.so": "file:./src/main/cpp/types/libminizip_ng", + "@ohos/aki": "1.2.13" + } + }, + "@ohos/videocompressor@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har": { "name": "@ohos/videocompressor", "version": "1.0.4", - "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/videoCompressor.har", "registryType": "local" }, "@pura/harmony-utils@1.4.0": { @@ -185,10 +225,22 @@ "resolved": "oh_modules/.ohpm/@alipay+blueshieldsdk@qgf9fllog8tazdv8uop120fy3saz8l+7jb55+sipesk=/oh_modules/@alipay/blueshieldsdk/src/main/cpp/types/libblueshield", "registryType": "local" }, - "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime": { + "libjsruntime.so@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime": { "name": "libjsruntime.so", "version": "1.0.0", - "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@4.84.2025110301/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/src/main/cpp/types/libjsruntime", + "registryType": "local" + }, + "libminizip_ng.so@oh_modules/.ohpm/@ohos+minizip@1.0.6/oh_modules/@ohos/minizip/src/main/cpp/types/libminizip_ng": { + "name": "libminizip_ng.so", + "version": "0.0.0", + "resolved": "oh_modules/.ohpm/@ohos+minizip@1.0.6/oh_modules/@ohos/minizip/src/main/cpp/types/libminizip_ng", + "registryType": "local" + }, + "libuni_modules__uni_crash_lib.so@oh_modules/.ohpm/uni_modules__uni_crash_lib@52lbsbiymmolbsgju3dusxipv9esdf4ryhndsun2mk8=/oh_modules/uni_modules__uni_crash_lib/src/main/cpp/types/libuni_modules__uni_crash_lib": { + "name": "libuni_modules__uni_crash_lib.so", + "version": "1.0.0", + "resolved": "oh_modules/.ohpm/uni_modules__uni_crash_lib@52lbsbiymmolbsgju3dusxipv9esdf4ryhndsun2mk8=/oh_modules/uni_modules__uni_crash_lib/src/main/cpp/types/libuni_modules__uni_crash_lib", "registryType": "local" }, "libutdid_native.so@oh_modules/.ohpm/@taobao-ohos+utdid_sdk@ecjyoomnzz6zaipo1koz9+avemnpw7+togfp5uwrtiu=/oh_modules/@taobao-ohos/utdid_sdk/src/main/cpp/types/libutdid_native": { @@ -204,6 +256,15 @@ "resolved": "https://ohpm.openharmony.cn/ohpm/pako/-/pako-2.1.0.tgz", "shasum": "266cc37f98c7d883545d11335c00fbd4062c9a86", "registryType": "ohpm" + }, + "uni_modules__uni_crash_lib@oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/uni_modules__uni_crash_lib.har": { + "name": "uni_modules__uni_crash_lib", + "version": "1.0.0", + "resolved": "oh_modules/.ohpm/@dcloudio+uni-app-runtime@5.14.2026070201/oh_modules/@dcloudio/uni-app-runtime/libs/uni_modules__uni_crash_lib.har", + "registryType": "local", + "dependencies": { + "libuni_modules__uni_crash_lib.so": "file:./src/main/cpp/types/libuni_modules__uni_crash_lib" + } } } } \ No newline at end of file diff --git a/oh-package.json5 b/oh-package.json5 index 078bf93..32c3a55 100644 --- a/oh-package.json5 +++ b/oh-package.json5 @@ -7,10 +7,11 @@ "@pura/picker_utils": "^1.0.2", "@candies/image_cropper": "^1.1.1", "@tencent/wechat_open_sdk": "^1.0.16", - "@dcloudio/uni-app-runtime": "^4.75.2025071101", + "@dcloudio/uni-app-runtime": "5.14.2026070201", "@alipay/afservicesdk": "file:./libs/AFServiceSDK.har", "@cashier_alipay/cashiersdk": "^15.8.43", - "@uni_modules/uni-payment-alipay": "^1.0.2" + "@uni_modules/uni-payment-alipay": "^1.0.2", + "@ohos/minizip": "1.0.6" }, "devDependencies": { "@ohos/hypium": "1.0.25", diff --git a/products/app/build-profile.json5 b/products/app/build-profile.json5 index 3cfdd9c..495dd5e 100644 --- a/products/app/build-profile.json5 +++ b/products/app/build-profile.json5 @@ -26,7 +26,7 @@ { "name": "default", "output": { - "artifactName": "rabbit_harmony_v1.0.1_26518938" + "artifactName": "rabbit_harmony_v1.0.1_261121826" } }, { diff --git a/products/app/oh-package-lock.json5 b/products/app/oh-package-lock.json5 index d1207de..c2b8c3b 100644 --- a/products/app/oh-package-lock.json5 +++ b/products/app/oh-package-lock.json5 @@ -7,6 +7,7 @@ "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "specifiers": { "@ohos/common@../../common": "@ohos/common@../../common", + "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive": "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive", "main_layout@../../features/mainLayout": "main_layout@../../features/mainLayout" }, "packages": { @@ -14,6 +15,15 @@ "name": "@ohos/common", "version": "0.0.1", "resolved": "../../common", + "registryType": "local", + "dependencies": { + "libunimp_archive.so": "file:./src/main/cpp/types/libunimp_archive" + } + }, + "libunimp_archive.so@../../common/src/main/cpp/types/libunimp_archive": { + "name": "libunimp_archive.so", + "version": "1.0.0", + "resolved": "../../common/src/main/cpp/types/libunimp_archive", "registryType": "local" }, "main_layout@../../features/mainLayout": { diff --git a/products/app/src/main/ets/appability/AppAbility.ets b/products/app/src/main/ets/appability/AppAbility.ets index a4363f9..12e4463 100644 --- a/products/app/src/main/ets/appability/AppAbility.ets +++ b/products/app/src/main/ets/appability/AppAbility.ets @@ -4,6 +4,7 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { AppUtil } from '@pura/harmony-utils'; import { init } from '@dcloudio/uni-app-runtime'; +import { closeUniMpApps } from '@ohos/common/src/main/ets/utils/UniMpManager'; import * as wxopensdk from '@tencent/wechat_open_sdk'; import { emitter } from '@kit.BasicServicesKit'; import { @@ -80,6 +81,7 @@ export default class AppAbility extends UIAbility { onDestroy(): void { + closeUniMpApps(); // 生命周期管理:销毁 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); } @@ -114,7 +116,7 @@ export default class AppAbility extends UIAbility { //初始化UniMp init(this, windowStage, { - debug: true + debug: AppUtil.debug() }) // 加载页面(启动页) @@ -141,4 +143,4 @@ export default class AppAbility extends UIAbility { // 生命周期管理:已处于后台页面 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); } -} \ No newline at end of file +} diff --git a/products/app/src/main/ets/pages/LoginPage.ets b/products/app/src/main/ets/pages/LoginPage.ets index b0fb953..8a870e5 100644 --- a/products/app/src/main/ets/pages/LoginPage.ets +++ b/products/app/src/main/ets/pages/LoginPage.ets @@ -11,6 +11,7 @@ import { common } from '@kit.AbilityKit'; import { emitter } from '@kit.BasicServicesKit'; import { EVT_LOGIN_WX_AUTHOR_SUCCESS } from '@ohos/common/src/main/ets/constants/EventConstants'; import { Logger } from '@ohos/common'; +import { LoginForHuawei } from '../view/LoginForHuawei'; /** * 登录页面 @@ -20,8 +21,9 @@ import { Logger } from '@ohos/common'; struct LoginPage { @Provide('pageInfos') pageStack: NavPathStack = new NavPathStack(); @State fromSource: string = ''; - @State hasAgreed?: boolean = undefined; - @State loginMethod?: number = 0; //登录方式:0 手机,1 一键登录,2 微信,3 支付宝 + @State hasAgreed: boolean = false; + @State loginMethod: number = 1; //登录方式:0 手机,1 华为账号一键登录,2 微信,3 支付宝 + @State huaweiLoggingIn: boolean = false; /* dialogController: CustomDialogController = new CustomDialogController({ @@ -106,6 +108,10 @@ struct LoginPage { */ } + onBackPress(): boolean { + return this.huaweiLoggingIn; + } + build() { Navigation(this.pageStack) { Stack() { @@ -124,19 +130,28 @@ struct LoginPage { isShowTitle: false, isShowBack: this.fromSource !== 'splash' && this.fromSource !== 'logout' && this.fromSource !== 'deleteAccount' }) + .enabled(!this.huaweiLoggingIn) //显示登录内容 if(this.loginMethod === 0){ // 手机号登录 - LoginForPhone({isChecked: this.hasAgreed, fromSource: this.fromSource}) + LoginForPhone({isChecked: $hasAgreed, fromSource: this.fromSource}) }else if(this.loginMethod === 2){ // 微信登录 - LoginForWechat({isChecked: this.hasAgreed, fromSource: this.fromSource}) + LoginForWechat({isChecked: $hasAgreed, fromSource: this.fromSource}) }else if(this.loginMethod === 3){ // 支付宝登录 - LoginForAlipay({isChecked: this.hasAgreed, fromSource: this.fromSource}) + LoginForAlipay({isChecked: $hasAgreed, fromSource: this.fromSource}) }else if(this.loginMethod === 1){ - // 一键登录 + LoginForHuawei({ + isChecked: $hasAgreed, + onSuccess: (): void => { + LoginSuccess(this.fromSource, false); + }, + onLoadingChange: (loading: boolean): void => { + this.huaweiLoggingIn = loading; + } + }) } } .width('100%') @@ -162,7 +177,15 @@ struct LoginPage { } .alignItems(VerticalAlign.Center) // 确保横线和文字垂直居中对齐 - Row(){ + Row({ space: 24 }){ + Image($r('app.media.ic_login_huawei_icon')) + .width(40) + .height(40) + .accessibilityText('华为账号一键登录') + .onClick(() => { + this.loginMethod = 1; + }) + Image($r('app.media.ic_login_wx_icon')) .width(40) .height(40) @@ -173,7 +196,6 @@ struct LoginPage { Image($r('app.media.ic_login_alipay_icon')) .width(40) .height(40) - .margin({ left: 40, right: 40 }) .onClick(() => { this.loginMethod = 3; }) @@ -185,6 +207,7 @@ struct LoginPage { this.loginMethod = 0; }) } + .enabled(!this.huaweiLoggingIn) .margin({ top: 27, bottom: 60 }) } .width('100%') @@ -214,11 +237,10 @@ struct LoginForPhone { @State isCounting: boolean = false; // 是否正在倒计时 private timerId: number = -1; // 定时器ID - @Prop isChecked: boolean = false; + @Link isChecked: boolean; @Prop fromSource: string = ''; onChange: (checked: boolean) => void = (checked: boolean) => { - if(checked){ 'true' }else{ 'false' } - KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true'); + KVStore.getInstance().put(IS_AGREE_AGREEMENT, checked ? 'true' : 'false'); }; cancel: () => void = () => {}; @@ -495,10 +517,9 @@ struct LoginForWechat { @Consume('pageInfos') pageStack: NavPathStack; @Prop fromSource: string = ''; - @Prop isChecked: boolean = false; + @Link isChecked: boolean; onChange: (checked: boolean) => void = (checked: boolean) => { - if(checked){ 'true' }else{ 'false' } - KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true'); + KVStore.getInstance().put(IS_AGREE_AGREEMENT, checked ? 'true' : 'false'); }; build() { Column(){ @@ -621,10 +642,9 @@ struct LoginForWechat { struct LoginForAlipay { @Consume('pageInfos') pageStack: NavPathStack; @Prop fromSource: string = ''; - @Prop isChecked: boolean = false; + @Link isChecked: boolean; onChange: (checked: boolean) => void = (checked: boolean) => { - if(checked){ 'true' }else{ 'false' } - KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true'); + KVStore.getInstance().put(IS_AGREE_AGREEMENT, checked ? 'true' : 'false'); }; build() { Column(){ @@ -758,7 +778,7 @@ struct LoginForAlipay { * 登录成功 (逻辑处理) * @param source */ -function LoginSuccess(source: string) { +function LoginSuccess(source: string, refreshConfig: boolean = true): void { ToastUtils.normalToast({ message: '登录成功', // 提示文字 duration: 2000, // 显示时长 (ms),默认 1500 @@ -766,10 +786,17 @@ function LoginSuccess(source: string) { }); //重新获取用户配置(数据会持久化到本地) - CommonService.getUserProfile().then(_ => { - // 当用户配置获取完成后,重新获取用户信息(数据会持久化到本地) - CommonService.getUserInfo() - }) + if (refreshConfig) { + CommonService.getUserProfile().then(_ => { + // 当用户配置获取完成后,重新获取用户信息(数据会持久化到本地) + CommonService.getUserInfo() + }) + } else { + // 华为登录已按 weiquan-har 等待配置刷新,这里只刷新用户详情。 + CommonService.getUserInfo().catch(() => { + Logger.info('LoginPage', '华为登录成功,用户详情刷新失败'); + }); + } if(source === 'splash' || source === 'logout' || source === 'deleteAccount'){ //登录成功后回到首页 @@ -778,4 +805,4 @@ function LoginSuccess(source: string) { AppStorage.setOrCreate('back', { isBack: true, source: 'login' }); router.back(); } -} \ No newline at end of file +} diff --git a/products/app/src/main/ets/pages/NavigationPage.ets b/products/app/src/main/ets/pages/NavigationPage.ets index 1f69fb9..536ba79 100644 --- a/products/app/src/main/ets/pages/NavigationPage.ets +++ b/products/app/src/main/ets/pages/NavigationPage.ets @@ -18,6 +18,8 @@ export function NavigationPage() { @Component export struct TabIndex { @State currentIndex: number = 0; + @State private navBarVisible: boolean = true; + private tabController: TabsController = new TabsController(); @State tabs: TabBarItem[] = TabsViewModel.getTabData(); @StorageLink('mainBreakpoint') currentBreakpoint: string = commonConstants.breakpointsInitializeName; private readonly breakpointSystem: BreakpointSystem = new BreakpointSystem(commonConstants.breakpointSystemName); @@ -64,6 +66,7 @@ export struct TabIndex { Navigation(this.pageStack) { Column() { Tabs({ + controller: this.tabController, barPosition: new BreakPointType({ sm: BarPosition.End, md: BarPosition.End, @@ -75,7 +78,13 @@ export struct TabIndex { ForEach(this.tabs, (item: TabBarItem) => { TabContent() { if (item.id === 0) { - HomeComponent() + HomeComponent({ + isActive: this.currentIndex === 0 && this.navBarVisible, + onSelectTab: (index: number) => { + this.currentIndex = index; + this.tabController.changeIndex(index); + } + }) } else { MineComponent() } @@ -109,6 +118,7 @@ export struct TabIndex { .onAnimationStart((_: number, targetIndex: number) => { this.currentIndex = targetIndex; }) + .onChange((index: number) => { this.currentIndex = index; }) .divider({ strokeWidth: 0.5, color: $r('app.color.tab_line'), @@ -120,6 +130,7 @@ export struct TabIndex { } .hideTitleBar(true) .mode(NavigationMode.Stack) + .onNavBarStateChange((visible: boolean) => { this.navBarVisible = visible; }) .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) } -} \ No newline at end of file +} diff --git a/products/app/src/main/ets/view/HomeBanner.ets b/products/app/src/main/ets/view/HomeBanner.ets new file mode 100644 index 0000000..ca33209 --- /dev/null +++ b/products/app/src/main/ets/view/HomeBanner.ets @@ -0,0 +1,128 @@ +import { common } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import { HomeBannerEntity } from '@ohos/common/src/main/ets/viewmodel/HomeBannerEntity'; + +// 两端兜底图均为 1125×654,固定容器比例,网络图片切换时不改变首页布局。 +const BANNER_RATIO: number = 1125 / 654; + +@Component +export struct HomeBanner { + @Prop @Watch('resetPage') banners: HomeBannerEntity[] = []; + @Prop active: boolean = true; + @State private currentIndex: number = 0; + @State private pressed: boolean = false; + @State private visible: boolean = false; + @State private windowActive: boolean = true; + private hostWindow?: window.Window; + private attached: boolean = false; + onSelect: (banner: HomeBannerEntity) => void = () => {}; + + private readonly onWindowEvent = (event: window.WindowEventType): void => { + this.windowActive = event === window.WindowEventType.WINDOW_ACTIVE || event === window.WindowEventType.WINDOW_SHOWN; + if (!this.windowActive) { this.pressed = false; } + }; + + private resetPage(): void { + this.currentIndex = 0; + this.pressed = false; + } + + aboutToAppear(): void { + this.attached = true; + this.windowActive = true; + const context = this.getUIContext().getHostContext() as common.UIAbilityContext; + window.getLastWindow(context).then((hostWindow: window.Window) => { + if (this.attached) { + this.hostWindow = hostWindow; + hostWindow.on('windowEvent', this.onWindowEvent); + } + }).catch(() => {}); + } + + aboutToDisappear(): void { + this.attached = false; + this.visible = false; + if (this.hostWindow) { + try { this.hostWindow.off('windowEvent', this.onWindowEvent); } catch (_) {} + this.hostWindow = undefined; + } + } + + build() { + Stack({ alignContent: Alignment.Bottom }) { + if (this.banners.length === 0) { + Image($r('app.media.ic_home_top_image')).width('100%').height('100%') + .objectFit(ImageFit.Fill) + } else { + Swiper() { + ForEach(this.banners, (banner: HomeBannerEntity, index: number) => { + HomeBannerImage({ banner: banner }) + .id('home_banner_item_' + index) + .accessibilityText(banner.text ?? '') + .onClick(() => this.onSelect(banner)) + }, (banner: HomeBannerEntity, index: number) => + index + ':' + banner.img + ':' + banner.type + ':' + banner.url + ':' + banner.text) + } + .id('home_banner_swiper') + .width('100%').height('100%') + .index(this.currentIndex) + .loop(this.banners.length > 1) + .disableSwipe(this.banners.length <= 1) + .indicator(false) + .interval(3000) + .autoPlay(this.banners.length > 1 && this.active && this.visible && this.windowActive && !this.pressed) + .onChange((index: number) => { this.currentIndex = index; }) + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { this.pressed = true; } + if (event.type === TouchType.Up || event.type === TouchType.Cancel) { this.pressed = false; } + }) + + Row({ space: 6 }) { + ForEach(this.banners, (_banner: HomeBannerEntity, index: number) => { + Circle().width(6).height(6) + .fill(this.currentIndex === index ? Color.White : '#73FFFFFF') + }, (_banner: HomeBannerEntity, index: number) => index.toString()) + } + .id('home_banner_indicator') + .accessibilityText('第' + (this.currentIndex + 1) + '张,共' + this.banners.length + '张') + .padding({ left: 8, right: 8, top: 6, bottom: 6 }) + .backgroundColor('#26000000').borderRadius(20) + .margin({ bottom: 30 }) + .hitTestBehavior(HitTestMode.None) + } + } + .id('home_banner') + .width('100%').aspectRatio(BANNER_RATIO).clip(true) + .onVisibleAreaChange([0, 1], (_visible: boolean, ratio: number) => { this.visible = ratio > 0; }) + } +} + +@Component +struct HomeBannerImage { + @Prop @Watch('resetImage') banner: HomeBannerEntity; + @State private imageRatio: number = BANNER_RATIO; + @State private imageLoaded: boolean = false; + + private resetImage(): void { + this.imageRatio = BANNER_RATIO; + this.imageLoaded = false; + } + + build() { + Stack({ alignContent: Alignment.Center }) { + Image($r('app.media.ic_home_top_image')).width('100%').height('100%').objectFit(ImageFit.Fill) + .opacity(this.imageLoaded ? 0 : 1) + Image(this.banner.img ?? '') + .alt($r('app.media.ic_home_top_image')) + .width('100%').height((BANNER_RATIO / this.imageRatio * 100) + '%') + .objectFit(ImageFit.Fill) + .onComplete((event) => { + if (event && event.width > 0 && event.height > 0) { + this.imageRatio = event.width / event.height; + this.imageLoaded = event.loadingStatus === 1; + } + }) + .onError(() => { this.imageRatio = BANNER_RATIO; }) + }.width('100%').height('100%').clip(true) + } +} diff --git a/products/app/src/main/ets/view/HomeComponent.ets b/products/app/src/main/ets/view/HomeComponent.ets index b46dcd4..8ed5b6b 100644 --- a/products/app/src/main/ets/view/HomeComponent.ets +++ b/products/app/src/main/ets/view/HomeComponent.ets @@ -1,12 +1,11 @@ import { HomeItem } from "../viewmodel/LocalBean"; import HomeViewModel from "../viewmodel/HomeViewModel"; -import { CuteParams } from "@ohos/common/src/main/ets/viewmodel/ParamBean"; +import { CuteParams, WebParams } from "@ohos/common/src/main/ets/viewmodel/ParamBean"; import { ToastUtils } from "@ohos/common/src/main/ets/dialog/ToastUtils"; import { UniIconEntity, UniVersionEntity, UserProfile } from "@ohos/common/src/main/ets/viewmodel/DataBean"; -import { USER_PROFILE } from "@ohos/common/src/main/ets/constants/AppConstants"; -import { downStartUp, downStartUpForPath } from "@ohos/common/src/main/ets/utils/UniMpManager"; +import { USER_INFO, USER_PROFILE } from "@ohos/common/src/main/ets/constants/AppConstants"; +import { downStartUp, downStartUpForPath, UniMpStatus } from "@ohos/common/src/main/ets/utils/UniMpManager"; import { Logger } from "@ohos/common"; -import { setUniMpNeedDownload } from "@ohos/common/src/main/ets/utils/KVManager"; import { GlobalDownloadingDialog } from '@ohos/common/src/main/ets/dialog/GlobalDownloadingDialog'; import { UpdateTipsDialog } from "@ohos/common/src/main/ets/dialog/UpdateTipsDialog"; import { openAppStore, getAppVersion } from '@ohos/common/src/main/ets/utils/AppUtils'; @@ -14,10 +13,19 @@ import { common } from "@kit.AbilityKit"; import { StringUtils } from "@ohos/common/src/main/ets/utils/StringUtils"; import emitter from "@ohos.events.emitter"; import { EVT_USER_CONFIG_PROFILE } from "@ohos/common/src/main/ets/constants/EventConstants"; +import { HomeBanner } from './HomeBanner'; +import { HomeBannerEntity, visibleHomeBanners } from '@ohos/common/src/main/ets/viewmodel/HomeBannerEntity'; +import { isHomeBannerUserLoggedIn, isHomeBannerWebUrl, reportHomeBannerClick, + resolveHomeBannerRoute } from '../viewmodel/HomeBannerActions'; +import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore'; +import { routerLogin } from '@ohos/common/src/main/ets/router/RouterManager'; @Component export struct HomeComponent { @Consume('pageInfos') pageStack: NavPathStack; + @Prop isActive: boolean = true; + @State private homeBanners: HomeBannerEntity[] = []; + onSelectTab: (index: number) => void = () => {}; @State resizeItems: HomeItem[] = HomeViewModel.getResizeData(); @State certificateItems: HomeItem[] = HomeViewModel.getCertificateData(); @State otherItems: HomeItem[] = HomeViewModel.getOtherData(); @@ -33,6 +41,7 @@ export struct HomeComponent { @State downloadAlipayStatus: number = 0 @State private uniMpDatas: UniIconEntity[] = [] @State downloadProgress: number = 0; + private shortcutLoading: boolean = false; // 版本信息 相关状态 @State targetVersion: string = ''; @@ -78,7 +87,7 @@ export struct HomeComponent { }), alignment: DialogAlignment.Center, // 居中显示 customStyle: true, // 使用自定义样式,去掉系统默认背景 - autoCancel: true // 点击遮罩层可关闭 + autoCancel: false }) loadingVersionUpdate(){ @@ -93,9 +102,10 @@ export struct HomeComponent { } }); this.profile = AppStorage.get(USER_PROFILE); + this.homeBanners = visibleHomeBanners(this.profile?.config?.homeBanners); // 模拟器 this.uniMpVersions = this.profile?.config?.uniVersionList || []; - this.uniMpDatas = this.profile?.config?.homeIconEntity || []; + this.uniMpDatas = (this.profile?.config?.homeIconEntity || []).filter((item: UniIconEntity) => item.enable); this.uniMpEnable = this.profile?.config?.isUniMpOpen?? false } @@ -118,14 +128,97 @@ export struct HomeComponent { }); } + @Builder + uniMpStarting(status: number) { + Column() { + LoadingProgress().width(28).height(28).color(Color.White) + Text(status === UniMpStatus.RELEASING ? '解压中,请稍后...' : '启动中,请稍后...') + .fontColor(Color.White).fontSize(12).margin({ top: 6 }) + } + .justifyContent(FlexAlign.Center) + .width('100%').height('100%').backgroundColor('#99000000').borderRadius(12) + } + + private onBannerClick(banner: HomeBannerEntity): void { + reportHomeBannerClick(banner); + const target = banner.url ?? ''; + if (banner.type === 'wx' || banner.type === 'alipay') { + // 与 Android requiredLogin 一致,banner 小程序入口必须是非游客用户。 + if (!isHomeBannerUserLoggedIn(KVStore.getInstance().getSync(USER_INFO, ''))) { + routerLogin('home_banner', false); + return; + } + if (!this.uniMpVersions.some((version: UniVersionEntity) => version.unimp_type === banner.type)) { + ToastUtils.showToast(this.getUIContext(), '功能暂不可用,请稍后重试'); + return; + } + if (this.shortcutLoading) { + ToastUtils.showToast(this.getUIContext(), '请等待模拟器更新完毕!'); + return; + } + const icon: UniIconEntity = { + icon: banner.img ?? '', type: banner.type, enable: true, + text: banner.text?.trim() ? banner.text : 'home', url: target.trim() ? target : '' + }; + downStartUpForPath(this.getUIContext(), this.uniMpVersions, icon, (status, progress) => { + if (status === UniMpStatus.BUSY) { return; } + if (banner.type === 'wx') { + this.downloadWxStatus = status; + this.downloadWxProgress = progress; + } else { + this.downloadAlipayStatus = status; + this.downloadAlipayProgress = progress; + } + if (status === UniMpStatus.DOWNLOADING || status === UniMpStatus.RELEASING || status === UniMpStatus.OPENING) { + this.downloadProgress = status === UniMpStatus.DOWNLOADING ? progress : 0; + if (!this.shortcutLoading) { + this.shortcutLoading = true; + this.downloadingController.open(); + } + } else if (status !== UniMpStatus.RELEASED && status !== UniMpStatus.DOWNLOADED) { + this.shortcutLoading = false; + this.downloadingController.close(); + } + }); + return; + } + if (!target.trim()) { return; } + if (banner.type === 'web') { + if (!isHomeBannerWebUrl(target)) { + ToastUtils.showToast(this.getUIContext(), '链接暂不可用'); + return; + } + const params: WebParams = { id: 1001, name: banner.text ?? '', type: 1, url: target }; + this.pageStack.pushPathByName('WebLayout', params); + } else if (banner.type === 'app') { + const route = resolveHomeBannerRoute(target); + if (!route) { + ToastUtils.showToast(this.getUIContext(), '功能暂不可用,请稍后重试'); + } else if (route === 'home' || route === 'mine') { + this.onSelectTab(route === 'home' ? 0 : 1); + } else if (route === 'login') { + routerLogin('home_banner', false); + } else { + const paths = this.pageStack.getAllPathName(); + if (paths.length === 0 || paths[paths.length - 1] !== route) { + this.pageStack.pushPathByName(route, null); + } + } + } + } + build() { // 父容器 Column 默认从顶部开始排列 Stack(){ Column() { List() { - // 顶部图片 + // 顶部 banner:配置、轮播与点击分流对齐 Rabbit-android HomeScreen。 ListItem() { - Image($r('app.media.ic_home_top_image')).width('100%') + HomeBanner({ + banners: this.homeBanners, + active: this.isActive, + onSelect: (banner: HomeBannerEntity) => this.onBannerClick(banner) + }) } if(this.uniMpEnable){ //模拟器(2位) @@ -140,18 +233,12 @@ export struct HomeComponent { Image($r('app.media.ic_unimp_wx_pld')) .width('100%') .onClick(()=> { - uniMpMpDeal(this.getUIContext(), this.uniMpVersions, 0, (status, progress, path) => { + uniMpMpDeal(this.getUIContext(), this.uniMpVersions, 'wx', (status, progress, path) => { + if (status === UniMpStatus.BUSY) { return; } this.downloadWxStatus = status if(status===1){ this.downloadWxProgress = progress } - if(status === 2){ - // 下载完成,记录版本信息和下载路径 - let uniMpVersion = this.uniMpVersions[0] - setUniMpNeedDownload(uniMpVersion.unimp_id??'', uniMpVersion.unimp_type??'', uniMpVersion.version??'', path??'') - }else if (status === 3){ - // 已启动(运行) - } Logger.info('uniMp', 'downloadWxProgress: ' + this.downloadWxProgress + ', path: ' + path) }) @@ -178,6 +265,8 @@ export struct HomeComponent { .height('100%') .backgroundColor('#99000000') .borderRadius(12) + } else if (this.downloadWxStatus === UniMpStatus.RELEASING || this.downloadWxStatus === UniMpStatus.OPENING) { + this.uniMpStarting(this.downloadWxStatus) } } .width('100%') @@ -191,18 +280,12 @@ export struct HomeComponent { .aspectRatio(168/96) .layoutWeight(1) .onClick(()=> { - uniMpMpDeal(this.getUIContext(), this.uniMpVersions, 1, (status, progress, path) => { + uniMpMpDeal(this.getUIContext(), this.uniMpVersions, 'alipay', (status, progress, path) => { + if (status === UniMpStatus.BUSY) { return; } this.downloadAlipayStatus = status if(status===1){ this.downloadAlipayProgress = progress } - if(status === 2){ - // 下载完成,记录版本信息和下载路径 - let uniMpVersion = this.uniMpVersions[1] - setUniMpNeedDownload(uniMpVersion.unimp_id??'', uniMpVersion.unimp_type??'', uniMpVersion.version??'', path??'') - }else if (status === 3){ - // 已启动(运行) - } Logger.info('uniMp', 'downloadAlipayProgress: ' + this.downloadAlipayProgress + ', path: ' + path) }) @@ -229,6 +312,8 @@ export struct HomeComponent { .height('100%') .backgroundColor('#99000000') .borderRadius(12) + } else if (this.downloadAlipayStatus === UniMpStatus.RELEASING || this.downloadAlipayStatus === UniMpStatus.OPENING) { + this.uniMpStarting(this.downloadAlipayStatus) } } .width('100%') @@ -267,12 +352,20 @@ export struct HomeComponent { .borderRadius(12) } .onClick(()=> { - this.downloadingController.open() + if (this.shortcutLoading) { + ToastUtils.showToast(this.getUIContext(), '请等待模拟器更新完毕!'); + return; + } downStartUpForPath(this.getUIContext(), this.uniMpVersions, item, (status, progress, path) => { Logger.info('uniMp', 'downStartUpForPath: ' + status + ', progress: ' + progress + ', path: ' + path) - if(status===1){ - this.downloadProgress = progress - }else{ + if(status === UniMpStatus.DOWNLOADING || status === UniMpStatus.RELEASING || status === UniMpStatus.OPENING){ + this.downloadProgress = status === UniMpStatus.DOWNLOADING ? progress : 0; + if (!this.shortcutLoading) { + this.shortcutLoading = true; + this.downloadingController.open(); + } + }else if (status !== UniMpStatus.RELEASED && status !== UniMpStatus.DOWNLOADED){ + this.shortcutLoading = false; this.downloadingController.close() } }) @@ -603,11 +696,12 @@ export struct HomeComponent { } -function uniMpMpDeal(context: UIContext, uniMpVersions: UniVersionEntity[], index: number, callback: (status: number, progress: number, path?: string) => void) { - if (uniMpVersions && uniMpVersions.length > index) { - let uniMpVersion = uniMpVersions[index] +function uniMpMpDeal(context: UIContext, uniMpVersions: UniVersionEntity[], type: string, callback: (status: number, progress: number, path?: string) => void) { + const uniMpVersion = uniMpVersions.find((item: UniVersionEntity) => item.unimp_type === type); + if (uniMpVersion) { downStartUp(context, uniMpVersion, callback) }else{ + callback(UniMpStatus.FAILURE, 0); ToastUtils.showToast(context, '出错了~'); } } @@ -884,4 +978,4 @@ export struct HomeComponent { return (rows * 80) + ((rows - 1) * 10); } } -*/ \ No newline at end of file +*/ diff --git a/products/app/src/main/ets/view/LoginForHuawei.ets b/products/app/src/main/ets/view/LoginForHuawei.ets new file mode 100644 index 0000000..cd39864 --- /dev/null +++ b/products/app/src/main/ets/view/LoginForHuawei.ets @@ -0,0 +1,276 @@ +import { BusinessError } from '@kit.BasicServicesKit'; +import { LoginWithHuaweiIDButton, loginComponentManager } from '@kit.AccountKit'; +import { AGREEMENT_URL, PRIVACY_URL, USER_PROFILE } from '@ohos/common/src/main/ets/constants/AppConstants'; +import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils'; +import { HUAWEI_AUTH_AGREEMENT_URL, HuaweiAuth } from '@ohos/common/src/main/ets/utils/HuaweiAuth'; +import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService'; +import { UserProfile } from '@ohos/common/src/main/ets/viewmodel/DataBean'; +import { WebParams } from '@ohos/common/src/main/ets/viewmodel/ParamBean'; + +@Component +export struct LoginForHuawei { + @Consume('pageInfos') pageStack: NavPathStack; + @Link @Watch('syncAgreement') isChecked: boolean; + @State private authorizing: boolean = false; + @State private submitting: boolean = false; + private active: boolean = false; + private generation: number = 0; + private submittedCode: string = ''; + private agreementDialogOpen: boolean = false; + private controller = new loginComponentManager.LoginWithHuaweiIDButtonController(); + onSuccess: () => void = () => {}; + onLoadingChange: (loading: boolean) => void = () => {}; + + private agreementController: CustomDialogController = new CustomDialogController({ + builder: HuaweiLoginAgreementDialog({ + onAgree: () => { + // 与 weiquan-har 一致:确认仅勾选协议,需用户再次点击登录按钮。 + this.isChecked = true; + this.syncAgreement(); + this.closeAgreement(); + }, + onCancel: () => this.closeAgreement(), + onOpen: (name: string, url: string) => { + this.closeAgreement(); + this.openAgreement(name, url); + } + }), + autoCancel: false, + customStyle: true, + alignment: DialogAlignment.Center, + onWillDismiss: (action: DismissDialogAction) => { + this.agreementDialogOpen = false; + action.dismiss(); + } + }); + + aboutToAppear(): void { + this.active = true; + const generation = ++this.generation; + this.syncAgreement(); + this.controller.setEnabled(true) + .onClickEvent((error: BusinessError, event: loginComponentManager.ClickEvent) => { + if (!this.active || generation !== this.generation) { return; } + if (error) { + this.handleError(error); + } else if (event === loginComponentManager.ClickEvent.HUAWEI_ID_LOGIN_BUTTON) { + this.onLoginClick(); + } + }) + .onClickLoginWithHuaweiIDButton((error: BusinessError, credential: loginComponentManager.HuaweiIDCredential) => { + if (!this.active || generation !== this.generation) { return; } + if (error) { + this.handleError(error); + } else { + this.submit(credential, generation); + } + }); + } + + aboutToDisappear(): void { + this.active = false; + this.generation++; + this.authorizing = false; + this.submitting = false; + this.closeAgreement(); + this.onLoadingChange(false); + } + + private syncAgreement(): void { + this.controller.setAgreementStatus(this.isChecked ? + loginComponentManager.AgreementStatus.ACCEPTED : loginComponentManager.AgreementStatus.NOT_ACCEPTED); + } + + private notifyLoading(): void { + this.onLoadingChange(this.authorizing || this.submitting); + } + + private closeAgreement(): void { + if (this.agreementDialogOpen) { + this.agreementDialogOpen = false; + this.agreementController.close(); + } + } + + private requestAgreement(): void { + const enabled = AppStorage.get(USER_PROFILE)?.config?.agreementDialog ?? true; + if (enabled) { + if (!this.agreementDialogOpen) { + this.agreementDialogOpen = true; + this.agreementController.open(); + } + } else { + this.showMessage('请先仔细阅读协议并勾选,然后再点击登录'); + } + } + + private onLoginClick(): void { + if (this.authorizing || this.submitting) { return; } + if (!this.isChecked) { + this.requestAgreement(); + return; + } + // 授权阶段由 SDK 管理按钮加载态,避免先禁用按钮打断 SDK 授权。 + this.authorizing = true; + this.notifyLoading(); + } + + private showMessage(message: string): void { + if (this.active) { ToastUtils.showToast(this.getUIContext(), message); } + } + + private handleError(error: BusinessError): void { + // 重复请求错误不能清除首个请求的加载状态。 + if (error.code === 1001500002 || this.submitting) { return; } + this.authorizing = false; + this.controller.setEnabled(true); + this.notifyLoading(); + if (error.code === 1005300001 && !this.isChecked) { + this.requestAgreement(); + return; + } + this.showMessage(HuaweiAuth.getErrorMessage(error)); + } + + private async submit(credential: loginComponentManager.HuaweiIDCredential, generation: number): Promise { + if (this.submitting) { return; } + this.authorizing = false; + if (!this.isChecked) { + this.notifyLoading(); + this.requestAgreement(); + return; + } + const code = credential?.authorizationCode; + if (!code?.trim()) { + this.notifyLoading(); + this.controller.setEnabled(true); + this.showMessage('华为账号未返回授权码,请重试或使用短信验证码登录'); + return; + } + if (this.submittedCode === code) { + this.notifyLoading(); + return; + } + this.submittedCode = code; + this.submitting = true; + this.controller.setEnabled(false); + this.notifyLoading(); + const isCurrent = (): boolean => this.active && generation === this.generation; + try { + await CommonService.huaweiLogin(credential, { + onSuccess: (_) => { if (isCurrent()) { this.onSuccess(); } }, + onFailure: (message) => { if (isCurrent()) { this.showMessage(message || '登录失败,请重试'); } }, + onError: (_) => { if (isCurrent()) { this.showMessage('登录失败,请检查网络后重试'); } } + }); + } finally { + if (isCurrent()) { + this.submitting = false; + this.controller.setEnabled(true); + this.notifyLoading(); + } + } + } + + private openAgreement(name: string, url: string): void { + const params: WebParams = { id: 1001, name: name, type: 1, url: url }; + this.pageStack.pushPathByName('WebLayout', params); + } + + build() { + Column() { + Text('以华为账号一键登录') + .id('login_huawei_title') + .fontSize(24) + .fontColor('#FF3D3D3D') + .margin({ top: 180 }) + + Text('华为账号提供认证服务') + .fontSize(14) + .fontColor('#FF767676') + .margin({ top: 10 }) + + LoginWithHuaweiIDButton({ + params: { + style: loginComponentManager.Style.BUTTON_RED, + extraStyle: { + buttonStyle: new loginComponentManager.ButtonStyle().loadingStyle({ show: true }) + }, + borderRadius: 28, + loginType: loginComponentManager.LoginType.QUICK_LOGIN, + supportDarkMode: true + }, + controller: this.controller + }) + .id('login_huawei_button') + .width('100%') + .height(56) + .margin({ top: 50, bottom: 14 }) + + Row() { + Checkbox({ name: 'huaweiLoginAgreement' }) + .id('login_huawei_agreement') + .width(22).height(22) + .margin({ left: 0, right: 4 }) + .select(this.isChecked) + .onChange((checked: boolean) => { this.isChecked = checked; }) + + Text() { + Span('已阅读并同意').fontColor('#FF767676') + Span('《用户协议》').fontColor('#FF5C75F8') + .onClick(() => this.openAgreement('用户协议', AGREEMENT_URL)) + Span('和').fontColor('#FF767676') + Span('《隐私协议》').fontColor('#FF5C75F8') + .onClick(() => this.openAgreement('隐私协议', PRIVACY_URL)) + Span('和').fontColor('#FF767676') + Span('《华为账号用户认证协议》').fontColor('#FF5C75F8') + .onClick(() => this.openAgreement('华为账号用户认证协议', HUAWEI_AUTH_AGREEMENT_URL)) + } + .fontSize(12).layoutWeight(1) + } + .padding({ left: 20, right: 20 }) + .alignItems(VerticalAlign.Center) + .enabled(!this.authorizing && !this.submitting) + + if (this.submitting) { + Row({ space: 8 }) { + LoadingProgress().width(20).height(20) + Text('正在登录...').fontSize(14).fontColor('#FF767676') + }.margin({ top: 12 }) + } + } + .width('100%') + .padding({ left: 30, right: 30 }) + } +} + +@CustomDialog +struct HuaweiLoginAgreementDialog { + controller?: CustomDialogController; + onAgree: () => void = () => {}; + onCancel: () => void = () => {}; + onOpen: (name: string, url: string) => void = () => {}; + + build() { + Column() { + Text('提示').fontSize(18).fontWeight(FontWeight.Medium).margin({ top: 20, bottom: 16 }) + Text() { + Span('登录之前须先查看并同意').fontColor('#FF767676') + Span('《用户协议》').fontColor('#FF5C75F8') + .onClick(() => this.onOpen('用户协议', AGREEMENT_URL)) + Span('、') + Span('《隐私协议》').fontColor('#FF5C75F8') + .onClick(() => this.onOpen('隐私协议', PRIVACY_URL)) + Span('、') + Span('《华为账号用户认证协议》').fontColor('#FF5C75F8') + .onClick(() => this.onOpen('华为账号用户认证协议', HUAWEI_AUTH_AGREEMENT_URL)) + }.fontSize(14).textAlign(TextAlign.Center).margin({ left: 24, right: 24, bottom: 20 }) + Divider() + Row() { + Text('取消').width('50%').height(48).textAlign(TextAlign.Center).fontSize(16) + .onClick(() => this.onCancel()) + Text('同意').width('50%').height(48).textAlign(TextAlign.Center).fontSize(16).fontColor('#FF5C75F8') + .onClick(() => this.onAgree()) + } + }.width('80%').backgroundColor(Color.White).borderRadius(12) + } +} diff --git a/products/app/src/main/ets/viewmodel/HomeBannerActions.ets b/products/app/src/main/ets/viewmodel/HomeBannerActions.ets new file mode 100644 index 0000000..4837d98 --- /dev/null +++ b/products/app/src/main/ets/viewmodel/HomeBannerActions.ets @@ -0,0 +1,45 @@ +import { url } from '@kit.ArkTS'; +import { PLATFORM } from '@ohos/common/src/main/ets/constants/AppConstants'; +import { ApiManager } from '@ohos/common/src/main/ets/provider/ApiManager'; +import { HomeBannerEntity } from '@ohos/common/src/main/ets/viewmodel/HomeBannerEntity'; +import { Logger } from '@ohos/common'; + +/** Android 路由名映射到已注册的鸿蒙页面。未知配置不直接交给导航栈。 */ +export function resolveHomeBannerRoute(route: string): string | undefined { + const routes: Record = { + 'home': 'home', 'mine': 'mine', 'login': 'login', + 'cutout': 'CuteLayout', 'resize': 'ResizeLayout', 'format': 'FormatLayout', + 'cameraGuide': 'GuideLayout', 'longImage': 'LongImageLayout', 'feedback': 'FeedbackLayout', + 'setting': 'SettingLayout', 'bindAccount': 'AccountBindLayout', 'managerAccount': 'AccountManagerLayout', + 'aboutMine': 'AboutUsLayout', 'deleteAccount': 'DeleteAccountLayout' + }; + return Object.keys(routes).includes(route) ? routes[route] : undefined; +} + +export function isHomeBannerWebUrl(value: string): boolean { + try { + const parsed = new url.URL(value); + return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.hostname.length > 0; + } catch (_) { return false; } +} + +export function isHomeBannerUserLoggedIn(userJson: string): boolean { + try { + const user = JSON.parse(userJson) as Record | null; + return user !== null && user['temp'] === false; + } catch (_) { return false; } +} + +export function reportHomeBannerClick(banner: HomeBannerEntity): void { + const report: Record = { + 'source': PLATFORM, 'type': 'click', 'key': 'client.home.banner.click', + 'value': banner.type ?? '', 'extra': banner.url ?? '' + }; + try { + ApiManager.getInstance().request('/api/user/event', undefined, 'post', report).catch(() => { + Logger.info('HomeBanner', '轮播图点击事件上报失败'); + }); + } catch (_) { + Logger.info('HomeBanner', '轮播图点击事件上报失败'); + } +} diff --git a/products/app/src/main/resources/base/media/ic_login_huawei_icon.png b/products/app/src/main/resources/base/media/ic_login_huawei_icon.png new file mode 100644 index 0000000..7ab81e1 Binary files /dev/null and b/products/app/src/main/resources/base/media/ic_login_huawei_icon.png differ diff --git a/products/app/src/ohosTest/ets/test/List.test.ets b/products/app/src/ohosTest/ets/test/List.test.ets index 794c7dc..341f960 100644 --- a/products/app/src/ohosTest/ets/test/List.test.ets +++ b/products/app/src/ohosTest/ets/test/List.test.ets @@ -1,5 +1,7 @@ import abilityTest from './Ability.test'; +import uniMpPasswordTest from './UniMpPassword.test'; export default function testsuite() { abilityTest(); -} \ No newline at end of file + uniMpPasswordTest(); +} diff --git a/products/app/src/ohosTest/module.json5 b/products/app/src/ohosTest/module.json5 index 1f056de..0fa6df6 100644 --- a/products/app/src/ohosTest/module.json5 +++ b/products/app/src/ohosTest/module.json5 @@ -2,6 +2,16 @@ "module": { "name": "app_test", "type": "feature", + "pages": "$profile:banner_test_pages", + "abilities": [ + { + "name": "HomeBannerTestAbility", + "srcEntry": "./ets/testability/HomeBannerTestAbility.ets", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true + } + ], "deviceTypes": [ "phone" ],