905086
2026-11-07 0b4478cf6c0eb509c95a9bec2cc7bda37b259e10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
import 'dart:async';
import 'dart:convert';
import 'dart:io';
 
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';
 
class AppState extends ChangeNotifier {
  bool loggedIn = false;
  int userId = 0;
  String phone = '';
  bool isMember = false;
  String memberExpire = '';
 
  /// 数据版本号:收藏/资源库变化时递增,页面监听后刷新
  int favoritesVersion = 0;
  int libraryVersion = 0;
 
  static final AppState instance = AppState();
 
  void bumpFavorites() {
    favoritesVersion++;
    notifyListeners();
  }
 
  void bumpLibrary() {
    libraryVersion++;
    notifyListeners();
  }
 
  Future<void> refreshUserInfo() async {
    try {
      final res = await ApiService.userInfo();
      if (res['code'] == 0) {
        final d = res['data'];
        loggedIn = true;
        userId = d['id'];
        phone = d['phone'];
        final member = d['member'] ?? {};
        isMember = member['is_member'] == true;
        memberExpire = member['expire_at'] ?? '';
        notifyListeners();
      } else {
        logout();
      }
    } catch (_) {
      // 网络错误保持现状
    }
  }
 
  void logout() {
    loggedIn = false;
    userId = 0;
    phone = '';
    isMember = false;
    memberExpire = '';
    ApiClient.clearToken();
    DownloadManager.instance.clear();
    notifyListeners();
  }
}
 
enum DownloadStatus { waiting, preparing, downloading, paused, done, failed }
 
class DownloadTaskFile {
  final String name;
  final String url;
  double totalBytes;
  double received = 0;
  DownloadStatus status = DownloadStatus.waiting;
  CancelToken? cancelToken;
  DownloadTaskFile(
      {required this.name, required this.url, required this.totalBytes});
 
  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;
  bool finished = false;
  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.isTool = false})
      : files = files;
 
  double get totalBytes =>
      files.fold(0, (sum, f) => sum + f.totalBytes);
  double get receivedBytes =>
      files.fold(0, (sum, f) => sum + f.received);
 
  double get progress {
    final total = totalBytes;
    return total > 0 ? receivedBytes / total : 0;
  }
 
  int get etaSeconds {
    if (speed <= 0) return 0;
    final remain = totalBytes - receivedBytes;
    if (remain <= 0) return 0;
    return (remain / speed).round();
  }
}
 
class DownloadManager extends ChangeNotifier {
  static final DownloadManager instance = DownloadManager._();
  DownloadManager._();
 
  final List<DownloadTask> tasks = [];
  DownloadTask? activeTask;
  bool _loopRunning = false;
  int _extractTargets = 0; // 需解压的压缩包数量
  int _extractDone = 0; // 已完成解压的压缩包数量
 
  bool get hasActive => activeTask != null && !activeTask!.finished;
 
  void clear() {
    activeTask?.canceled = true;
    tasks.clear();
    activeTask = null;
    notifyListeners();
  }
 
  /// 清除指定游戏已完成的任务记录(卸载后不再视为已安装;不影响工具任务)
  void clearFinishedTask(int gameId) {
    final t = activeTask;
    if (t != null && !t.isTool && t.gameId == gameId && t.finished) {
      activeTask = null;
      notifyListeners();
    }
  }
 
  Future<void> startDownload(Game game) async {
    // 获取下载文件列表(服务端校验会员)
    final res = await ApiService.downloadInfo(game.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: game.id,
        title: game.title,
        files: tasks,
        launchExe: (res['data']['launch_exe'] ?? '') as String);
    this.tasks.insert(0, task);
    activeTask = task;
    notifyListeners();
    _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;
    if (raw is String && raw.trim().isNotEmpty) {
      try {
        final d = jsonDecode(raw);
        if (d is List) return d;
      } catch (_) {}
    }
    return [];
  }
 
  double _parseSizeToBytes(String s) {
    final m = RegExp(r'([\d.]+)\s*(GB|MB|KB|B)').firstMatch(s.toUpperCase());
    if (m == null) return 1024 * 1024 * 1024;
    final v = double.parse(m.group(1)!);
    switch (m.group(2)) {
      case 'GB':
        return v * 1024 * 1024 * 1024;
      case 'MB':
        return v * 1024 * 1024;
      case 'KB':
        return v * 1024;
      default:
        return v;
    }
  }
 
  void pause() {
    if (activeTask == null) return;
    activeTask!.paused = true;
    activeTask!.speed = 0;
    for (final f in activeTask!.files) {
      if (f.status == DownloadStatus.downloading ||
          f.status == DownloadStatus.preparing) {
        f.status = DownloadStatus.paused;
      }
      f.cancelToken?.cancel('paused');
    }
    notifyListeners();
  }
 
  void resume() {
    if (activeTask == null) return;
    activeTask!.paused = false;
    _runLoop();
    notifyListeners();
  }
 
  void cancelTask() {
    if (activeTask == null) return;
    activeTask!.canceled = true;
    for (final f in activeTask!.files) {
      f.cancelToken?.cancel('canceled');
    }
    activeTask = null;
    notifyListeners();
  }
 
  void _runLoop() async {
    if (_loopRunning) return;
    _loopRunning = true;
    try {
      final task = activeTask!;
      task.startTime = DateTime.now();
      final dlPath = await AppPrefs.getDownloadPath();
      final dir = Directory('$dlPath\\${safeFileName(task.title)}');
      await dir.create(recursive: true);
 
      for (final file in task.files) {
        if (task.canceled || task.paused) break;
        file.status = DownloadStatus.preparing;
        notifyListeners();
        await Future.delayed(const Duration(milliseconds: 300));
        if (task.canceled || task.paused) break;
 
        if (file.url.isNotEmpty) {
          await _downloadFile(task, file, '${dir.path}\\${file.name}');
        }
        if (task.canceled || task.paused) break;
        file.status = DownloadStatus.done;
        notifyListeners();
      }
      if (!task.canceled && !task.paused) {
        // 下载完成:解压压缩包到安装目录并删除压缩包
        await _installTask(task, dir.path);
        task.finished = true;
        notifyListeners();
      }
    } catch (e) {
      debugLog('download loop error: $e');
    } finally {
      _loopRunning = false;
      notifyListeners();
    }
  }
 
  Future<void> _downloadFile(
      DownloadTask task, DownloadTaskFile file, String savePath) async {
    file.status = DownloadStatus.downloading;
    file.cancelToken = CancelToken();
    notifyListeners();
    int lastReceived = 0;
    DateTime lastTime = DateTime.now();
    try {
      await ApiClient.dio.download(
        file.url,
        savePath,
        cancelToken: file.cancelToken,
        onReceiveProgress: (count, total) {
          if (total > 0) file.totalBytes = total.toDouble();
          file.received = count.toDouble();
          final now = DateTime.now();
          final diff = now.difference(lastTime).inMilliseconds;
          if (diff >= 500) {
            task.speed =
                (count - lastReceived) * 1000 / diff;
            lastReceived = count;
            lastTime = now;
          }
          notifyListeners();
        },
      );
      task.speed = 0;
      notifyListeners();
    } on DioException catch (e) {
      if (e.type == DioExceptionType.cancel) {
        file.status = DownloadStatus.paused;
      } else {
        file.status = DownloadStatus.failed;
      }
      notifyListeners();
      rethrow;
    }
  }
 
  /// 安装目录(与资源库启动逻辑保持一致)
  Future<String> _installDir(String title) => gameInstallDir(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;
    task.extractProgress = 0;
    task.extractLog.clear();
    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);
        }
      }
      _extractTargets = archives.length - skip.length;
      _extractDone = 0;
      for (final a in archives) {
        if (skip.contains(a.path)) continue;
        await _extractArchive(a, installPath, task);
      }
      task.extractProgress = 1;
      // 全部解压完成后删除压缩包
      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();
    }
  }
 
  /// 解压单个压缩包到目标目录(7z 时流式读取输出获取进度与文件名)
  Future<void> _extractArchive(
      File archive, String destDir, DownloadTask task) async {
    final lower = archive.path.toLowerCase();
    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:使用本机已安装的 WinRAR(无进度输出,模拟进度前进)
      final rar = await _findWinRar();
      if (rar == null) {
        throw '未找到 7-Zip 或 WinRAR,无法解压 ${p.basename(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);
  }
 
  /// 解压无进度输出时(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',
    ];
    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<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);
    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();
  }
}