905086
2026-11-08 6cc9b12b81d184bb2df9dc68f93ca45c3d47d229
fluttergamebox/lib/store/app_state.dart
@@ -79,11 +79,19 @@
  double get progress => totalBytes > 0 ? received / totalBytes : 0;
}
/// 解压日志条目(安装阶段展示:百分比 + 解压出的文件路径)
class ExtractLogEntry {
  int percent; // 所在压缩包内的进度百分比
  String path; // 解压出的文件相对路径
  ExtractLogEntry(this.percent, this.path);
}
class DownloadTask {
  final int gameId;
  final String title;
  final List<DownloadTaskFile> files;
  final String launchExe; // 启动程序相对路径(相对游戏安装目录)
  final bool isTool; // 是否为工具下载任务(工具与游戏id独立,避免误判)
  double speed = 0; // bytes/s
  bool autoShutdown = false;
  bool paused = false;
@@ -91,13 +99,16 @@
  bool canceled = false;
  bool extracting = false; // 正在解压安装
  bool extractFailed = false; // 解压失败
  double extractProgress = 0; // 安装(解压)总进度 0~1
  final List<ExtractLogEntry> extractLog = []; // 解压文件日志
  DateTime? startTime;
  DownloadTask(
      {required this.gameId,
      required this.title,
      required List<DownloadTaskFile> files,
      this.launchExe = ''})
      this.launchExe = '',
      this.isTool = false})
      : files = files;
  double get totalBytes =>
@@ -125,6 +136,8 @@
  final List<DownloadTask> tasks = [];
  DownloadTask? activeTask;
  bool _loopRunning = false;
  int _extractTargets = 0; // 需解压的压缩包数量
  int _extractDone = 0; // 已完成解压的压缩包数量
  bool get hasActive => activeTask != null && !activeTask!.finished;
@@ -135,6 +148,24 @@
    notifyListeners();
  }
  /// 清除指定游戏已完成的任务记录(卸载后不再视为已安装;不影响工具任务)
  void clearFinishedTask(int gameId) {
    final t = activeTask;
    if (t != null && !t.isTool && t.gameId == gameId && t.finished) {
      activeTask = null;
      notifyListeners();
    }
  }
  /// 清除指定工具已完成的任务记录(工具卸载后不再视为已安装)
  void clearFinishedToolTask(int toolId) {
    final t = activeTask;
    if (t != null && t.isTool && t.gameId == toolId && t.finished) {
      activeTask = null;
      notifyListeners();
    }
  }
  Future<void> startDownload(Game game) async {
    // 获取下载文件列表(服务端校验会员)
    final res = await ApiService.downloadInfo(game.id);
@@ -168,6 +199,39 @@
    _runLoop();
  }
  /// 工具安装:下载压缩包并解压(与游戏流程一致,无需会员校验)
  Future<void> startToolDownload(Tool tool) async {
    final res = await ApiService.toolDownloadInfo(tool.id);
    if (res['code'] != 0) {
      throw res['msg'] ?? '获取下载信息失败';
    }
    final List<dynamic> fileList = _parseFiles(res['data']['files']);
    final dlPath = await AppPrefs.getDownloadPath();
    if (dlPath.isEmpty) {
      throw '请先在右上角菜单中设置下载安装路径';
    }
    if (fileList.isEmpty) {
      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: tool.id,
        title: tool.name,
        files: tasks,
        launchExe: (res['data']['launch_exe'] ?? '') as String,
        isTool: true);
    this.tasks.insert(0, task);
    activeTask = task;
    notifyListeners();
    _runLoop();
  }
  /// 服务端files字段为JSON字符串或数组,统一解析为List
  List<dynamic> _parseFiles(dynamic raw) {
    if (raw is List) return raw;
@@ -234,7 +298,7 @@
      final task = activeTask!;
      task.startTime = DateTime.now();
      final dlPath = await AppPrefs.getDownloadPath();
      final dir = Directory('$dlPath\\${_safeName(task.title)}');
      final dir = Directory('$dlPath\\${safeFileName(task.title)}');
      await dir.create(recursive: true);
      for (final file in task.files) {
@@ -304,15 +368,8 @@
    }
  }
  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<String> _installDir(String title) => gameInstallDir(title);
  /// 下载完成后:压缩包解压到安装目录,非压缩包文件移动过去,最后删除压缩包
  Future<void> _installTask(DownloadTask task, String dlDir) async {
@@ -337,6 +394,8 @@
    if (archives.isEmpty && plainFiles.isEmpty) return;
    task.extracting = true;
    task.extractProgress = 0;
    task.extractLog.clear();
    notifyListeners();
    try {
      // 普通文件直接移动到安装目录
@@ -352,10 +411,13 @@
          skip.add(a.path);
        }
      }
      _extractTargets = archives.length - skip.length;
      _extractDone = 0;
      for (final a in archives) {
        if (skip.contains(a.path)) continue;
        await _extractArchive(a, installPath);
        await _extractArchive(a, installPath, task);
      }
      task.extractProgress = 1;
      // 全部解压完成后删除压缩包
      for (final a in archives) {
        if (await a.exists()) await a.delete();
@@ -376,37 +438,110 @@
    }
  }
  /// 解压单个压缩包到目标目录
  Future<void> _extractArchive(File archive, String destDir) async {
  /// 解压单个压缩包到目标目录(7z 时流式读取输出获取进度与文件名)
  Future<void> _extractArchive(
      File archive, String destDir, DownloadTask task) async {
    final lower = archive.path.toLowerCase();
    if (lower.endsWith('.zip')) {
      // Windows 10+ 自带 bsdtar,可直接解压 zip
    final z7 = await _find7z();
    if (z7 != null) {
      // 7-Zip 支持全部格式,-bsp1 输出每个文件的进度
      final proc =
          await Process.start(z7, ['x', '-y', '-bsp1', '-o$destDir', archive.path]);
      _consumeExtractOutput(proc, task);
      final code = await proc.exitCode;
      if (code != 0) {
        throw '解压失败: ${p.basename(archive.path)}';
      }
    } else if (lower.endsWith('.zip')) {
      // Windows 10+ 自带 bsdtar,可直接解压 zip(无进度输出,模拟进度前进)
      _addExtractLog(task, 0, p.basename(archive.path));
      final sim = _startSimulatedProgress(task);
      final r = await Process.run('tar', ['-xf', archive.path, '-C', destDir]);
      sim.cancel();
      if (r.exitCode != 0) {
        throw 'tar 解压失败: ${r.stderr}';
      }
    } else {
      // rar/7z:使用本机已安装的 7-Zip 或 WinRAR
      final tool = await _findExtractTool();
      if (tool == null) {
      // rar/7z:使用本机已安装的 WinRAR(无进度输出,模拟进度前进)
      final rar = await _findWinRar();
      if (rar == null) {
        throw '未找到 7-Zip 或 WinRAR,无法解压 ${p.basename(archive.path)}';
      }
      final r = await Process.run(tool, ['x', '-y', '-o$destDir', archive.path]);
      _addExtractLog(task, 0, p.basename(archive.path));
      final sim = _startSimulatedProgress(task);
      final r = await Process.run(rar, ['x', '-y', '-o$destDir', archive.path]);
      sim.cancel();
      if (r.exitCode != 0) {
        throw '解压失败: ${r.stderr}';
      }
    }
    _extractDone++;
    if (_extractTargets > 0) {
      // 单包完成后按实际完成数推进(模拟进度可能已超前,则不回退)
      final real = _extractDone / _extractTargets;
      if (real > task.extractProgress) task.extractProgress = real;
    }
    notifyListeners();
    // 若压缩的是"游戏文件夹本身",解压后只有一层同名目录,将其内容上移
    await _flattenSingleRoot(destDir);
  }
  Future<String?> _findExtractTool() async {
  /// 解压无进度输出时(tar/WinRAR),模拟进度缓慢前进(封顶95%,完成后置100%)
  Timer _startSimulatedProgress(DownloadTask task) {
    return Timer.periodic(const Duration(milliseconds: 400), (_) {
      if (task.extractProgress < 0.95) {
        task.extractProgress =
            (task.extractProgress + 0.01).clamp(0.0, 0.95).toDouble();
        notifyListeners();
      }
    });
  }
  /// 跟踪 7z 进度输出(形如 " 13% 148 - 路径\文件.dll"),更新解压进度与日志
  void _consumeExtractOutput(Process proc, DownloadTask task) {
    final re = RegExp(r'(\d+)%\s*\d*\s*-?\s*(.*)');
    void handle(String line) {
      final m = re.firstMatch(line);
      if (m == null) return;
      final percent = (int.tryParse(m.group(1)!) ?? 0) / 100;
      final name = (m.group(2) ?? '').trim();
      if (name.isNotEmpty) {
        final last = task.extractLog.isEmpty ? null : task.extractLog.last;
        if (last != null && last.path == name) {
          last.percent = (percent * 100).round();
        } else {
          _addExtractLog(task, (percent * 100).round(), name);
        }
      }
      final targets = _extractTargets > 0 ? _extractTargets : 1;
      task.extractProgress =
          ((_extractDone + percent) / targets).clamp(0.0, 0.999).toDouble();
      notifyListeners();
    }
    proc.stdout
        .transform(systemEncoding.decoder)
        .transform(const LineSplitter())
        .listen(handle);
    proc.stderr
        .transform(systemEncoding.decoder)
        .transform(const LineSplitter())
        .listen(handle);
  }
  /// 追加一条解压日志(上限200条,超出时移除最早的)
  void _addExtractLog(DownloadTask task, int percent, String path) {
    task.extractLog.add(ExtractLogEntry(percent, path));
    if (task.extractLog.length > 200) {
      task.extractLog.removeAt(0);
    }
  }
  Future<String?> _find7z() 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('\\')) {
@@ -421,6 +556,17 @@
    return null;
  }
  Future<String?> _findWinRar() async {
    final candidates = [
      r'C:\Program Files\WinRAR\WinRAR.exe',
      r'C:\Program Files (x86)\WinRAR\WinRAR.exe',
    ];
    for (final c in candidates) {
      if (await File(c).exists()) return c;
    }
    return null;
  }
  /// 目标目录只有一个子目录且无其他文件时,把子目录内容上移一层
  Future<void> _flattenSingleRoot(String destDir) async {
    final dest = Directory(destDir);