rabbit-harmony/common/src/main/ets/utils/UniMpArchive.ets

42 lines
1.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<string, Object>;
if (manifest['id'] !== appId) {
throw new Error('WGT资源包的应用ID与配置不一致');
}
}