| | |
| | | |
| | | import 'package:dio/dio.dart'; |
| | | import 'package:flutter/foundation.dart'; |
| | | import 'package:path/path.dart' as p; |
| | | import 'package:fluttergamebox/api/api_client.dart'; |
| | | import 'package:fluttergamebox/api/api_service.dart'; |
| | | import 'package:fluttergamebox/utils/util.dart'; |
| | |
| | | final int gameId; |
| | | final String title; |
| | | final List<DownloadTaskFile> files; |
| | | final String launchExe; // 启动程序相对路径(相对游戏安装目录) |
| | | double speed = 0; // bytes/s |
| | | bool autoShutdown = false; |
| | | bool paused = false; |
| | | bool finished = false; |
| | | bool canceled = false; |
| | | bool extracting = false; // 正在解压安装 |
| | | bool extractFailed = false; // 解压失败 |
| | | DateTime? startTime; |
| | | |
| | | DownloadTask( |
| | | {required this.gameId, |
| | | required this.title, |
| | | required List<DownloadTaskFile> files}) |
| | | required List<DownloadTaskFile> files, |
| | | this.launchExe = ''}) |
| | | : files = files; |
| | | |
| | | double get totalBytes => |
| | |
| | | if (dlPath.isEmpty) { |
| | | throw '请先在右上角菜单中设置下载安装路径'; |
| | | } |
| | | // 没有文件的游戏:创建占位文件任务(演示下载流程) |
| | | final tasks = <DownloadTaskFile>[]; |
| | | // 未上传下载文件的游戏无法下载 |
| | | if (fileList.isEmpty) { |
| | | final demoSize = _parseSizeToBytes(game.size); |
| | | tasks.add(DownloadTaskFile( |
| | | name: '${game.title}.part01.rar', |
| | | url: '', |
| | | totalBytes: demoSize)); |
| | | } else { |
| | | throw '该游戏暂无下载文件,请联系管理员上传游戏压缩包'; |
| | | } |
| | | final tasks = <DownloadTaskFile>[]; |
| | | for (final f in fileList) { |
| | | tasks.add(DownloadTaskFile( |
| | | name: f['name'] ?? 'file', |
| | | url: f['url'] ?? '', |
| | | totalBytes: _parseSizeToBytes(f['size'] ?? '0 B'))); |
| | | } |
| | | } |
| | | final task = DownloadTask( |
| | | gameId: game.id, title: game.title, files: tasks); |
| | | gameId: game.id, |
| | | title: game.title, |
| | | files: tasks, |
| | | launchExe: (res['data']['launch_exe'] ?? '') as String); |
| | | this.tasks.insert(0, task); |
| | | activeTask = task; |
| | | notifyListeners(); |
| | |
| | | await Future.delayed(const Duration(milliseconds: 300)); |
| | | if (task.canceled || task.paused) break; |
| | | |
| | | if (file.url.isEmpty) { |
| | | // 演示模式:模拟下载 |
| | | await _simulateDownload(task, file); |
| | | } else { |
| | | if (file.url.isNotEmpty) { |
| | | await _downloadFile(task, file, '${dir.path}\\${file.name}'); |
| | | } |
| | | if (task.canceled || task.paused) break; |
| | |
| | | notifyListeners(); |
| | | } |
| | | if (!task.canceled && !task.paused) { |
| | | // 下载完成:解压压缩包到安装目录并删除压缩包 |
| | | await _installTask(task, dir.path); |
| | | task.finished = true; |
| | | notifyListeners(); |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | Future<void> _simulateDownload( |
| | | DownloadTask task, DownloadTaskFile file) async { |
| | | file.status = DownloadStatus.downloading; |
| | | notifyListeners(); |
| | | const chunk = 1024 * 1024 * 4; // 每tick 4MB |
| | | final tickMs = 30; |
| | | while (file.received < file.totalBytes) { |
| | | if (task.canceled || task.paused) return; |
| | | await Future.delayed(Duration(milliseconds: tickMs)); |
| | | // 模拟速度 ~100MB/s 波动 |
| | | final speed = (90 + (file.name.hashCode % 20)) * 1024 * 1024.0; |
| | | file.received = |
| | | (file.received + speed * tickMs / 1000).clamp(0, file.totalBytes); |
| | | task.speed = speed; |
| | | notifyListeners(); |
| | | } |
| | | task.speed = 0; |
| | | notifyListeners(); |
| | | } |
| | | |
| | | String _safeName(String s) => |
| | | s.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_'); |
| | | |
| | | /// 安装目录(与资源库启动逻辑保持一致) |
| | | Future<String> _installDir(String title) async { |
| | | final ins = await AppPrefs.getInstallPath(); |
| | | final base = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins; |
| | | return '$base\\${_safeName(title)}'; |
| | | } |
| | | |
| | | /// 下载完成后:压缩包解压到安装目录,非压缩包文件移动过去,最后删除压缩包 |
| | | Future<void> _installTask(DownloadTask task, String dlDir) async { |
| | | final installPath = await _installDir(task.title); |
| | | final installDir = Directory(installPath); |
| | | await installDir.create(recursive: true); |
| | | |
| | | // 区分压缩包和普通文件(演示任务 url 为空,无实际文件) |
| | | final archives = <File>[]; |
| | | final plainFiles = <File>[]; |
| | | for (final f in task.files) { |
| | | if (f.url.isEmpty) continue; |
| | | final file = File(p.join(dlDir, f.name)); |
| | | if (!await file.exists()) continue; |
| | | final lower = f.name.toLowerCase(); |
| | | if (lower.endsWith('.zip') || lower.endsWith('.rar') || lower.endsWith('.7z')) { |
| | | archives.add(file); |
| | | } else { |
| | | plainFiles.add(file); |
| | | } |
| | | } |
| | | if (archives.isEmpty && plainFiles.isEmpty) return; |
| | | |
| | | task.extracting = true; |
| | | notifyListeners(); |
| | | try { |
| | | // 普通文件直接移动到安装目录 |
| | | for (final f in plainFiles) { |
| | | await f.rename(p.join(installPath, p.basename(f.path))); |
| | | } |
| | | // 多卷压缩包(xxx.partN.rar)只解压第一卷 |
| | | final partRe = RegExp(r'\.part(\d+)\.rar$', caseSensitive: false); |
| | | final skip = <String>{}; |
| | | for (final a in archives) { |
| | | final m = partRe.firstMatch(p.basename(a.path)); |
| | | if (m != null && int.parse(m.group(1)!) != 1) { |
| | | skip.add(a.path); |
| | | } |
| | | } |
| | | for (final a in archives) { |
| | | if (skip.contains(a.path)) continue; |
| | | await _extractArchive(a, installPath); |
| | | } |
| | | // 全部解压完成后删除压缩包 |
| | | for (final a in archives) { |
| | | if (await a.exists()) await a.delete(); |
| | | } |
| | | // 清理下载目录中已空的游戏文件夹 |
| | | final dl = Directory(dlDir); |
| | | if (await dl.exists()) { |
| | | try { |
| | | await dl.delete(); |
| | | } catch (_) {} |
| | | } |
| | | } catch (e) { |
| | | debugLog('install error: $e'); |
| | | task.extractFailed = true; |
| | | } finally { |
| | | task.extracting = false; |
| | | notifyListeners(); |
| | | } |
| | | } |
| | | |
| | | /// 解压单个压缩包到目标目录 |
| | | Future<void> _extractArchive(File archive, String destDir) async { |
| | | final lower = archive.path.toLowerCase(); |
| | | if (lower.endsWith('.zip')) { |
| | | // Windows 10+ 自带 bsdtar,可直接解压 zip |
| | | final r = await Process.run('tar', ['-xf', archive.path, '-C', destDir]); |
| | | if (r.exitCode != 0) { |
| | | throw 'tar 解压失败: ${r.stderr}'; |
| | | } |
| | | } else { |
| | | // rar/7z:使用本机已安装的 7-Zip 或 WinRAR |
| | | final tool = await _findExtractTool(); |
| | | if (tool == null) { |
| | | throw '未找到 7-Zip 或 WinRAR,无法解压 ${p.basename(archive.path)}'; |
| | | } |
| | | final r = await Process.run(tool, ['x', '-y', '-o$destDir', archive.path]); |
| | | if (r.exitCode != 0) { |
| | | throw '解压失败: ${r.stderr}'; |
| | | } |
| | | } |
| | | // 若压缩的是"游戏文件夹本身",解压后只有一层同名目录,将其内容上移 |
| | | await _flattenSingleRoot(destDir); |
| | | } |
| | | |
| | | Future<String?> _findExtractTool() async { |
| | | final candidates = [ |
| | | '7z', |
| | | r'C:\Program Files\7-Zip\7z.exe', |
| | | r'C:\Program Files (x86)\7-Zip\7z.exe', |
| | | r'C:\Program Files\WinRAR\WinRAR.exe', |
| | | r'C:\Program Files (x86)\WinRAR\WinRAR.exe', |
| | | ]; |
| | | for (final c in candidates) { |
| | | if (c.contains('\\')) { |
| | | if (await File(c).exists()) return c; |
| | | } else { |
| | | try { |
| | | final r = await Process.run('where', [c]); |
| | | if (r.exitCode == 0) return c; |
| | | } catch (_) {} |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /// 目标目录只有一个子目录且无其他文件时,把子目录内容上移一层 |
| | | Future<void> _flattenSingleRoot(String destDir) async { |
| | | final dest = Directory(destDir); |
| | | final entries = await dest.list().toList(); |
| | | if (entries.length != 1 || entries.first is! Directory) return; |
| | | final inner = entries.first as Directory; |
| | | for (final e in await inner.list().toList()) { |
| | | await e.rename(p.join(dest.path, p.basename(e.path))); |
| | | } |
| | | await inner.delete(); |
| | | } |
| | | } |