905086
2026-11-04 9975888d222206fd358d0f2c159a28a6abc1a404
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
import 'dart:async';
import 'dart:convert';
import 'dart:io';
 
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
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 DownloadTask {
  final int gameId;
  final String title;
  final List<DownloadTaskFile> files;
  double speed = 0; // bytes/s
  bool autoShutdown = false;
  bool paused = false;
  bool finished = false;
  bool canceled = false;
  DateTime? startTime;
 
  DownloadTask(
      {required this.gameId,
      required this.title,
      required List<DownloadTaskFile> files})
      : 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;
 
  bool get hasActive => activeTask != null && !activeTask!.finished;
 
  void clear() {
    activeTask?.canceled = true;
    tasks.clear();
    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 '请先在右上角菜单中设置下载安装路径';
    }
    // 没有文件的游戏:创建占位文件任务(演示下载流程)
    final tasks = <DownloadTaskFile>[];
    if (fileList.isEmpty) {
      final demoSize = _parseSizeToBytes(game.size);
      tasks.add(DownloadTaskFile(
          name: '${game.title}.part01.rar',
          url: '',
          totalBytes: demoSize));
    } else {
      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);
    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\\${_safeName(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.isEmpty) {
          // 演示模式:模拟下载
          await _simulateDownload(task, file);
        } else {
          await _downloadFile(task, file, '${dir.path}\\${file.name}');
        }
        if (task.canceled || task.paused) break;
        file.status = DownloadStatus.done;
        notifyListeners();
      }
      if (!task.canceled && !task.paused) {
        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<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'[\\/:*?"<>|]'), '_');
}