feat: 支持游戏启动程序配置与自动解压安装
- 新增游戏启动程序字段,管理端可配置,客户端启动时优先使用
- 实现下载后自动解压压缩包到安装目录,删除压缩包
- 修复大文件上传临时目录问题,改为程序目录下的uploads/tmp
- 优化商店页和收藏页的游戏卡片布局,避免空白区域
- 优化安装包上传进度显示,防止保存时数据不完整
2 files added
14 files modified
| | |
| | | final String gpuReq; |
| | | final String ramReq; |
| | | final String versionNote; |
| | | final String launchExe; // 启动程序相对路径(相对游戏安装目录) |
| | | final String cover; |
| | | final String video; |
| | | final List<String> screenshots; |
| | |
| | | required this.gpuReq, |
| | | required this.ramReq, |
| | | required this.versionNote, |
| | | required this.launchExe, |
| | | required this.cover, |
| | | required this.video, |
| | | required this.screenshots, |
| | |
| | | gpuReq: j['gpu_req'] ?? '', |
| | | ramReq: j['ram_req'] ?? '', |
| | | versionNote: j['version_note'] ?? '', |
| | | launchExe: j['launch_exe'] ?? '', |
| | | cover: j['cover'] ?? '', |
| | | video: j['video'] ?? '', |
| | | screenshots: shots, |
| | |
| | | |
| | | Future<void> _download() async { |
| | | if (game == null) return; |
| | | // 检查下载路径 |
| | | var dlPath = await AppPrefs.getDownloadPath(); |
| | | if (dlPath.isEmpty) { |
| | | final ok = await _askDownloadPath(); |
| | | if (!ok) return; |
| | | dlPath = await AppPrefs.getDownloadPath(); |
| | | } |
| | | // 每次下载前都弹出选择下载安装路径 |
| | | final ok = await _askDownloadPath(); |
| | | if (!ok) return; |
| | | // 会员校验+开始下载 |
| | | try { |
| | | await DownloadManager.instance.startDownload(game!); |
| | |
| | | } |
| | | } |
| | | |
| | | /// 首次下载询问下载路径 |
| | | /// 下载前选择下载安装路径 |
| | | Future<bool> _askDownloadPath() async { |
| | | final res = await ApiService.downloadInfo(widget.gameId); |
| | | if (res['code'] != 0) { |
| | | if (mounted) _toast(res['msg'] ?? '无法下载', error: true); |
| | | return false; |
| | | } |
| | | final result = await showDialog<bool>( |
| | | context: context, |
| | | builder: (context) => _DownloadPathDialog(gameTitle: game!.title), |
| | |
| | | ], |
| | | ), |
| | | ) |
| | | : GridView.builder( |
| | | padding: const EdgeInsets.only(bottom: 40), |
| | | gridDelegate: |
| | | const SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 4, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: 16, |
| | | childAspectRatio: 0.62, |
| | | ), |
| | | itemCount: games.length, |
| | | itemBuilder: (context, i) => GameCard(game: games[i]), |
| | | ), |
| | | : LayoutBuilder(builder: (context, constraints) { |
| | | // 卡片高度 = 封面高度 + 信息区实际内容高度,避免出现大段空白 |
| | | const crossAxisSpacing = 16.0; |
| | | final cardWidth = |
| | | (constraints.maxWidth - crossAxisSpacing * 3) / 4; |
| | | final coverHeight = cardWidth / 1.42; |
| | | const infoHeight = 96.0; |
| | | return GridView.builder( |
| | | padding: const EdgeInsets.only(bottom: 40), |
| | | gridDelegate: |
| | | SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 4, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: crossAxisSpacing, |
| | | mainAxisExtent: coverHeight + infoHeight, |
| | | ), |
| | | itemCount: games.length, |
| | | itemBuilder: (context, i) => GameCard(game: games[i]), |
| | | ); |
| | | }), |
| | | ), |
| | | ], |
| | | ), |
| | |
| | | ], |
| | | ), |
| | | ) |
| | | : GridView.builder( |
| | | padding: const EdgeInsets.only(bottom: 40), |
| | | gridDelegate: |
| | | const SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 5, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: 16, |
| | | childAspectRatio: 0.60, |
| | | ), |
| | | itemCount: filtered.length, |
| | | itemBuilder: (context, i) => |
| | | _LibraryCard(game: filtered[i], onRemove: _load), |
| | | ), |
| | | : LayoutBuilder(builder: (context, constraints) { |
| | | // 卡片高度 = 封面高度 + 信息区实际内容高度,避免出现大段空白 |
| | | const crossAxisSpacing = 16.0; |
| | | final cardWidth = |
| | | (constraints.maxWidth - crossAxisSpacing * 4) / 5; |
| | | final coverHeight = cardWidth / 1.42; |
| | | const infoHeight = 92.0; |
| | | return GridView.builder( |
| | | padding: const EdgeInsets.only(bottom: 40), |
| | | gridDelegate: |
| | | SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 5, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: crossAxisSpacing, |
| | | mainAxisExtent: coverHeight + infoHeight, |
| | | ), |
| | | itemCount: filtered.length, |
| | | itemBuilder: (context, i) => |
| | | _LibraryCard(game: filtered[i], onRemove: _load), |
| | | ); |
| | | }), |
| | | ), |
| | | ], |
| | | ), |
| | |
| | | |
| | | Future<void> _launch(BuildContext context) async { |
| | | final dir = await _installDir(); |
| | | // 尝试查找目录中的exe并启动(启动已下载的游戏不需要会员) |
| | | final d = Directory(dir); |
| | | if (await d.exists()) { |
| | | // 优先启动管理端设置的启动程序 |
| | | if (game.launchExe.isNotEmpty) { |
| | | final exe = File(p.join(dir, game.launchExe)); |
| | | if (await exe.exists()) { |
| | | Process.run(exe.path, [], |
| | | workingDirectory: p.dirname(exe.path)); |
| | | return; |
| | | } |
| | | } |
| | | // 未设置或找不到时,尝试查找目录中的exe并启动(启动已下载的游戏不需要会员) |
| | | final exes = d |
| | | .listSync(recursive: false) |
| | | .whereType<File>() |
| | |
| | | } |
| | | return Padding( |
| | | padding: const EdgeInsets.symmetric(horizontal: 70), |
| | | child: GridView.builder( |
| | | shrinkWrap: true, |
| | | physics: const NeverScrollableScrollPhysics(), |
| | | gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 4, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: 16, |
| | | childAspectRatio: 0.62, |
| | | ), |
| | | itemCount: games.length, |
| | | itemBuilder: (context, i) => GameCard(game: games[i]), |
| | | ), |
| | | child: LayoutBuilder(builder: (context, constraints) { |
| | | // 卡片高度 = 封面高度 + 信息区实际内容高度,避免信息区出现大段空白 |
| | | const crossAxisSpacing = 16.0; |
| | | final cardWidth = |
| | | (constraints.maxWidth - crossAxisSpacing * 3) / 4; |
| | | final coverHeight = cardWidth / 1.42; // 与 GameCard 封面 AspectRatio 一致 |
| | | const infoHeight = 96.0; // 版本行 + 标题两行 + 类别/添加按钮行 + 内边距 |
| | | return GridView.builder( |
| | | shrinkWrap: true, |
| | | physics: const NeverScrollableScrollPhysics(), |
| | | gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( |
| | | crossAxisCount: 4, |
| | | mainAxisSpacing: 18, |
| | | crossAxisSpacing: crossAxisSpacing, |
| | | mainAxisExtent: coverHeight + infoHeight, |
| | | ), |
| | | itemCount: games.length, |
| | | itemBuilder: (context, i) => GameCard(game: games[i]), |
| | | ); |
| | | }), |
| | | ); |
| | | } |
| | | |
| | |
| | | |
| | | 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); |
| | | throw '该游戏暂无下载文件,请联系管理员上传游戏压缩包'; |
| | | } |
| | | final tasks = <DownloadTaskFile>[]; |
| | | for (final f in fileList) { |
| | | 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'))); |
| | | } |
| | | 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(); |
| | | } |
| | | } |
| | |
| | | Row( |
| | | children: [ |
| | | Text( |
| | | task.finished |
| | | ? '下载完成' |
| | | : task.paused |
| | | ? '已暂停' |
| | | : '正在下载', |
| | | style: TextStyle( |
| | | color: task.paused |
| | | ? AppColors.yellow |
| | | task.extracting |
| | | ? '正在解压安装...' |
| | | : task.extractFailed |
| | | ? '解压失败' |
| | | : task.finished |
| | | ? AppColors.green |
| | | : AppColors.accent, |
| | | ? '下载完成' |
| | | : task.paused |
| | | ? '已暂停' |
| | | : '正在下载', |
| | | style: TextStyle( |
| | | color: task.extractFailed |
| | | ? AppColors.red |
| | | : task.paused |
| | | ? AppColors.yellow |
| | | : task.finished |
| | | ? AppColors.green |
| | | : AppColors.accent, |
| | | fontSize: 14, |
| | | fontWeight: FontWeight.w500), |
| | | ), |
| | |
| | | ), |
| | | const SizedBox(height: 8), |
| | | Text( |
| | | '${formatBytes(task.speed)}/s', |
| | | task.extracting |
| | | ? '解压中,请勿关闭软件' |
| | | : task.extractFailed |
| | | ? '压缩包保留在下载目录,可手动解压' |
| | | : '${formatBytes(task.speed)}/s', |
| | | style: const TextStyle( |
| | | color: AppColors.textGray, fontSize: 13), |
| | | ), |
| | |
| | | children: [ |
| | | Expanded( |
| | | child: ElevatedButton( |
| | | onPressed: task.finished |
| | | onPressed: task.finished || task.extracting |
| | | ? null |
| | | : () { |
| | | if (task.paused) { |
| | |
| | | <div id="g_shots_list"></div> |
| | | </div> |
| | | <div class="upload-box"> |
| | | <div class="hint">游戏安装包(zip/rar/exe/iso 等,可多选)</div> |
| | | <div class="hint">游戏压缩包(游戏安装目录打包成的 zip/rar/7z,可多选。用户下载后自动解压到游戏目录并删除压缩包)</div> |
| | | <input type="file" multiple onchange="uploadPackages(this)"> |
| | | <div id="g_files_list"></div> |
| | | </div> |
| | | <div class="form-row"><label>游戏启动程序(相对路径,如 Binaries\Win64\Game.exe,用户启动游戏时直接打开)</label><input id="g_launch_exe" placeholder="Binaries\Win64\Game.exe"></div> |
| | | <div class="form-row"><label>游戏介绍(说明图片文字)</label><textarea id="g_description"></textarea></div> |
| | | <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px"> |
| | | <button class="btn btn-gray" onclick="hideGameModal()">取消</button> |
| | | <button class="btn" onclick="saveGame()">保存</button> |
| | | <button class="btn" id="saveGameBtn" onclick="saveGame()">保存</button> |
| | | </div> |
| | | </div> |
| | | </div> |
| | |
| | | setTimeout(() => t.className = 'toast', 2500); |
| | | } |
| | | async function api(path, opts = {}) { |
| | | opts.headers = Object.assign({'Content-Type': 'application/json'}, opts.headers || {}); |
| | | opts.headers = Object.assign({}, opts.headers || {}); |
| | | if (token) opts.headers['Authorization'] = 'Bearer ' + token; |
| | | if (opts.body && typeof opts.body !== 'string' && !(opts.body instanceof FormData)) { |
| | | opts.body = JSON.stringify(opts.body); |
| | | // FormData(文件上传)不能手动设置 Content-Type,由浏览器自动生成 multipart 边界 |
| | | if (opts.body instanceof FormData) { |
| | | if (opts.headers['Content-Type']) delete opts.headers['Content-Type']; |
| | | } else { |
| | | opts.headers['Content-Type'] = 'application/json'; |
| | | if (opts.body && typeof opts.body !== 'string') { |
| | | opts.body = JSON.stringify(opts.body); |
| | | } |
| | | } |
| | | const res = await fetch(path, opts); |
| | | if (res.status === 401) { localStorage.removeItem('admin_token'); location.reload(); throw new Error('未登录'); } |
| | |
| | | g_size.value = g.size || ''; g_install_size.value = g.install_size || ''; |
| | | g_os.value = g.os_req || ''; g_cpu.value = g.cpu_req || ''; g_gpu.value = g.gpu_req || ''; g_ram.value = g.ram_req || ''; |
| | | g_version_note.value = g.version_note || ''; g_description.value = g.description || ''; |
| | | g_launch_exe.value = g.launch_exe || ''; |
| | | g_platform.value = g.platform || 'pc'; g_banner.value = g.is_banner ? '1' : '0'; |
| | | g_cover.value = g.cover || ''; g_video.value = g.video || ''; |
| | | try { editingScreenshots = JSON.parse(g.screenshots || '[]'); } catch(e) {} |
| | |
| | | toast('上传成功'); |
| | | } |
| | | async function uploadScreenshots(input) { |
| | | let ok = 0, fail = 0; |
| | | for (const f of input.files) { |
| | | const fd = new FormData(); |
| | | fd.append('file', f); fd.append('type', 'image'); |
| | | const res = await api('/admin/api/upload', {method: 'POST', body: fd}); |
| | | if (res.code === 0) editingScreenshots.push(res.data.url); |
| | | if (res.code === 0) { editingScreenshots.push(res.data.url); ok++; } |
| | | else { fail++; toast(f.name + ':' + (res.msg || '上传失败'), true); } |
| | | } |
| | | renderShots(); toast('截图上传完成'); |
| | | renderShots(); |
| | | if (ok > 0) toast(`截图上传完成(${ok}个${fail > 0 ? ',失败' + fail + '个' : ''})`); |
| | | } |
| | | async function uploadPackages(input) { |
| | | if (!input.files.length) return; |
| | | let ok = 0, fail = 0; |
| | | setSaveEnabled(false); |
| | | for (const f of input.files) { |
| | | const fd = new FormData(); |
| | | fd.append('file', f); fd.append('type', 'file'); |
| | | const res = await api('/admin/api/upload', {method: 'POST', body: fd}); |
| | | if (res.code === 0) editingFiles.push({name: res.data.name, size: res.data.size, url: res.data.url}); |
| | | try { |
| | | // 大文件用 XHR 上传并显示进度 |
| | | const res = await new Promise((resolve, reject) => { |
| | | const xhr = new XMLHttpRequest(); |
| | | xhr.open('POST', '/admin/api/upload'); |
| | | if (token) xhr.setRequestHeader('Authorization', 'Bearer ' + token); |
| | | xhr.upload.onprogress = e => { |
| | | if (e.lengthComputable) renderUploadProgress(f.name, e.loaded, e.total); |
| | | }; |
| | | xhr.onload = () => { try { resolve(JSON.parse(xhr.responseText)); } catch (err) { reject(err); } }; |
| | | xhr.onerror = () => reject(new Error('网络错误')); |
| | | xhr.send(fd); |
| | | }); |
| | | if (res.code === 0) { editingFiles.push({name: res.data.name, size: res.data.size, url: res.data.url}); ok++; } |
| | | else { fail++; toast(f.name + ':' + (res.msg || '上传失败'), true); } |
| | | } catch (e) { |
| | | fail++; toast(f.name + ':上传失败(' + e.message + ')', true); |
| | | } |
| | | } |
| | | renderFiles(); toast('安装包上传完成'); |
| | | setSaveEnabled(true); |
| | | renderFiles(); |
| | | if (ok > 0) toast(`安装包上传完成(${ok}个${fail > 0 ? ',失败' + fail + '个' : ''})`); |
| | | } |
| | | /// 压缩包上传中时禁用保存按钮,防止保存了空的文件列表 |
| | | function setSaveEnabled(enabled) { |
| | | const btn = document.getElementById('saveGameBtn'); |
| | | if (btn) { btn.disabled = !enabled; btn.style.opacity = enabled ? '' : '0.5'; } |
| | | } |
| | | function renderUploadProgress(name, loaded, total) { |
| | | const pct = Math.floor(loaded / total * 100); |
| | | const size = total > 1024*1024*1024 ? (total/1024/1024/1024).toFixed(2)+' GB' |
| | | : total > 1024*1024 ? (total/1024/1024).toFixed(1)+' MB' : (total/1024).toFixed(0)+' KB'; |
| | | document.getElementById('g_files_list').innerHTML = |
| | | `<div class="file-item"><span>${name}(${size})上传中 ${pct}%</span></div>`; |
| | | } |
| | | function renderShots() { |
| | | document.getElementById('g_shots_list').innerHTML = editingScreenshots.map((u, i) => |
| | |
| | | platform: g_platform.value, tags: g_tags.value.trim(), |
| | | size: g_size.value.trim(), install_size: g_install_size.value.trim(), |
| | | os_req: g_os.value.trim(), cpu_req: g_cpu.value.trim(), gpu_req: g_gpu.value.trim(), ram_req: g_ram.value.trim(), |
| | | version_note: g_version_note.value.trim(), cover: g_cover.value, video: g_video.value, |
| | | version_note: g_version_note.value.trim(), launch_exe: g_launch_exe.value.trim(), cover: g_cover.value, video: g_video.value, |
| | | screenshots: JSON.stringify(editingScreenshots), description: g_description.value, |
| | | files: JSON.stringify(editingFiles), is_banner: g_banner.value === '1', |
| | | }; |
| | |
| | | "title": game.Title, "category_id": game.CategoryID, "platform": game.Platform, |
| | | "tags": game.Tags, "size": game.Size, "install_size": game.InstallSize, |
| | | "os_req": game.OSReq, "cpu_req": game.CPUReq, "gpu_req": game.GPUReq, "ram_req": game.RAMReq, |
| | | "version_note": game.VersionNote, "cover": game.Cover, "video": game.Video, |
| | | "version_note": game.VersionNote, "launch_exe": game.LaunchExe, "cover": game.Cover, "video": game.Video, |
| | | "screenshots": game.Screenshots, "description": game.Description, "files": game.Files, |
| | | "is_banner": game.IsBanner, |
| | | }) |
| | |
| | | } |
| | | config.DB.Model(&game).UpdateColumn("download_count", game.DownloadCount+1) |
| | | c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{ |
| | | "title": game.Title, |
| | | "files": game.Files, |
| | | "title": game.Title, |
| | | "files": game.Files, |
| | | "launch_exe": game.LaunchExe, |
| | | }}) |
| | | } |
| | |
| | | package main |
| | | |
| | | import ( |
| | | "os" |
| | | "path/filepath" |
| | | |
| | | "gamebox-server/config" |
| | | "gamebox-server/handlers" |
| | | "gamebox-server/middleware" |
| | |
| | | ) |
| | | |
| | | func main() { |
| | | // 大文件上传时 multipart 会先写系统临时目录(C盘), |
| | | // 系统盘空间不足会导致大压缩包上传失败,这里指到程序目录下的 uploads/tmp |
| | | if abs, err := filepath.Abs(filepath.Join("uploads", "tmp")); err == nil { |
| | | os.MkdirAll(abs, 0755) |
| | | os.Setenv("TMP", abs) |
| | | os.Setenv("TEMP", abs) |
| | | } |
| | | |
| | | config.InitDB() |
| | | |
| | | r := gin.Default() |
| | |
| | | GPUReq string `gorm:"size:100" json:"gpu_req"` |
| | | RAMReq string `gorm:"size:100" json:"ram_req"` |
| | | VersionNote string `gorm:"size:500" json:"version_note"` // V1.685.421顶级版|容量175GB|官方简体中文... |
| | | LaunchExe string `gorm:"size:255" json:"launch_exe"` // 游戏启动程序相对路径(相对游戏安装目录),如 Binaries\Win64\Game.exe |
| | | Cover string `gorm:"size:255" json:"cover"` |
| | | Video string `gorm:"size:255" json:"video"` |
| | | Screenshots string `gorm:"type:text" json:"screenshots"` // JSON数组 |