From 0b4478cf6c0eb509c95a9bec2cc7bda37b259e10 Mon Sep 17 00:00:00 2001
From: 905086 <k2049@qq.com>
Date: Sat, 07 Nov 2026 19:06:06 +0800
Subject: [PATCH] feat: 新增工具管理功能及工具下载安装流程
---
server/models/models.go | 5
server/handlers/admin.go | 2
fluttergamebox/lib/store/app_state.dart | 41 ++++++
server/handlers/games.go | 41 ++++++
fluttergamebox/lib/pages/library_page.dart | 1
fluttergamebox/lib/pages/main_shell.dart | 17 ++
fluttergamebox/lib/api/api_service.dart | 6 +
server/handlers/auth.go | 4
fluttergamebox/lib/pages/detail_page.dart | 1
fluttergamebox/lib/pages/tools_page.dart | 166 +++++++++++++++++++--------
server/admin/index.html | 7 +
server/main.go | 1
fluttergamebox/lib/widgets/download_manager.dart | 12 +-
13 files changed, 235 insertions(+), 69 deletions(-)
diff --git a/fluttergamebox/lib/api/api_service.dart b/fluttergamebox/lib/api/api_service.dart
index a5626ea..65e230b 100644
--- a/fluttergamebox/lib/api/api_service.dart
+++ b/fluttergamebox/lib/api/api_service.dart
@@ -118,6 +118,7 @@
final String cover;
final String description;
final String fileUrl;
+ final String launchExe;
Tool({
required this.id,
required this.name,
@@ -125,6 +126,7 @@
required this.cover,
required this.description,
required this.fileUrl,
+ this.launchExe = '',
});
factory Tool.fromJson(Map<String, dynamic> j) => Tool(
id: j['id'],
@@ -133,6 +135,7 @@
cover: j['cover'] ?? '',
description: j['description'] ?? '',
fileUrl: j['file_url'] ?? '',
+ launchExe: j['launch_exe'] ?? '',
);
}
@@ -190,6 +193,9 @@
return (res['data'] as List).map((e) => Tool.fromJson(e)).toList();
}
+ static Future<Map<String, dynamic>> toolDownloadInfo(int toolId) async =>
+ await ApiClient.get('/api/tools/$toolId/download');
+
static Future<String> announcements() async {
final res = await ApiClient.get('/api/announcements');
if (res['code'] != 0) return '';
diff --git a/fluttergamebox/lib/pages/detail_page.dart b/fluttergamebox/lib/pages/detail_page.dart
index a11abbe..cf4a0d3 100644
--- a/fluttergamebox/lib/pages/detail_page.dart
+++ b/fluttergamebox/lib/pages/detail_page.dart
@@ -537,6 +537,7 @@
final installed = _installed ||
(t != null &&
t.gameId == game!.id &&
+ !t.isTool &&
t.finished &&
!t.extractFailed);
return SizedBox(
diff --git a/fluttergamebox/lib/pages/library_page.dart b/fluttergamebox/lib/pages/library_page.dart
index f19c476..706f3c8 100644
--- a/fluttergamebox/lib/pages/library_page.dart
+++ b/fluttergamebox/lib/pages/library_page.dart
@@ -371,6 +371,7 @@
return _installed ||
(t != null &&
t.gameId == widget.game.id &&
+ !t.isTool &&
t.finished &&
!t.extractFailed);
}
diff --git a/fluttergamebox/lib/pages/main_shell.dart b/fluttergamebox/lib/pages/main_shell.dart
index b02184b..cbbac32 100644
--- a/fluttergamebox/lib/pages/main_shell.dart
+++ b/fluttergamebox/lib/pages/main_shell.dart
@@ -620,7 +620,7 @@
case '游戏恢复':
_showToast('游戏恢复功能:重新下载可恢复游戏文件');
case '重启应用':
- _showToast('应用重启中...');
+ _restartApp();
case '检查更新':
_showToast('当前已是最新版本!');
case '退出应用':
@@ -628,6 +628,21 @@
}
}
+ /// 重启应用:启动新的应用进程后退出当前进程
+ Future<void> _restartApp() async {
+ try {
+ // 以分离模式启动当前应用的 exe(带原有启动参数)
+ await Process.start(
+ Platform.resolvedExecutable,
+ Platform.executableArguments,
+ mode: ProcessStartMode.detached,
+ );
+ } catch (_) {
+ // 启动失败时仍尝试退出(下次手动打开)
+ }
+ exit(0);
+ }
+
void _showToast(String msg) {
final ctx = context;
// 使用全局 overlay 显示
diff --git a/fluttergamebox/lib/pages/tools_page.dart b/fluttergamebox/lib/pages/tools_page.dart
index 81d01d4..dcc8e5e 100644
--- a/fluttergamebox/lib/pages/tools_page.dart
+++ b/fluttergamebox/lib/pages/tools_page.dart
@@ -1,4 +1,4 @@
-import 'package:flutter/material.dart';
+import 'package:flutter/material.dart';
import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/api/api_service.dart';
import 'package:fluttergamebox/common/theme.dart';
@@ -15,7 +15,6 @@
class _ToolsPageState extends State<ToolsPage>
with AutomaticKeepAliveClientMixin {
List<Tool> tools = [];
- final Set<int> _installed = {};
bool _loading = true;
@override
@@ -36,14 +35,7 @@
});
}
- Future<void> _install(Tool tool) async {
- if (_installed.contains(tool.id)) return;
- // 模拟安装
- setState(() => _installed.add(tool.id));
- _toast('${tool.name} 安装完成');
- }
-
- void _toast(String msg) {
+ void _toast(String msg, {bool error = false}) {
final overlay = Overlay.of(context);
final entry = OverlayEntry(
builder: (context) => Positioned(
@@ -56,12 +48,12 @@
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
- color: AppColors.green,
+ color: error ? AppColors.red : AppColors.green,
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
- const Icon(Icons.check_circle,
+ Icon(error ? Icons.error_outline : Icons.check_circle,
color: Colors.white, size: 18),
const SizedBox(width: 8),
Expanded(
@@ -100,8 +92,8 @@
fontWeight: FontWeight.w500)),
const SizedBox(width: 12),
const Text('游戏必备运行库和实用工具',
- style: TextStyle(
- color: AppColors.textGray, fontSize: 13)),
+ style:
+ TextStyle(color: AppColors.textGray, fontSize: 13)),
],
),
const SizedBox(height: 16),
@@ -126,7 +118,7 @@
),
itemCount: tools.length,
itemBuilder: (context, i) =>
- _ToolCard(tool: tools[i], installed: _installed.contains(tools[i].id), onInstall: () => _install(tools[i])),
+ _ToolCard(tool: tools[i], onError: _toast),
),
),
],
@@ -135,15 +127,50 @@
}
}
-class _ToolCard extends StatelessWidget {
+class _ToolCard extends StatefulWidget {
final Tool tool;
- final bool installed;
- final VoidCallback onInstall;
- const _ToolCard({
- required this.tool,
- required this.installed,
- required this.onInstall,
- });
+ final void Function(String msg, {bool error}) onError;
+ const _ToolCard({required this.tool, required this.onError});
+ @override
+ State<_ToolCard> createState() => _ToolCardState();
+}
+
+class _ToolCardState extends State<_ToolCard> {
+ bool _installed = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _checkInstalled();
+ }
+
+ Future<void> _checkInstalled() async {
+ final ok = await isGameInstalled(widget.tool.name, widget.tool.launchExe);
+ if (mounted) setState(() => _installed = ok);
+ }
+
+ /// 启动已安装的工具
+ Future<void> _launch() async {
+ final ok =
+ await launchInstalledGame(widget.tool.name, widget.tool.launchExe);
+ if (!ok) widget.onError('未找到工具文件,请重新下载安装', error: true);
+ }
+
+ /// 安装:选择下载路径后下载并解压(与游戏流程一致)
+ Future<void> _install() async {
+ final ok = await showDialog<bool>(
+ context: context,
+ builder: (context) =>
+ DownloadPathDialog(gameTitle: widget.tool.name),
+ );
+ if (ok != true) return;
+ try {
+ await DownloadManager.instance.startToolDownload(widget.tool);
+ if (mounted) showDownloadDialog(context);
+ } catch (e) {
+ widget.onError(e.toString(), error: true);
+ }
+ }
@override
Widget build(BuildContext context) {
@@ -163,13 +190,13 @@
borderRadius: const BorderRadius.vertical(
top: Radius.circular(6)),
child: Image.network(
- ApiClient.baseUrl + tool.cover,
+ ApiClient.baseUrl + widget.tool.cover,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(
color: const Color(0xFF2A2E45),
child: Center(
child: Text(
- tool.name.characters.first,
+ widget.tool.name.characters.first,
style: const TextStyle(
color: AppColors.textDim, fontSize: 28),
),
@@ -202,37 +229,74 @@
padding: const EdgeInsets.all(10),
child: Column(
children: [
- Text(tool.description,
+ // 工具名称
+ Text(widget.tool.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
- color: Colors.white, fontSize: 12)),
+ color: Colors.white,
+ fontSize: 12,
+ fontWeight: FontWeight.w500)),
+ if (widget.tool.description.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ // 工具描述
+ Text(widget.tool.description,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ color: AppColors.textDim, fontSize: 11)),
+ ],
const SizedBox(height: 8),
- Row(
- children: [
- Text(tool.size,
- style: const TextStyle(
- color: AppColors.textDim, fontSize: 11)),
- const Spacer(),
- GestureDetector(
- onTap: onInstall,
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 14, vertical: 4),
- decoration: BoxDecoration(
- color: installed
- ? const Color(0xFF3A3F52)
- : AppColors.accent,
- borderRadius: BorderRadius.circular(3),
+ // 按钮状态随下载管理器任务实时变化
+ ListenableBuilder(
+ listenable: DownloadManager.instance,
+ builder: (context, _) {
+ final t = DownloadManager.instance.activeTask;
+ final busy = t != null &&
+ t.isTool &&
+ t.gameId == widget.tool.id &&
+ !t.finished;
+ final installed = _installed ||
+ (t != null &&
+ t.isTool &&
+ t.gameId == widget.tool.id &&
+ t.finished &&
+ !t.extractFailed);
+ return Row(
+ children: [
+ Text(widget.tool.size,
+ style: const TextStyle(
+ color: AppColors.textDim, fontSize: 11)),
+ const Spacer(),
+ GestureDetector(
+ onTap: busy
+ ? null
+ : () => installed ? _launch() : _install(),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 14, vertical: 4),
+ decoration: BoxDecoration(
+ color: busy
+ ? const Color(0xFF3A3F52)
+ : installed
+ ? AppColors.accent
+ : AppColors.green,
+ borderRadius: BorderRadius.circular(3),
+ ),
+ child: Text(
+ busy
+ ? '下载中'
+ : installed
+ ? '启动'
+ : '安装',
+ style: const TextStyle(
+ color: Colors.white, fontSize: 11),
+ ),
+ ),
),
- child: Text(
- installed ? '已安装' : '安装',
- style: const TextStyle(
- color: Colors.white, fontSize: 11),
- ),
- ),
- ),
- ],
+ ],
+ );
+ },
),
],
),
diff --git a/fluttergamebox/lib/store/app_state.dart b/fluttergamebox/lib/store/app_state.dart
index c9b9af0..bdcfcd9 100644
--- a/fluttergamebox/lib/store/app_state.dart
+++ b/fluttergamebox/lib/store/app_state.dart
@@ -91,6 +91,7 @@
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;
@@ -106,7 +107,8 @@
{required this.gameId,
required this.title,
required List<DownloadTaskFile> files,
- this.launchExe = ''})
+ this.launchExe = '',
+ this.isTool = false})
: files = files;
double get totalBytes =>
@@ -146,10 +148,10 @@
notifyListeners();
}
- /// 清除指定游戏已完成的任务记录(卸载后不再视为已安装)
+ /// 清除指定游戏已完成的任务记录(卸载后不再视为已安装;不影响工具任务)
void clearFinishedTask(int gameId) {
final t = activeTask;
- if (t != null && t.gameId == gameId && t.finished) {
+ if (t != null && !t.isTool && t.gameId == gameId && t.finished) {
activeTask = null;
notifyListeners();
}
@@ -188,6 +190,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;
diff --git a/fluttergamebox/lib/widgets/download_manager.dart b/fluttergamebox/lib/widgets/download_manager.dart
index 38c9446..ec5f683 100644
--- a/fluttergamebox/lib/widgets/download_manager.dart
+++ b/fluttergamebox/lib/widgets/download_manager.dart
@@ -54,7 +54,7 @@
Future<void> _launchGame(DownloadTask task) async {
final ok = await launchInstalledGame(task.title, task.launchExe);
if (!ok && mounted) {
- _toast('未找到游戏文件,请重新下载安装');
+ _toast(task.isTool ? '未找到工具文件,请重新下载安装' : '未找到游戏文件,请重新下载安装');
}
}
@@ -475,13 +475,13 @@
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: (task.finished && !task.extractFailed)
- ? const Row(
+ ? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
- Icon(Icons.play_arrow, size: 18),
- SizedBox(width: 8),
- Text('启动游戏',
- style: TextStyle(fontSize: 14)),
+ const Icon(Icons.play_arrow, size: 18),
+ const SizedBox(width: 8),
+ Text(task.isTool ? '启动' : '启动游戏',
+ style: const TextStyle(fontSize: 14)),
],
)
: const Text('取消安装'),
diff --git a/server/admin/index.html b/server/admin/index.html
index 5c6baf7..3777f69 100644
--- a/server/admin/index.html
+++ b/server/admin/index.html
@@ -96,9 +96,9 @@
<div class="nav-tabs">
<button class="active" data-tab="keys" onclick="switchTab('keys')">密钥管理</button>
<button data-tab="games" onclick="switchTab('games')">游戏管理</button>
+ <button data-tab="tools" onclick="switchTab('tools')">工具管理</button>
<button data-tab="cats" onclick="switchTab('cats')">类别管理</button>
<button data-tab="ann" onclick="switchTab('ann')">公告设置</button>
- <button data-tab="tools" onclick="switchTab('tools')">工具管理</button>
</div>
<button id="logoutBtn" onclick="logout()">退出登录</button>
</div>
@@ -246,6 +246,9 @@
<input id="t_file_url" placeholder="安装包URL,或点击上传">
<input type="file" onchange="uploadSingle(this, 'file', 't_file_url')">
</div>
+ <div class="form-row"><label>启动程序路径</label>
+ <input id="t_launch_exe" placeholder="解压后目录内的相对路径,如 A1524\\setup.exe">
+ </div>
<div class="form-row"><label>描述</label><textarea id="t_description"></textarea></div>
<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px">
<button class="btn btn-gray" onclick="hideToolModal()">取消</button>
@@ -595,6 +598,7 @@
document.getElementById('t_size').value = t ? (t.size || '') : '';
document.getElementById('t_cover').value = t ? (t.cover || '') : '';
document.getElementById('t_file_url').value = t ? (t.file_url || '') : '';
+ document.getElementById('t_launch_exe').value = t ? (t.launch_exe || '') : '';
document.getElementById('t_description').value = t ? (t.description || '') : '';
renderToolCover();
document.getElementById('toolModal').classList.remove('hidden');
@@ -607,6 +611,7 @@
size: document.getElementById('t_size').value.trim(),
cover: document.getElementById('t_cover').value.trim(),
file_url: document.getElementById('t_file_url').value.trim(),
+ launch_exe: document.getElementById('t_launch_exe').value.trim(),
description: document.getElementById('t_description').value.trim(),
};
if (!body.name) return toast('请填写工具名称', true);
diff --git a/server/handlers/admin.go b/server/handlers/admin.go
index cd59794..85dbb39 100644
--- a/server/handlers/admin.go
+++ b/server/handlers/admin.go
@@ -196,6 +196,7 @@
Cover string `json:"cover"`
Description string `json:"description"`
FileURL string `json:"file_url"`
+ LaunchExe string `json:"launch_exe"`
}
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Name) == "" {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写工具名称"})
@@ -215,6 +216,7 @@
tool.Cover = req.Cover
tool.Description = req.Description
tool.FileURL = req.FileURL
+ tool.LaunchExe = req.LaunchExe
if req.ID > 0 {
config.DB.Save(&tool)
} else {
diff --git a/server/handlers/auth.go b/server/handlers/auth.go
index 1961433..75dafc9 100644
--- a/server/handlers/auth.go
+++ b/server/handlers/auth.go
@@ -155,9 +155,9 @@
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户不存在"})
return
}
- // 查询会员有效期(永久卡 expired_at 为 NULL;取最大的未过期时间)
+ // 查询会员有效期(永久卡 expired_at 为 NULL;冻结的密钥不计入会员;取最大的未过期时间)
var keys []models.MemberKey
- config.DB.Where("user_id = ? AND (expired_at IS NULL OR expired_at > ?)", userID, time.Now()).Find(&keys)
+ config.DB.Where("user_id = ? AND frozen = ? AND (expired_at IS NULL OR expired_at > ?)", userID, false, time.Now()).Find(&keys)
permanent := false
var expire *time.Time
for i := range keys {
diff --git a/server/handlers/games.go b/server/handlers/games.go
index 6b0f3d4..e2fabf5 100644
--- a/server/handlers/games.go
+++ b/server/handlers/games.go
@@ -3,6 +3,7 @@
import (
"net/http"
"strconv"
+ "strings"
"time"
"gamebox-server/config"
@@ -101,6 +102,33 @@
c.JSON(http.StatusOK, gin.H{"code": 0, "data": tools})
}
+// ToolDownloadInfo 工具下载信息(无需会员校验,返回格式与游戏下载一致)
+func ToolDownloadInfo(c *gin.Context) {
+ var tool models.Tool
+ if err := config.DB.First(&tool, c.Param("id")).Error; err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "工具不存在"})
+ return
+ }
+ if tool.FileURL == "" {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该工具暂无下载文件,请联系管理员上传"})
+ return
+ }
+ // 压缩包文件名取 URL 最后一段
+ fileName := tool.FileURL
+ if idx := strings.LastIndex(tool.FileURL, "/"); idx >= 0 && idx < len(tool.FileURL)-1 {
+ fileName = tool.FileURL[idx+1:]
+ }
+ if q := strings.Index(fileName, "?"); q > 0 {
+ fileName = fileName[:q]
+ }
+ files := []gin.H{{"name": fileName, "url": tool.FileURL, "size": tool.Size}}
+ c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
+ "name": tool.Name,
+ "files": files,
+ "launch_exe": tool.LaunchExe,
+ }})
+}
+
// GetAnnouncements 公告
func GetAnnouncements(c *gin.Context) {
var anns []models.Announcement
@@ -200,11 +228,18 @@
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "游戏不存在"})
return
}
- // 校验会员是否有效(永久卡 expired_at 为 NULL)
+ // 校验会员是否有效(永久卡 expired_at 为 NULL;冻结的密钥视为无效)
var keys []models.MemberKey
- config.DB.Where("user_id = ? AND (expired_at IS NULL OR expired_at > ?)", userID, time.Now()).Find(&keys)
+ config.DB.Where("user_id = ? AND frozen = ? AND (expired_at IS NULL OR expired_at > ?)", userID, false, time.Now()).Find(&keys)
if len(keys) == 0 {
- c.JSON(http.StatusOK, gin.H{"code": 2, "msg": "您的会员已到期,无法下载游戏。请激活新的会员密钥!"})
+ // 用户绑定的密钥被冻结时给出精确提示
+ var frozenCount int64
+ config.DB.Model(&models.MemberKey{}).Where("user_id = ? AND frozen = ?", userID, true).Count(&frozenCount)
+ if frozenCount > 0 {
+ c.JSON(http.StatusOK, gin.H{"code": 2, "msg": "您的密钥已被冻结,无法下载,请联系管理员激活密钥!"})
+ } else {
+ c.JSON(http.StatusOK, gin.H{"code": 2, "msg": "您的会员已到期,无法下载游戏。请激活新的会员密钥!"})
+ }
return
}
// 加入资源库 & 下载计数
diff --git a/server/main.go b/server/main.go
index 3a1e2bc..d487db4 100644
--- a/server/main.go
+++ b/server/main.go
@@ -39,6 +39,7 @@
api.GET("/games", handlers.GetGames)
api.GET("/banners", handlers.GetBanners)
api.GET("/tools", handlers.GetTools)
+ api.GET("/tools/:id/download", handlers.ToolDownloadInfo)
api.GET("/announcements", handlers.GetAnnouncements)
api.GET("/games/:id", handlers.GetGameDetail) // 支持可选登录
diff --git a/server/models/models.go b/server/models/models.go
index 48b2af7..1798138 100644
--- a/server/models/models.go
+++ b/server/models/models.go
@@ -52,10 +52,11 @@
type Tool struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:100" json:"name"`
- Size string `gorm:"size:20" json:"size"`
+ Size string `gorm:"size:20" json:"size"` // 展示用大小,如 85.2MB
Cover string `gorm:"size:255" json:"cover"`
Description string `gorm:"size:500" json:"description"`
- FileURL string `gorm:"size:255" json:"file_url"`
+ FileURL string `gorm:"size:255" json:"file_url"` // 下载压缩包URL
+ LaunchExe string `gorm:"size:255" json:"launch_exe"` // 启动程序相对路径(相对解压后目录)
CreatedAt time.Time `json:"created_at"`
}
--
Gitblit v1.10.0