Commit 0925b7fc by tanghuan

调整下载和解压

1 parent 51f507f4
...@@ -178,8 +178,6 @@ class WebCubit extends Cubit<WebState> { ...@@ -178,8 +178,6 @@ class WebCubit extends Cubit<WebState> {
WebViewController get controller => _controller; WebViewController get controller => _controller;
WebCubit(super.initialState) { WebCubit(super.initialState) {
print('========================== 构造 WebCubit ==========================');
// 没有登录数据,跳转到登录页面 // 没有登录数据,跳转到登录页面
if (state.sessionCode == null || state.sessionCode == '') { if (state.sessionCode == null || state.sessionCode == '') {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
...@@ -191,32 +189,37 @@ class WebCubit extends Cubit<WebState> { ...@@ -191,32 +189,37 @@ class WebCubit extends Cubit<WebState> {
} }
Future<void> _init() async { Future<void> _init() async {
// 获取版本信息 try {
var versionConfig = await _getVersionConfig(); // 获取版本信息
var correctVersion = versionConfig['version'] as String; var versionConfig = await _getVersionConfig();
var downloadUrl = versionConfig['zip'] as String; var correctVersion = versionConfig['version'] as String;
var urgency = versionConfig['urgency'] as int? ?? 1; var downloadUrl = versionConfig['zip'] as String;
var urgency = versionConfig['urgency'] as int? ?? 0;
// 当前使用的H5版本
var curVersion = getIt.get<SharedPreferences>().getString('h5_version') ?? Constant.h5Version; // 当前使用的H5版本
var curVersion = getIt.get<SharedPreferences>().getString('h5_version') ?? Constant.h5Version;
// 版本不一致则需要升级
if (curVersion != correctVersion) { // 版本不一致则需要升级
if (urgency == 1) { if (curVersion != correctVersion) {
// 一直等待升级完成 if (urgency == 1) {
// 遮罩界面 // 一直等待升级完成
emit(state.copyWith(isUpgrading: true)); // 遮罩界面
await _upgrade(curVersion, downloadUrl); emit(state.copyWith(isUpgrading: true));
// 升级完成后取消遮罩,继续初始化其它数据 await _upgrade(correctVersion, downloadUrl);
emit(state.copyWith(isUpgrading: false)); // 升级完成后取消遮罩,继续初始化其它数据
} else { emit(state.copyWith(isUpgrading: false));
// 后台下载,完成后提示用户 } else {
_upgrade(correctVersion, downloadUrl).then( // 后台下载,完成后提示用户
(value) { _upgrade(correctVersion, downloadUrl).then(
emit(state.copyWith(suggestUpgrade: true)); (value) {
}, emit(state.copyWith(suggestUpgrade: true));
); },
);
}
} }
} catch (e) {
print('升级检测处理失败');
print(e);
} }
// 消息处理器 // 消息处理器
...@@ -269,30 +272,38 @@ class WebCubit extends Cubit<WebState> { ...@@ -269,30 +272,38 @@ class WebCubit extends Cubit<WebState> {
try { try {
// 下载zip文件 // 下载zip文件
var tempDir = await getTemporaryDirectory(); var tempDir = await getTemporaryDirectory();
var saveFilePath = '${tempDir.path}/${Uuid().v4()}.zip'; var tempFilePath = '${tempDir.path}/${Uuid().v4()}.zip';
Response response = await dio.download(zipUrl, saveFilePath); Response response = await dio.download(zipUrl, tempFilePath);
if (response.statusCode != 200) { if (response.statusCode != 200) {
throw Exception('文件下载失败'); throw Exception('文件下载失败');
} }
// 解压zip文件 var dir = await getApplicationSupportDirectory();
String? httpDirect; String httpDirPath = '${dir.path}/${Constant.h5DistDir}';
if (Platform.isAndroid) {
var direct = await getExternalStorageDirectory(); var httpDir = Directory(httpDirPath);
httpDirect = '${direct?.path}/${Constant.h5DistDir}/$version'; if (!httpDir.existsSync()) {
} else if (Platform.isIOS || Platform.isMacOS) { await httpDir.create(recursive: true);
var direct = await getApplicationSupportDirectory();
httpDirect = '${direct.path}/${Constant.h5DistDir}/$version';
} }
var result = await ZipUtil.extractZipFile(saveFilePath, httpDirect!); var tempZipFile = File(tempFilePath);
var saveZipFilePath = '$httpDirPath/$version.zip';
// 复制zip文件,保留备用
await tempZipFile.copy(saveZipFilePath);
// 删除临时文件
await tempZipFile.delete();
// 解压zip文件
String targetDir = '$httpDirPath/$version';
var result = await ZipUtil.extractZipFile(saveZipFilePath, targetDir);
if (!result) { if (!result) {
throw Exception('文件解压失败'); throw Exception('文件解压失败');
} }
var sharedPreferences = await SharedPreferences.getInstance(); var sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString('h5_version', version); await sharedPreferences.setString('h5_version', version);
} finally { } finally {
dio.close(force: true); dio.close(force: true);
} }
...@@ -318,10 +329,6 @@ class WebCubit extends Cubit<WebState> { ...@@ -318,10 +329,6 @@ class WebCubit extends Cubit<WebState> {
print('onPageFinished--------------------------------->'); print('onPageFinished--------------------------------->');
print(url); print(url);
/*if (url == '${Constant.localServerTestFileUrl}/login.html') {
return;
}*/
_controller.runJavaScript( _controller.runJavaScript(
'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")', 'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
); );
...@@ -474,12 +481,53 @@ class WebCubit extends Cubit<WebState> { ...@@ -474,12 +481,53 @@ class WebCubit extends Cubit<WebState> {
_controller.reload(); _controller.reload();
} }
///
/// 1 清理非 h5_version 的缓存
/// 2 清理文件目录和缓存目录(不包括解压的H5资源目录)
///
Future<void> clearStorage() async { Future<void> clearStorage() async {
await getIt.get<SharedPreferences>().clear(); var sharedPreferences = getIt.get<SharedPreferences>();
sharedPreferences.getKeys().forEach((key) {
if (!key.startsWith('h5_version')) {
sharedPreferences.remove(key);
}
});
var version = sharedPreferences.getString('h5_version') ?? Constant.h5Version;
var dir = await getApplicationSupportDirectory();
String httpDirPath = '${dir.path}/${Constant.h5DistDir}';
var httpDir = Directory(httpDirPath);
if (!httpDir.existsSync()) {
return;
}
// 查询目录下的所有文件和目录
List<FileSystemEntity> entities = await Directory(httpDirPath).list().toList();
for (var entity in entities) {
if (entity is Directory) {
// 删除目录
if (!entity.path.endsWith(version)) {
await entity.delete(recursive: true);
}
} else if (entity is File) {
// 删除文件
if (!entity.path.endsWith('$version.zip')) {
await entity.delete();
}
}
}
} }
Future<void> logout() async { Future<void> logout() async {
await clearStorage(); // 删除所有auth_开头的key
var sharedPreferences = getIt.get<SharedPreferences>();
sharedPreferences.getKeys().forEach((key) {
if (key.startsWith('auth_')) {
sharedPreferences.remove(key);
}
});
// IM 登出 // IM 登出
await getIt.get<ImService>().logout(); await getIt.get<ImService>().logout();
...@@ -513,17 +561,18 @@ class WebCubit extends Cubit<WebState> { ...@@ -513,17 +561,18 @@ class WebCubit extends Cubit<WebState> {
TextButton( TextButton(
child: Text('取消'), child: Text('取消'),
onPressed: () { onPressed: () {
Navigator.of(context).pop();
emit(state.copyWith(suggestUpgrade: false)); emit(state.copyWith(suggestUpgrade: false));
Navigator.of(context).pop();
}, },
), ),
TextButton( TextButton(
child: Text('确定'), child: Text('确定'),
onPressed: () { onPressed: () {
Navigator.of(context).pop();
emit(state.copyWith(suggestUpgrade: false)); emit(state.copyWith(suggestUpgrade: false));
getIt.get<LocalServerService>().resetHttpDirectory(); getIt.get<LocalServerService>().resetHttpDirectory();
_loadHtml(); _controller.reload();
// _loadHtml();
Navigator.of(context).pop();
}, },
), ),
], ],
......
...@@ -150,13 +150,8 @@ class LocalServerService { ...@@ -150,13 +150,8 @@ class LocalServerService {
Future<void> _initHttpDirectory() async { Future<void> _initHttpDirectory() async {
var version = getIt.get<SharedPreferences>().getString('h5_version') ?? Constant.h5Version; var version = getIt.get<SharedPreferences>().getString('h5_version') ?? Constant.h5Version;
if (Platform.isAndroid) { var direct = await getApplicationSupportDirectory();
var direct = await getExternalStorageDirectory(); _httpDirectory = '${direct.path}/${Constant.h5DistDir}/$version';
_httpDirectory = '${direct?.path}/${Constant.h5DistDir}/$version';
} else if (Platform.isIOS || Platform.isMacOS) {
var direct = await getApplicationSupportDirectory();
_httpDirectory = '${direct.path}/${Constant.h5DistDir}/$version';
}
} }
Future<void> _extractDist() async { Future<void> _extractDist() async {
...@@ -167,7 +162,13 @@ class LocalServerService { ...@@ -167,7 +162,13 @@ class LocalServerService {
// return; // return;
// } // }
var zipFilePath = "assets/dist.zip"; // 判断H5打包文件是否存在,不存在则从assets中解压
await ZipUtil.extractZipFile(zipFilePath, outputDirectory); var version = getIt.get<SharedPreferences>().getString('h5_version') ?? Constant.h5Version;
var dir = await getApplicationSupportDirectory();
var distFilePath = '${dir.path}/${Constant.h5DistDir}/$version.zip';
if (!File(distFilePath).existsSync()) {
distFilePath = 'assets/dist.zip';
}
await ZipUtil.extractZipFile(distFilePath, outputDirectory);
} }
} }
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!