From 076d5b99d238ebcdc9b9b7b136887a69fc2fa333 Mon Sep 17 00:00:00 2001
From: 905086 <k2049@qq.com>
Date: Sat, 07 Nov 2026 16:55:04 +0800
Subject: [PATCH] feat: 新增永久卡、密钥冻结、工具管理及公告功能,优化游戏安装逻辑
---
server/handlers/keys.go | 41
server/models/models.go | 7
server/handlers/admin.go | 118 +++
fluttergamebox/lib/pages/login_page.dart | 78 --
files/gamebox沟通记录/gamebox20261106沟通.txt | 8
fluttergamebox/lib/store/app_state.dart | 144 +++
server/handlers/games.go | 4
fluttergamebox/lib/utils/network_info.dart | 191 +++++
files/target/安装.png | 0
fluttergamebox/lib/pages/library_page.dart | 360 +++++++--
fluttergamebox/lib/pages/main_shell.dart | 106 ++
fluttergamebox/lib/utils/util.dart | 64 +
fluttergamebox/lib/widgets/info_dialogs.dart | 100 ++
server/handlers/auth.go | 15
fluttergamebox/lib/pages/detail_page.dart | 214 +----
server/admin/index.html | 132 +++
server/main.go | 8
fluttergamebox/lib/widgets/download_manager.dart | 551 +++++++++++---
18 files changed, 1,626 insertions(+), 515 deletions(-)
diff --git "a/files/gamebox\346\262\237\351\200\232\350\256\260\345\275\225/gamebox20261106\346\262\237\351\200\232.txt" "b/files/gamebox\346\262\237\351\200\232\350\256\260\345\275\225/gamebox20261106\346\262\237\351\200\232.txt"
new file mode 100644
index 0000000..1ea497c
--- /dev/null
+++ "b/files/gamebox\346\262\237\351\200\232\350\256\260\345\275\225/gamebox20261106\346\262\237\351\200\232.txt"
@@ -0,0 +1,8 @@
+资源库中,如果右键未安装的游戏,则出现两个选择:安装游戏、从资源库移除。
+==
+在管理后台的密钥管理中,要可以生成永久卡。
+操作栏中,要可以冻结密码。冻结以后,就不可以使用了。
+密钥管理中要可以根据手机号搜索密钥。
+==
+管理后台的工具管理模块。
+
diff --git "a/files/target/\345\256\211\350\243\205.png" "b/files/target/\345\256\211\350\243\205.png"
new file mode 100644
index 0000000..3fb6943
--- /dev/null
+++ "b/files/target/\345\256\211\350\243\205.png"
Binary files differ
diff --git a/fluttergamebox/lib/pages/detail_page.dart b/fluttergamebox/lib/pages/detail_page.dart
index cee38dd..a11abbe 100644
--- a/fluttergamebox/lib/pages/detail_page.dart
+++ b/fluttergamebox/lib/pages/detail_page.dart
@@ -1,6 +1,5 @@
import 'dart:async';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/api/api_service.dart';
@@ -21,6 +20,7 @@
Game? game;
bool isFavorite = false;
bool inLibrary = false;
+ bool _installed = false; // 游戏是否已安装到本机
bool _loading = true;
int _mediaIndex = 0;
Timer? _slideTimer;
@@ -60,6 +60,9 @@
curve: Curves.easeInOut);
}
});
+ // 检测游戏是否已安装到本机
+ _installed = await isGameInstalled(game!.title, game!.launchExe);
+ if (mounted) setState(() {});
} else {
setState(() => _loading = false);
}
@@ -99,11 +102,20 @@
}
}
+ /// 启动已安装的游戏
+ Future<void> _launch() async {
+ if (game == null) return;
+ final ok = await launchInstalledGame(game!.title, game!.launchExe);
+ if (!ok && mounted) {
+ _toast('未找到游戏文件,请先下载游戏', error: true);
+ }
+ }
+
/// 下载前选择下载安装路径
Future<bool> _askDownloadPath() async {
final result = await showDialog<bool>(
context: context,
- builder: (context) => _DownloadPathDialog(gameTitle: game!.title),
+ builder: (context) => DownloadPathDialog(gameTitle: game!.title),
);
return result == true;
}
@@ -516,27 +528,41 @@
),
),
const SizedBox(height: 12),
- // 下载游戏
- SizedBox(
- width: double.infinity,
- height: 44,
- child: ElevatedButton(
- onPressed: _download,
- style: ElevatedButton.styleFrom(
- backgroundColor: AppColors.accent,
- foregroundColor: Colors.white,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(4)),
- ),
- child: const Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Icon(Icons.download, size: 18),
- SizedBox(width: 8),
- Text('下载游戏', style: TextStyle(fontSize: 14)),
- ],
- ),
- ),
+ // 下载游戏 / 启动游戏(已安装则切换为启动)
+ ListenableBuilder(
+ listenable: DownloadManager.instance,
+ builder: (context, _) {
+ // 本机已安装,或该游戏下载任务已完成(含解压)则显示启动按钮
+ final t = DownloadManager.instance.activeTask;
+ final installed = _installed ||
+ (t != null &&
+ t.gameId == game!.id &&
+ t.finished &&
+ !t.extractFailed);
+ return SizedBox(
+ width: double.infinity,
+ height: 44,
+ child: ElevatedButton(
+ onPressed: installed ? _launch : _download,
+ style: ElevatedButton.styleFrom(
+ backgroundColor: AppColors.accent,
+ foregroundColor: Colors.white,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(4)),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(installed ? Icons.play_arrow : Icons.download,
+ size: 18),
+ const SizedBox(width: 8),
+ Text(installed ? '启动游戏' : '下载游戏',
+ style: const TextStyle(fontSize: 14)),
+ ],
+ ),
+ ),
+ );
+ },
),
],
),
@@ -577,145 +603,3 @@
);
}
}
-
-/// 下载路径选择弹窗
-class _DownloadPathDialog extends StatefulWidget {
- final String gameTitle;
- const _DownloadPathDialog({required this.gameTitle});
- @override
- State<_DownloadPathDialog> createState() => _DownloadPathDialogState();
-}
-
-class _DownloadPathDialogState extends State<_DownloadPathDialog> {
- final _dlCtrl = TextEditingController();
- final _insCtrl = TextEditingController();
-
- @override
- void initState() {
- super.initState();
- _load();
- }
-
- Future<void> _load() async {
- final dl = await AppPrefs.getDownloadPath();
- final ins = await AppPrefs.getInstallPath();
- setState(() {
- _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
- _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
- });
- }
-
- @override
- Widget build(BuildContext context) {
- return Dialog(
- backgroundColor: const Color(0xFF1E2130),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
- child: Container(
- width: 500,
- padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- const Icon(Icons.folder,
- size: 16, color: AppColors.textGray),
- const SizedBox(width: 8),
- const Text('请选择下载安装路径',
- style: TextStyle(
- color: Colors.white,
- fontSize: 14,
- fontWeight: FontWeight.w500)),
- const Spacer(),
- GestureDetector(
- onTap: () => Navigator.pop(context, false),
- child: const Icon(Icons.close,
- size: 16, color: AppColors.textGray),
- ),
- ],
- ),
- const SizedBox(height: 18),
- _pathRow('下载路径', _dlCtrl),
- const SizedBox(height: 12),
- _pathRow('安装路径', _insCtrl),
- const SizedBox(height: 20),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- OutlinedButton(
- onPressed: () => Navigator.pop(context, false),
- style: OutlinedButton.styleFrom(
- foregroundColor: AppColors.textGray,
- side: const BorderSide(color: AppColors.bgLighter),
- padding: const EdgeInsets.symmetric(
- horizontal: 22, vertical: 10),
- ),
- child: const Text('取消'),
- ),
- const SizedBox(width: 12),
- ElevatedButton(
- onPressed: () async {
- await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
- if (context.mounted) Navigator.pop(context, true);
- },
- style: ElevatedButton.styleFrom(
- backgroundColor: AppColors.accent,
- foregroundColor: Colors.white,
- padding: const EdgeInsets.symmetric(
- horizontal: 22, vertical: 10),
- ),
- child: const Text('确认'),
- ),
- ],
- ),
- ],
- ),
- ),
- );
- }
-
- Widget _pathRow(String label, TextEditingController ctrl) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(label,
- style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
- const SizedBox(height: 6),
- Row(
- children: [
- Expanded(
- child: TextField(
- controller: ctrl,
- style: const TextStyle(color: Colors.black, fontSize: 13),
- decoration: InputDecoration(
- filled: true,
- fillColor: Colors.white,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 10, vertical: 10),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(4),
- borderSide: BorderSide.none),
- ),
- ),
- ),
- const SizedBox(width: 8),
- ElevatedButton(
- onPressed: () async {
- final dir = await FilePicker.platform.getDirectoryPath();
- if (dir != null) setState(() => ctrl.text = dir);
- },
- style: ElevatedButton.styleFrom(
- backgroundColor: AppColors.accent,
- foregroundColor: Colors.white,
- padding: const EdgeInsets.symmetric(
- horizontal: 14, vertical: 11),
- ),
- child: const Text('选择目录', style: TextStyle(fontSize: 12)),
- ),
- ],
- ),
- ],
- );
- }
-}
diff --git a/fluttergamebox/lib/pages/library_page.dart b/fluttergamebox/lib/pages/library_page.dart
index 5e8b0fc..f19c476 100644
--- a/fluttergamebox/lib/pages/library_page.dart
+++ b/fluttergamebox/lib/pages/library_page.dart
@@ -6,6 +6,7 @@
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/store/app_state.dart';
import 'package:fluttergamebox/utils/util.dart';
+import 'package:fluttergamebox/widgets/download_manager.dart';
import 'package:path/path.dart' as p;
class LibraryPage extends StatefulWidget {
@@ -119,7 +120,7 @@
final cardWidth =
(constraints.maxWidth - crossAxisSpacing * 4) / 5;
final coverHeight = cardWidth / 1.42;
- const infoHeight = 92.0;
+ const infoHeight = 96.0;
return GridView.builder(
padding: const EdgeInsets.only(bottom: 40),
gridDelegate:
@@ -131,7 +132,7 @@
),
itemCount: filtered.length,
itemBuilder: (context, i) =>
- _LibraryCard(game: filtered[i], onRemove: _load),
+ _LibraryCard(game: filtered[i], onRemoved: _load),
);
}),
),
@@ -341,42 +342,67 @@
}
/// 资源库游戏卡片(右键菜单)
-class _LibraryCard extends StatelessWidget {
+class _LibraryCard extends StatefulWidget {
final Game game;
- final VoidCallback onRemove;
- const _LibraryCard({required this.game, required this.onRemove});
+ final VoidCallback? onRemoved; // 从资源库移除后刷新列表
+ const _LibraryCard({required this.game, this.onRemoved});
+ @override
+ State<_LibraryCard> createState() => _LibraryCardState();
+}
- Future<String> _installDir() async {
- final ins = await AppPrefs.getInstallPath();
- final base = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
- return '$base\\${game.title.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_')}';
+class _LibraryCardState extends State<_LibraryCard> {
+ bool _installed = false; // 游戏是否已安装到本机
+ bool _uninstalling = false; // 正在卸载(删除游戏目录)
+
+ @override
+ void initState() {
+ super.initState();
+ _checkInstalled();
}
- Future<void> _launch(BuildContext context) async {
- final dir = await _installDir();
- 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>()
- .where((f) => f.path.toLowerCase().endsWith('.exe'))
- .toList();
- if (exes.isNotEmpty) {
- Process.run(exes.first.path, [], workingDirectory: dir);
- return;
- }
+ Future<void> _checkInstalled() async {
+ final ok = await isGameInstalled(widget.game.title, widget.game.launchExe);
+ if (mounted) setState(() => _installed = ok);
+ }
+
+ /// 当前是否已安装(本机已装,或该游戏的下载任务刚完成)
+ bool _effectiveInstalled() {
+ final t = DownloadManager.instance.activeTask;
+ return _installed ||
+ (t != null &&
+ t.gameId == widget.game.id &&
+ t.finished &&
+ !t.extractFailed);
+ }
+
+ Future<String> _installDir() async => gameInstallDir(widget.game.title);
+
+ /// 启动游戏(启动已下载的游戏不需要会员)
+ Future<void> _launch() async {
+ final ok =
+ await launchInstalledGame(widget.game.title, widget.game.launchExe);
+ if (!ok && mounted) {
+ _showToast('未找到游戏文件,请先下载游戏');
}
- // 未找到可执行文件
+ }
+
+ /// 安装(未安装时):选择路径后下载并安装
+ Future<void> _install() async {
+ // 选择下载安装路径
+ final ok = await showDialog<bool>(
+ context: context,
+ builder: (context) => DownloadPathDialog(gameTitle: widget.game.title),
+ );
+ if (ok != true) return;
+ try {
+ await DownloadManager.instance.startDownload(widget.game);
+ if (mounted) showDownloadDialog(context);
+ } catch (e) {
+ _showToast(e.toString());
+ }
+ }
+
+ void _showToast(String msg) {
final overlay = Overlay.of(context);
final entry = OverlayEntry(
builder: (context) => Positioned(
@@ -386,20 +412,19 @@
color: Colors.transparent,
child: Container(
width: 280,
- padding: const EdgeInsets.symmetric(
- horizontal: 16, vertical: 12),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: AppColors.red,
borderRadius: BorderRadius.circular(6),
),
- child: const Row(
+ child: Row(
children: [
- Icon(Icons.error_outline, color: Colors.white, size: 18),
- SizedBox(width: 8),
+ const Icon(Icons.error_outline, color: Colors.white, size: 18),
+ const SizedBox(width: 8),
Expanded(
- child: Text('未找到游戏文件,请先下载游戏',
- style:
- TextStyle(color: Colors.white, fontSize: 13)),
+ child: Text(msg,
+ style: const TextStyle(
+ color: Colors.white, fontSize: 13)),
),
],
),
@@ -424,15 +449,163 @@
// 通过PowerShell创建桌面快捷方式(指向游戏目录)
final dir = await _installDir();
final script =
- '\$s=(New-Object -COM WScript.Shell).CreateShellLink(\"\$env:USERPROFILE\\Desktop\\${game.title}.lnk\");'
+ '\$s=(New-Object -COM WScript.Shell).CreateShellLink(\"\$env:USERPROFILE\\Desktop\\${widget.game.title}.lnk\");'
'\$s.TargetPath=\"$dir\"; \$s.Save()';
Process.run('powershell', ['-command', script]);
}
+ /// 卸载:确认后仅删除本机游戏目录(游戏保留在资源库中)
Future<void> _uninstall(BuildContext context) async {
- final res = await ApiService.removeFromLibrary(game.id);
- if (res['code'] == 0) {
- onRemove();
+ if (_uninstalling) return; // 已在卸载中
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (context) => Dialog(
+ backgroundColor: const Color(0xFF1E2130),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+ child: Container(
+ width: 360,
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(Icons.warning_amber_rounded,
+ color: AppColors.yellow, size: 48),
+ const SizedBox(height: 16),
+ const Text('确认卸载游戏',
+ style: TextStyle(
+ color: Colors.white,
+ fontSize: 16,
+ fontWeight: FontWeight.bold)),
+ const SizedBox(height: 8),
+ Text(
+ '将删除本机的「${widget.game.title}」游戏目录,游戏仍保留在资源库中,卸载后可在详情页重新下载。',
+ textAlign: TextAlign.center,
+ style: const TextStyle(color: AppColors.textGray, fontSize: 13),
+ ),
+ const SizedBox(height: 20),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ OutlinedButton(
+ onPressed: () => Navigator.pop(context, false),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: AppColors.textGray,
+ side: const BorderSide(color: AppColors.bgLighter),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('取消'),
+ ),
+ const SizedBox(width: 12),
+ ElevatedButton(
+ onPressed: () => Navigator.pop(context, true),
+ style: ElevatedButton.styleFrom(
+ backgroundColor: AppColors.red,
+ foregroundColor: Colors.white,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('卸载'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ if (confirmed != true) return;
+
+ // 仅删除游戏安装目录,不从资源库移出
+ setState(() => _uninstalling = true);
+ try {
+ final dir = Directory(await _installDir());
+ if (await dir.exists()) {
+ await dir.delete(recursive: true);
+ }
+ } catch (_) {
+ debugLog('uninstall delete dir failed: ${widget.game.title}');
+ }
+ if (mounted) {
+ // 卸载完成后按钮由"卸载中"切换为"安装"
+ setState(() {
+ _uninstalling = false;
+ _installed = false;
+ });
+ }
+ // 清除残留的已完成下载任务记录,避免仍被判定为已安装
+ DownloadManager.instance.clearFinishedTask(widget.game.id);
+ }
+
+ /// 从资源库移除(仅移除记录,不影响本机游戏文件)
+ Future<void> _removeFromLibrary(BuildContext context) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (context) => Dialog(
+ backgroundColor: const Color(0xFF1E2130),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+ child: Container(
+ width: 360,
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(Icons.list_alt,
+ color: AppColors.yellow, size: 48),
+ const SizedBox(height: 16),
+ const Text('从资源库移除',
+ style: TextStyle(
+ color: Colors.white,
+ fontSize: 16,
+ fontWeight: FontWeight.bold)),
+ const SizedBox(height: 8),
+ Text(
+ '将「${widget.game.title}」从资源库列表中移除,不影响本机已下载的游戏文件。',
+ textAlign: TextAlign.center,
+ style: const TextStyle(color: AppColors.textGray, fontSize: 13),
+ ),
+ const SizedBox(height: 20),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ OutlinedButton(
+ onPressed: () => Navigator.pop(context, false),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: AppColors.textGray,
+ side: const BorderSide(color: AppColors.bgLighter),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('取消'),
+ ),
+ const SizedBox(width: 12),
+ ElevatedButton(
+ onPressed: () => Navigator.pop(context, true),
+ style: ElevatedButton.styleFrom(
+ backgroundColor: AppColors.red,
+ foregroundColor: Colors.white,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('移除'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ if (confirmed != true) return;
+
+ try {
+ final res = await ApiClient.delete('/api/library/${widget.game.id}');
+ if (res['code'] == 0) {
+ AppState.instance.bumpLibrary();
+ widget.onRemoved?.call(); // 刷新资源库列表
+ }
+ } catch (_) {
+ debugLog('remove from library failed: ${widget.game.title}');
}
}
@@ -467,16 +640,25 @@
),
child: Column(
mainAxisSize: MainAxisSize.min,
- children: [
- _menuItem(context, Icons.play_arrow, '启动游戏',
- () => _launch(context)),
- _menuItem(context, Icons.link, '创建快捷方式',
- _createShortcut),
- _menuItem(context, Icons.folder_open, '打开游戏目录',
- _openDir),
- _menuItem(context, Icons.delete_outline, '卸载游戏',
- () => _uninstall(context)),
- ],
+ children: _effectiveInstalled()
+ ? [
+ // 已安装:启动/快捷方式/打开目录/卸载
+ _menuItem(context, Icons.play_arrow, '启动游戏',
+ _launch),
+ _menuItem(context, Icons.link, '创建快捷方式',
+ _createShortcut),
+ _menuItem(context, Icons.folder_open, '打开游戏目录',
+ _openDir),
+ _menuItem(context, Icons.delete_outline, '卸载游戏',
+ () => _uninstall(context)),
+ ]
+ : [
+ // 未安装:安装/从资源库移除
+ _menuItem(context, Icons.download, '安装游戏',
+ _install),
+ _menuItem(context, Icons.list_alt, '从资源库移除',
+ () => _removeFromLibrary(context)),
+ ],
),
),
),
@@ -510,7 +692,10 @@
@override
Widget build(BuildContext context) {
return GestureDetector(
- onTap: () => _launch(context),
+ onTap: () {
+ if (_uninstalling) return; // 卸载中不响应点击
+ _effectiveInstalled() ? _launch() : _install();
+ },
onSecondaryTapDown: (details) =>
_showContextMenu(context, details.globalPosition),
child: MouseRegion(
@@ -532,13 +717,13 @@
borderRadius: const BorderRadius.vertical(
top: Radius.circular(6)),
child: Image.network(
- ApiClient.baseUrl + game.cover,
+ ApiClient.baseUrl + widget.game.cover,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(
color: const Color(0xFF2A2E45),
child: Center(
child: Text(
- game.title.characters.first,
+ widget.game.title.characters.first,
style: const TextStyle(
color: AppColors.textDim,
fontSize: 32)),
@@ -558,7 +743,7 @@
borderRadius:
BorderRadius.horizontal(right: Radius.circular(3)),
),
- child: Text(game.platformLabel,
+ child: Text(widget.game.platformLabel,
style: const TextStyle(
color: Colors.white, fontSize: 11)),
),
@@ -574,7 +759,7 @@
color: Colors.black.withOpacity(0.6),
borderRadius: BorderRadius.circular(3),
),
- child: Text(game.size,
+ child: Text(widget.game.size,
style: const TextStyle(
color: Colors.white, fontSize: 11)),
),
@@ -588,18 +773,18 @@
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (game.versionNote.isNotEmpty)
+ if (widget.game.versionNote.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Text(
- game.versionNote,
+ widget.game.versionNote,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textDim, fontSize: 11),
),
),
- Text(game.title,
+ Text(widget.game.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
@@ -611,27 +796,46 @@
children: [
Expanded(
child: Text(
- game.tags.split(',').first,
+ widget.game.tags.split(',').first,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textDim, fontSize: 11),
),
),
- // 启动按钮(对标:标签行右侧紧凑按钮)
- GestureDetector(
- onTap: () => _launch(context),
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 14, vertical: 4),
- decoration: BoxDecoration(
- color: AppColors.accent,
- borderRadius: BorderRadius.circular(3),
- ),
- child: const Text('启动',
- style: TextStyle(
- color: Colors.white, fontSize: 11)),
- ),
+ // 启动/安装/卸载中按钮(随安装状态切换)
+ ListenableBuilder(
+ listenable: DownloadManager.instance,
+ builder: (context, _) {
+ final installed = _effectiveInstalled();
+ final label = _uninstalling
+ ? '卸载中'
+ : installed
+ ? '启动'
+ : '安装';
+ return GestureDetector(
+ // 卸载中禁用点击
+ onTap: _uninstalling
+ ? null
+ : () =>
+ installed ? _launch() : _install(),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 14, vertical: 4),
+ decoration: BoxDecoration(
+ color: _uninstalling
+ ? AppColors.bgLighter
+ : installed
+ ? AppColors.accent
+ : AppColors.green,
+ borderRadius: BorderRadius.circular(3),
+ ),
+ child: Text(label,
+ style: const TextStyle(
+ color: Colors.white, fontSize: 11)),
+ ),
+ );
+ },
),
],
),
diff --git a/fluttergamebox/lib/pages/login_page.dart b/fluttergamebox/lib/pages/login_page.dart
index 29a43b9..f39154d 100644
--- a/fluttergamebox/lib/pages/login_page.dart
+++ b/fluttergamebox/lib/pages/login_page.dart
@@ -1,13 +1,10 @@
-import 'dart:convert';
-
-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';
import 'package:fluttergamebox/store/app_state.dart';
import 'package:fluttergamebox/widgets/auth_dialogs.dart';
import 'package:fluttergamebox/widgets/window_controls.dart';
-import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@@ -43,13 +40,7 @@
if (res['code'] == 0) {
await ApiClient.saveToken(res['data']['token']);
await AppState.instance.refreshUserInfo();
- if (mounted) {
- // 登录成功后弹出公告
- final ann = await ApiService.announcements();
- if (mounted && ann.isNotEmpty) {
- showAnnouncementDialog(context, ann);
- }
- }
+ // 公告改为进入首页时统一弹出(见 main_shell)
} else {
setState(() => _error = res['msg'] ?? '登录失败');
}
@@ -364,68 +355,3 @@
Future.delayed(const Duration(seconds: 2), () => entry.remove());
}
-/// 登录成功后的公告弹窗
-void showAnnouncementDialog(BuildContext context, String content) {
- showDialog(
- context: context,
- builder: (context) => Dialog(
- backgroundColor: Colors.white,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
- child: Container(
- width: 420,
- padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- const Icon(Icons.campaign,
- color: Color(0xFF2B7FFF), size: 22),
- const SizedBox(width: 8),
- const Text('系统公告',
- style: TextStyle(
- color: Colors.black,
- fontSize: 16,
- fontWeight: FontWeight.bold)),
- const Spacer(),
- GestureDetector(
- onTap: () => Navigator.pop(context),
- child: const Icon(Icons.close,
- color: Colors.grey, size: 20),
- ),
- ],
- ),
- const SizedBox(height: 16),
- ConstrainedBox(
- constraints: const BoxConstraints(maxHeight: 320),
- child: SingleChildScrollView(
- child: Text(
- content,
- style: const TextStyle(
- color: Color(0xFFE74C3C),
- fontSize: 13,
- height: 1.9),
- ),
- ),
- ),
- const SizedBox(height: 16),
- Align(
- alignment: Alignment.centerRight,
- child: ElevatedButton(
- onPressed: () => Navigator.pop(context),
- style: ElevatedButton.styleFrom(
- backgroundColor: const Color(0xFF2B7FFF),
- foregroundColor: Colors.white,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(4)),
- ),
- child: const Text('知道了'),
- ),
- ),
- ],
- ),
- ),
- ),
- );
-}
diff --git a/fluttergamebox/lib/pages/main_shell.dart b/fluttergamebox/lib/pages/main_shell.dart
index 3b0088f..b02184b 100644
--- a/fluttergamebox/lib/pages/main_shell.dart
+++ b/fluttergamebox/lib/pages/main_shell.dart
@@ -43,6 +43,22 @@
ShellNav.instance.openDetail =
(id) => setState(() => _detailGameId = id);
ShellNav.instance.goBack = _closeDetail;
+ // 打开首页时自动弹出系统公告(内容在管理后台设置)
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _showHomeAnnouncement();
+ });
+ }
+
+ /// 打开首页自动弹出公告(无公告内容则不弹出)
+ void _showHomeAnnouncement() async {
+ final res = await ApiClient.get('/api/announcements');
+ if (!mounted || res['code'] != 0) return;
+ final data = res['data'] as List;
+ if (data.isEmpty) return;
+ final content = (data[0]['content'] ?? '').toString().trim();
+ if (content.isEmpty) return;
+ if (!mounted) return;
+ _showAnnouncementDialog(context, content);
}
@override
@@ -92,7 +108,8 @@
height: 3,
color: AppColors.bgLight,
child: LinearProgressIndicator(
- value: task.progress,
+ // 下载阶段显示下载进度,安装(解压)阶段显示解压进度
+ value: task.extracting ? task.extractProgress : task.progress,
backgroundColor: Colors.transparent,
color: AppColors.accent,
),
@@ -685,6 +702,72 @@
}
}
+/// 公告弹窗(标题+内容+关闭),首页打开与左侧栏共用
+void _showAnnouncementDialog(BuildContext context, String content) {
+ showDialog(
+ context: context,
+ builder: (context) => Dialog(
+ backgroundColor: Colors.white,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+ child: Container(
+ width: 420,
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ const Icon(Icons.campaign,
+ color: Color(0xFF2B7FFF), size: 22),
+ const SizedBox(width: 8),
+ const Text('系统公告',
+ style: TextStyle(
+ color: Colors.black,
+ fontSize: 16,
+ fontWeight: FontWeight.bold)),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => Navigator.pop(context),
+ child: const Icon(Icons.close,
+ color: Colors.grey, size: 20),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxHeight: 320),
+ child: SingleChildScrollView(
+ child: Text(
+ content,
+ style: const TextStyle(
+ color: Color(0xFFE74C3C),
+ fontSize: 13,
+ height: 1.9),
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Align(
+ alignment: Alignment.centerRight,
+ child: ElevatedButton(
+ onPressed: () => Navigator.pop(context),
+ style: ElevatedButton.styleFrom(
+ backgroundColor: const Color(0xFF2B7FFF),
+ foregroundColor: Colors.white,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(4)),
+ ),
+ child: const Text('知道了'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
+
/// 左侧浮动栏:系统公告/联系客服/常见问题
class _LeftSidebar extends StatelessWidget {
const _LeftSidebar();
@@ -723,26 +806,7 @@
(res['data'] as List).isNotEmpty
? res['data'][0]['content']
: '暂无公告';
- showDialog(
- context: context,
- builder: (context) => AlertDialog(
- backgroundColor: Colors.white,
- title: const Text('系统公告',
- style: TextStyle(color: Colors.black, fontSize: 16)),
- content: SizedBox(
- width: 380,
- child: Text('$content',
- style:
- const TextStyle(color: Color(0xFFE74C3C), fontSize: 13, height: 1.9)),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('知道了', style: TextStyle(color: Color(0xFF2B7FFF))),
- ),
- ],
- ),
- );
+ _showAnnouncementDialog(context, '$content');
}
void _showToast2(BuildContext context, String msg) {
diff --git a/fluttergamebox/lib/store/app_state.dart b/fluttergamebox/lib/store/app_state.dart
index 6c60af1..c9b9af0 100644
--- a/fluttergamebox/lib/store/app_state.dart
+++ b/fluttergamebox/lib/store/app_state.dart
@@ -79,6 +79,13 @@
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;
@@ -91,6 +98,8 @@
bool canceled = false;
bool extracting = false; // 正在解压安装
bool extractFailed = false; // 解压失败
+ double extractProgress = 0; // 安装(解压)总进度 0~1
+ final List<ExtractLogEntry> extractLog = []; // 解压文件日志
DateTime? startTime;
DownloadTask(
@@ -125,6 +134,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 +146,15 @@
notifyListeners();
}
+ /// 清除指定游戏已完成的任务记录(卸载后不再视为已安装)
+ void clearFinishedTask(int gameId) {
+ final t = activeTask;
+ if (t != null && t.gameId == gameId && t.finished) {
+ activeTask = null;
+ notifyListeners();
+ }
+ }
+
Future<void> startDownload(Game game) async {
// 获取下载文件列表(服务端校验会员)
final res = await ApiService.downloadInfo(game.id);
@@ -234,7 +254,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 +324,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 +350,8 @@
if (archives.isEmpty && plainFiles.isEmpty) return;
task.extracting = true;
+ task.extractProgress = 0;
+ task.extractLog.clear();
notifyListeners();
try {
// 普通文件直接移动到安装目录
@@ -352,10 +367,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 +394,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 +512,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);
diff --git a/fluttergamebox/lib/utils/network_info.dart b/fluttergamebox/lib/utils/network_info.dart
new file mode 100644
index 0000000..bbb991c
--- /dev/null
+++ b/fluttergamebox/lib/utils/network_info.dart
@@ -0,0 +1,191 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:dio/dio.dart';
+
+/// 电脑网络信息
+class NetworkInfo {
+ final String connType; // 连接方式(WLAN/以太网)
+ final String localIp; // 内网IP
+ final String gateway; // 网关
+ final String dns; // DNS服务器
+ final String publicIp; // 公网IP
+ final String location; // 地区
+ final String isp; // 运营商
+
+ const NetworkInfo({
+ this.connType = '未知',
+ this.localIp = '未知',
+ this.gateway = '未知',
+ this.dns = '未知',
+ this.publicIp = '获取失败',
+ this.location = '未知',
+ this.isp = '未知',
+ });
+}
+
+NetworkInfo? _cache;
+DateTime? _cacheAt;
+
+/// 获取真实的网络信息(结果缓存10分钟,避免频繁请求)
+Future<NetworkInfo> getNetworkInfo() async {
+ if (_cache != null &&
+ _cacheAt != null &&
+ DateTime.now().difference(_cacheAt!) < const Duration(minutes: 10)) {
+ return _cache!;
+ }
+ // 公网信息(多源降级)与本地网卡信息并行获取
+ final results = await Future.wait([
+ _fetchPublicInfo(),
+ _fetchLocalInfo(),
+ ]);
+ final pub = results[0] as Map<String, String>?;
+ final local = results[1] as Map<String, String?>;
+
+ final info = NetworkInfo(
+ connType: local['if'] ?? '未知',
+ localIp: local['ip'] ?? '未知',
+ gateway: local['gw'] ?? '未知',
+ dns: local['dns'] ?? '未知',
+ publicIp: pub?['ip'] ?? '获取失败',
+ location: pub?['location'] ?? '未知',
+ isp: pub?['isp'] ?? '未知',
+ );
+ _cache = info;
+ _cacheAt = DateTime.now();
+ return info;
+}
+
+Dio _dio() => Dio(BaseOptions(
+ connectTimeout: const Duration(seconds: 5),
+ receiveTimeout: const Duration(seconds: 5),
+ // 部分公共IP接口返回非200状态码
+ validateStatus: (status) => status != null && status < 500,
+ ));
+
+/// 公网IP/地区/运营商:依次尝试多个源,取第一个成功的
+Future<Map<String, String>?> _fetchPublicInfo() async {
+ final dio = _dio();
+ final sources = <Future<Map<String, String>?> Function(Dio)>[
+ _fromIpipNet,
+ _fromUserAgentInfo,
+ _fromIpApiCom,
+ ];
+ for (final fetch in sources) {
+ try {
+ final r = await fetch(dio);
+ if (r != null && (r['ip'] ?? '').isNotEmpty) return r;
+ } catch (_) {
+ // 尝试下一个源
+ }
+ }
+ return null;
+}
+
+/// 源1:myip.ipip.net,返回文本"当前 IP:x.x.x.x 来自于:中国 广东 深圳 电信"
+Future<Map<String, String>?> _fromIpipNet(Dio dio) async {
+ final res = await dio.get<String>('https://myip.ipip.net');
+ final text = res.data ?? '';
+ final m = RegExp(r'当前 IP:(.+?)\s*来自于:(.+)').firstMatch(text);
+ if (m == null) return null;
+ final parts = m.group(2)!.trim().split(RegExp(r'\s+'));
+ final isp = parts.isNotEmpty ? parts.removeLast() : '';
+ return {
+ 'ip': m.group(1)!.trim(),
+ 'location': parts.join(' '),
+ 'isp': isp,
+ };
+}
+
+/// 源2:ip.useragentinfo.com,返回JSON {"ip":"x.x.x.x","country":"中国","province":"广东省","city":"广州市","isp":"电信"}
+Future<Map<String, String>?> _fromUserAgentInfo(Dio dio) async {
+ final res = await dio.get('https://ip.useragentinfo.com/json');
+ final d = res.data;
+ if (d is! Map) return null;
+ final location = [d['country'], d['province'], d['city']]
+ .whereType<String>()
+ .where((s) => s.isNotEmpty)
+ .join(' ');
+ final ip = (d['ip'] ?? '').toString();
+ if (ip.isEmpty) return null;
+ return {'ip': ip, 'location': location, 'isp': (d['isp'] ?? '').toString()};
+}
+
+/// 源3:ip-api.com,返回JSON {"query":"x.x.x.x","country":"中国","regionName":"广东","city":"深圳","isp":"..."}
+Future<Map<String, String>?> _fromIpApiCom(Dio dio) async {
+ final res =
+ await dio.get('http://ip-api.com/json/?lang=zh-CN&fields=query,isp,org,as');
+ final d = res.data;
+ if (d is! Map) return null;
+ final ip = (d['query'] ?? '').toString();
+ if (ip.isEmpty) return null;
+ // isp多为英文AS描述,转成常见中文运营商名
+ final org = '${d['isp']} ${d['org']} ${d['as']}'.toUpperCase();
+ String isp = d['isp'].toString();
+ if (org.contains('CHINANET') || org.contains('TELECOM') || org.contains('电信')) {
+ isp = '电信';
+ } else if (org.contains('UNICOM') || org.contains('联通')) {
+ isp = '联通';
+ } else if (org.contains('CMNET') || org.contains('MOBILE') || org.contains('移动')) {
+ isp = '移动';
+ } else if (org.contains('TIETONG') || org.contains('铁通')) {
+ isp = '铁通';
+ } else if (org.contains('CERNET')) {
+ isp = '教育网';
+ } else if (org.contains('GWBN')) {
+ isp = '长城宽带';
+ } else if (isp.isEmpty) {
+ isp = '未知';
+ }
+ return {'ip': ip, 'location': '未知', 'isp': isp};
+}
+
+/// 本地网卡信息:连接方式/内网IP/网关/DNS(PowerShell查询)
+Future<Map<String, String?>> _fetchLocalInfo() async {
+ const script = r'''
+$nic = Get-NetIPConfiguration | Where-Object {
+ $_.NetAdapter.Status -eq 'Up' -and
+ $_.NetAdapter.InterfaceDescription -notmatch 'VMware|Virtual|Hyper-V|VirtualBox|WSL|TAP|Loopback|Bluetooth' -and
+ @($_.IPv4Address.IPAddress) -match '^(?!169\.254\.|127\.)' -and @($_.IPv4Address.IPAddress).Count -gt 0
+}
+$c = $nic | Where-Object { $null -ne $_.IPv4DefaultGateway } | Select-Object -First 1
+if ($null -eq $c) { $c = $nic | Select-Object -First 1 }
+if ($null -eq $c) { '{}' | Write-Output } else {
+ $ips = @($c.IPv4Address.IPAddress | Where-Object { $_ -notmatch '^169\.254\.|^127\.' })
+ $dns = (Get-DnsClientServerAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -eq $c.InterfaceAlias -and $_.ServerAddresses }).ServerAddresses -join ','
+ @{ ip = [string]$ips[0]; gw = [string]$c.IPv4DefaultGateway.NextHop; if = [string]$c.InterfaceAlias; dns = [string]$dns } | ConvertTo-Json -Compress
+}
+''';
+ try {
+ final res = await Process.run('powershell', ['-NoProfile', '-Command', script]);
+ if (res.exitCode != 0) return const {};
+ final out = (res.stdout as String).trim();
+ if (out.isEmpty) return const {};
+ final d = jsonDecode(out);
+ if (d is! Map) return const {};
+ String? val(Object? v) {
+ final s = v?.toString() ?? '';
+ return s.isEmpty ? null : s;
+ }
+
+ // 连接方式映射:WLAN→无线网络,以太网→有线网络
+ var connType = val(d['if']);
+ if (connType != null) {
+ if (connType.toUpperCase().contains('WLAN') ||
+ connType.toUpperCase().contains('WI-FI')) {
+ connType = '无线网络 ($connType)';
+ } else if (connType.contains('以太网') ||
+ connType.toUpperCase().contains('ETHERNET')) {
+ connType = '有线网络 ($connType)';
+ }
+ }
+ return {
+ 'ip': val(d['ip']),
+ 'gw': val(d['gw']),
+ 'dns': val(d['dns']),
+ 'if': connType,
+ };
+ } catch (_) {
+ return const {};
+ }
+}
diff --git a/fluttergamebox/lib/utils/util.dart b/fluttergamebox/lib/utils/util.dart
index d6d07f4..4c4fcea 100644
--- a/fluttergamebox/lib/utils/util.dart
+++ b/fluttergamebox/lib/utils/util.dart
@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
/// 获取本机机器码(注册表 MachineGuid,失败则退化为稳定哈希)
@@ -51,6 +52,16 @@
return '${bytes.toStringAsFixed(0)} B';
}
+/// 速度格式化(按比特展示:下载弹窗显示 Mbps / bps)
+String formatSpeed(double bytesPerSec) {
+ if (bytesPerSec <= 0) return '0.00 bps';
+ final mbps = bytesPerSec * 8 / 1000000;
+ if (mbps < 1) {
+ return '${(bytesPerSec * 8 / 1000).toStringAsFixed(2)} Kbps';
+ }
+ return '${mbps.toStringAsFixed(2)} Mbps';
+}
+
/// 秒 -> HH:MM:SS
String formatDuration(int seconds) {
final h = seconds ~/ 3600;
@@ -60,6 +71,59 @@
return '${two(h)}:${two(m)}:${two(s)}';
}
+/// 文件名安全化(去除 Windows 非法字符)
+String safeFileName(String s) => s.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_');
+
+/// 游戏安装目录(与下载安装逻辑保持一致)
+Future<String> gameInstallDir(String title) async {
+ final ins = await AppPrefs.getInstallPath();
+ final base = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+ return '$base\\${safeFileName(title)}';
+}
+
+/// 游戏是否已安装(目录存在且能找到启动程序)
+Future<bool> isGameInstalled(String title, String launchExe) async {
+ final dir = Directory(await gameInstallDir(title));
+ if (!await dir.exists()) return false;
+ if (launchExe.isNotEmpty) {
+ if (await File(p.join(dir.path, launchExe)).exists()) return true;
+ }
+ try {
+ return dir
+ .listSync(recursive: false)
+ .whereType<File>()
+ .any((f) => f.path.toLowerCase().endsWith('.exe'));
+ } catch (_) {
+ return false;
+ }
+}
+
+/// 启动已安装的游戏(优先管理端设置的启动程序,否则取目录中第一个exe)
+Future<bool> launchInstalledGame(String title, String launchExe) async {
+ final dirPath = await gameInstallDir(title);
+ final dir = Directory(dirPath);
+ if (!await dir.exists()) return false;
+ if (launchExe.isNotEmpty) {
+ final exe = File(p.join(dirPath, launchExe));
+ if (await exe.exists()) {
+ Process.run(exe.path, [], workingDirectory: p.dirname(exe.path));
+ return true;
+ }
+ }
+ try {
+ final exes = dir
+ .listSync(recursive: false)
+ .whereType<File>()
+ .where((f) => f.path.toLowerCase().endsWith('.exe'))
+ .toList();
+ if (exes.isNotEmpty) {
+ Process.run(exes.first.path, [], workingDirectory: dirPath);
+ return true;
+ }
+ } catch (_) {}
+ return false;
+}
+
void debugLog(String msg) {
if (kDebugMode) print('[gamebox] $msg');
}
diff --git a/fluttergamebox/lib/widgets/download_manager.dart b/fluttergamebox/lib/widgets/download_manager.dart
index fbdf17c..38c9446 100644
--- a/fluttergamebox/lib/widgets/download_manager.dart
+++ b/fluttergamebox/lib/widgets/download_manager.dart
@@ -1,9 +1,10 @@
import 'dart:io';
+import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
-import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/network_info.dart';
import 'package:fluttergamebox/utils/util.dart';
import 'package:path/path.dart' as p;
@@ -16,9 +17,81 @@
);
}
-class _DownloadDialog extends StatelessWidget {
+class _DownloadDialog extends StatefulWidget {
const _DownloadDialog();
@override
+ State<_DownloadDialog> createState() => _DownloadDialogState();
+}
+
+class _DownloadDialogState extends State<_DownloadDialog> {
+ bool _showDetails = true; // 展开/收起详细任务
+ String _isp = '获取中...'; // 网络运营商(真实获取)
+ final _logCtrl = ScrollController(); // 解压日志自动滚动到底部
+
+ @override
+ void initState() {
+ super.initState();
+ _loadIsp();
+ }
+
+ /// 获取真实网络运营商
+ Future<void> _loadIsp() async {
+ try {
+ final n = await getNetworkInfo();
+ if (mounted) setState(() => _isp = n.isp);
+ } catch (_) {
+ if (mounted) setState(() => _isp = '未知');
+ }
+ }
+
+ @override
+ void dispose() {
+ _logCtrl.dispose();
+ super.dispose();
+ }
+
+ /// 安装完成后启动游戏
+ Future<void> _launchGame(DownloadTask task) async {
+ final ok = await launchInstalledGame(task.title, task.launchExe);
+ if (!ok && mounted) {
+ _toast('未找到游戏文件,请重新下载安装');
+ }
+ }
+
+ void _toast(String msg) {
+ final overlay = Overlay.of(context);
+ final entry = OverlayEntry(
+ builder: (context) => Positioned(
+ top: 60,
+ left: MediaQuery.of(context).size.width / 2 - 140,
+ child: Material(
+ color: Colors.transparent,
+ child: Container(
+ width: 280,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ decoration: BoxDecoration(
+ color: AppColors.red,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Row(
+ children: [
+ const Icon(Icons.error_outline, color: Colors.white, size: 18),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(msg,
+ style: const TextStyle(color: Colors.white, fontSize: 13)),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ overlay.insert(entry);
+ Future.delayed(const Duration(seconds: 2), () => entry.remove());
+ }
+
+ @override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: DownloadManager.instance,
@@ -43,6 +116,15 @@
),
);
}
+ // 环形进度:下载阶段用下载进度,安装(解压)阶段用解压进度
+ final displayProgress = task.extracting ? task.extractProgress : task.progress;
+ if (task.extracting) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (_logCtrl.hasClients) {
+ _logCtrl.jumpTo(_logCtrl.position.maxScrollExtent);
+ }
+ });
+ }
return Dialog(
backgroundColor: const Color(0xFF1E2130),
shape:
@@ -110,7 +192,7 @@
width: 86,
height: 86,
child: CircularProgressIndicator(
- value: task.finished ? 1 : task.progress,
+ value: task.finished ? 1 : displayProgress,
color: task.paused
? AppColors.yellow
: AppColors.accent,
@@ -119,7 +201,7 @@
),
),
Text(
- '${(task.progress * 100).toStringAsFixed(task.progress < 0.1 ? 2 : 0)}%',
+ '${(displayProgress * 100).toStringAsFixed(displayProgress < 0.1 ? 2 : 0)}%',
style: const TextStyle(
color: Colors.white,
fontSize: 15,
@@ -137,7 +219,7 @@
children: [
Text(
task.extracting
- ? '正在解压安装...'
+ ? '正在安装'
: task.extractFailed
? '解压失败'
: task.finished
@@ -160,11 +242,9 @@
),
const SizedBox(height: 8),
Text(
- task.extracting
- ? '解压中,请勿关闭软件'
- : task.extractFailed
- ? '压缩包保留在下载目录,可手动解压'
- : '${formatBytes(task.speed)}/s',
+ task.extractFailed
+ ? '压缩包保留在下载目录,可手动解压'
+ : formatSpeed(task.speed),
style: const TextStyle(
color: AppColors.textGray, fontSize: 13),
),
@@ -176,9 +256,11 @@
),
const SizedBox(height: 4),
Text(
- task.finished
- ? '已完成'
- : '剩余时间 ${formatDuration(task.etaSeconds)}',
+ task.extracting
+ ? '00:00:00'
+ : task.finished
+ ? '已完成'
+ : '剩余时间 ${formatDuration(task.etaSeconds)}',
style: const TextStyle(
color: AppColors.textGray, fontSize: 13),
),
@@ -188,103 +270,157 @@
],
),
const SizedBox(height: 16),
- // 网络信息条
+ // 网络信息条 + 收起详细任务
Container(
- padding:
- const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
- decoration: BoxDecoration(
- color: AppColors.bg,
- borderRadius: BorderRadius.circular(4),
+ padding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: AppColors.bg,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Row(
+ children: [
+ Text('网络运营商:$_isp',
+ style: const TextStyle(
+ color: AppColors.textGray, fontSize: 12)),
+ const Spacer(),
+ GestureDetector(
+ onTap: () =>
+ setState(() => _showDetails = !_showDetails),
+ child: Row(
+ children: [
+ Text(
+ _showDetails ? '收起详细任务' : '展开详细任务',
+ style: const TextStyle(
+ color: AppColors.textGray, fontSize: 12)),
+ const SizedBox(width: 4),
+ Icon(
+ _showDetails
+ ? Icons.keyboard_arrow_up
+ : Icons.keyboard_arrow_down,
+ color: AppColors.textGray,
+ size: 14),
+ ],
+ ),
),
- child: Row(
- children: [
- const Text('网络运营商:联通',
- style: TextStyle(
- color: AppColors.textGray, fontSize: 12)),
- const Spacer(),
- const Text('点击切换线路:自动',
- style: TextStyle(
- color: AppColors.textGray, fontSize: 12)),
- ],
+ const SizedBox(width: 16),
+ const Text('点击切换线路:自动',
+ style: TextStyle(
+ color: AppColors.textGray, fontSize: 12)),
+ ],
+ ),
+ ),
+ if (_showDetails) ...[
+ const SizedBox(height: 10),
+ // 详细任务列表:下载阶段显示分卷下载,安装阶段显示解压日志
+ Container(
+ constraints: const BoxConstraints(maxHeight: 180),
+ decoration: BoxDecoration(
+ color: AppColors.bg,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: task.extracting || task.extractFailed
+ ? ListView.builder(
+ shrinkWrap: true,
+ controller: _logCtrl,
+ itemCount: task.extractLog.length,
+ itemBuilder: (context, i) {
+ final e = task.extractLog[i];
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12, vertical: 6),
+ child: Row(
+ children: [
+ SizedBox(
+ width: 40,
+ child: Text('${e.percent}%',
+ style: const TextStyle(
+ color: AppColors.textWhite,
+ fontSize: 11)),
+ ),
+ Expanded(
+ child: Text(e.path,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ color: AppColors.textGray,
+ fontSize: 11)),
+ ),
+ ],
+ ),
+ );
+ },
+ )
+ : ListView.builder(
+ shrinkWrap: true,
+ itemCount: task.files.length,
+ itemBuilder: (context, i) {
+ final f = task.files[i];
+ Color stColor = AppColors.textDim;
+ String stLabel = '等待下载';
+ switch (f.status) {
+ case DownloadStatus.preparing:
+ stColor = AppColors.yellow;
+ stLabel = '正在准备';
+ case DownloadStatus.downloading:
+ stColor = AppColors.green;
+ stLabel = '正在下载';
+ case DownloadStatus.paused:
+ stColor = AppColors.yellow;
+ stLabel = '已暂停';
+ case DownloadStatus.done:
+ stColor = AppColors.green;
+ stLabel = '已完成';
+ case DownloadStatus.failed:
+ stColor = AppColors.red;
+ stLabel = '下载失败';
+ default:
+ stLabel = '等待下载';
+ }
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12, vertical: 6),
+ child: Row(
+ children: [
+ SizedBox(
+ width: 200,
+ child: Text(f.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ color: AppColors.textWhite,
+ fontSize: 12)),
+ ),
+ Expanded(
+ child: LinearProgressIndicator(
+ value: f.progress,
+ backgroundColor: AppColors.bgLighter,
+ color: AppColors.accent,
+ minHeight: 3,
+ ),
+ ),
+ const SizedBox(width: 10),
+ SizedBox(
+ width: 130,
+ child: Text(
+ '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
+ style: const TextStyle(
+ color: AppColors.textGray,
+ fontSize: 11)),
+ ),
+ SizedBox(
+ width: 60,
+ child: Text(stLabel,
+ style: TextStyle(
+ color: stColor, fontSize: 11)),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
),
- ),
- const SizedBox(height: 10),
- // 文件列表
- Container(
- constraints: const BoxConstraints(maxHeight: 180),
- decoration: BoxDecoration(
- color: AppColors.bg,
- borderRadius: BorderRadius.circular(4),
- ),
- child: ListView.builder(
- shrinkWrap: true,
- itemCount: task.files.length,
- itemBuilder: (context, i) {
- final f = task.files[i];
- Color stColor = AppColors.textDim;
- String stLabel = '等待下载';
- switch (f.status) {
- case DownloadStatus.preparing:
- stColor = AppColors.yellow;
- stLabel = '正在准备';
- case DownloadStatus.downloading:
- stColor = AppColors.green;
- stLabel = '正在下载';
- case DownloadStatus.paused:
- stColor = AppColors.yellow;
- stLabel = '已暂停';
- case DownloadStatus.done:
- stColor = AppColors.green;
- stLabel = '已完成';
- case DownloadStatus.failed:
- stColor = AppColors.red;
- stLabel = '下载失败';
- default:
- stLabel = '等待下载';
- }
- return Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12, vertical: 6),
- child: Row(
- children: [
- SizedBox(
- width: 200,
- child: Text(f.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- color: AppColors.textWhite,
- fontSize: 12)),
- ),
- Expanded(
- child: LinearProgressIndicator(
- value: f.progress,
- backgroundColor: AppColors.bgLighter,
- color: AppColors.accent,
- minHeight: 3,
- ),
- ),
- const SizedBox(width: 10),
- SizedBox(
- width: 130,
- child: Text(
- '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
- style: const TextStyle(
- color: AppColors.textGray,
- fontSize: 11)),
- ),
- SizedBox(
- width: 60,
- child: Text(stLabel,
- style: TextStyle(
- color: stColor, fontSize: 11)),
- ),
- ],
- ),
- );
- },
- ),
- ),
+ ],
const SizedBox(height: 18),
// 操作按钮
Row(
@@ -301,34 +437,54 @@
}
},
style: ElevatedButton.styleFrom(
- backgroundColor: task.paused
- ? AppColors.accent
- : const Color(0xFF3A3F52),
+ backgroundColor: AppColors.accent,
foregroundColor: Colors.white,
- disabledBackgroundColor:
- AppColors.green.withOpacity(0.3),
+ disabledBackgroundColor: AppColors.bgLighter,
+ disabledForegroundColor: AppColors.textDim,
padding: const EdgeInsets.symmetric(vertical: 12),
),
- child: Text(task.finished
- ? '下载完成'
- : task.paused
- ? '继续下载'
- : '暂停下载'),
+ child: Text(task.extracting
+ ? '正在安装'
+ : task.finished
+ ? '下载完成'
+ : task.paused
+ ? '继续下载'
+ : '暂停下载'),
),
),
const SizedBox(width: 12),
Expanded(
child: ElevatedButton(
- onPressed: () {
- DownloadManager.instance.cancelTask();
- Navigator.pop(context);
- },
+ // 安装完成后变为启动按钮
+ onPressed: task.extracting
+ ? null
+ : (task.finished && !task.extractFailed)
+ ? () => _launchGame(task)
+ : () {
+ DownloadManager.instance.cancelTask();
+ Navigator.pop(context);
+ },
style: ElevatedButton.styleFrom(
- backgroundColor: const Color(0xFF3A3F52),
+ backgroundColor:
+ (task.finished && !task.extractFailed)
+ ? AppColors.accent
+ : const Color(0xFF3A3F52),
foregroundColor: Colors.white,
+ disabledBackgroundColor: AppColors.bgLighter,
+ disabledForegroundColor: AppColors.textDim,
padding: const EdgeInsets.symmetric(vertical: 12),
),
- child: const Text('取消安装'),
+ child: (task.finished && !task.extractFailed)
+ ? const Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.play_arrow, size: 18),
+ SizedBox(width: 8),
+ Text('启动游戏',
+ style: TextStyle(fontSize: 14)),
+ ],
+ )
+ : const Text('取消安装'),
),
),
],
@@ -398,3 +554,152 @@
}
Process.run('explorer.exe', [p.normalize(dir.path)]);
}
+
+/// 下载路径选择弹窗(详情页下载、资源库安装共用)
+class DownloadPathDialog extends StatefulWidget {
+ final String gameTitle;
+ const DownloadPathDialog({super.key, required this.gameTitle});
+ @override
+ State<DownloadPathDialog> createState() => _DownloadPathDialogState();
+}
+
+class _DownloadPathDialogState extends State<DownloadPathDialog> {
+ final _dlCtrl = TextEditingController();
+ final _insCtrl = TextEditingController();
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ @override
+ void dispose() {
+ _dlCtrl.dispose();
+ _insCtrl.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load() async {
+ final dl = await AppPrefs.getDownloadPath();
+ final ins = await AppPrefs.getInstallPath();
+ setState(() {
+ _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
+ _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ backgroundColor: const Color(0xFF1E2130),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+ child: Container(
+ width: 500,
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ const Icon(Icons.folder,
+ size: 16, color: AppColors.textGray),
+ const SizedBox(width: 8),
+ const Text('请选择下载安装路径',
+ style: TextStyle(
+ color: Colors.white,
+ fontSize: 14,
+ fontWeight: FontWeight.w500)),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => Navigator.pop(context, false),
+ child: const Icon(Icons.close,
+ size: 16, color: AppColors.textGray),
+ ),
+ ],
+ ),
+ const SizedBox(height: 18),
+ _pathRow('下载路径', _dlCtrl),
+ const SizedBox(height: 12),
+ _pathRow('安装路径', _insCtrl),
+ const SizedBox(height: 20),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ OutlinedButton(
+ onPressed: () => Navigator.pop(context, false),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: AppColors.textGray,
+ side: const BorderSide(color: AppColors.bgLighter),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('取消'),
+ ),
+ const SizedBox(width: 12),
+ ElevatedButton(
+ onPressed: () async {
+ await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
+ if (context.mounted) Navigator.pop(context, true);
+ },
+ style: ElevatedButton.styleFrom(
+ backgroundColor: AppColors.accent,
+ foregroundColor: Colors.white,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 22, vertical: 10),
+ ),
+ child: const Text('确认'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _pathRow(String label, TextEditingController ctrl) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(label,
+ style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
+ const SizedBox(height: 6),
+ Row(
+ children: [
+ Expanded(
+ child: TextField(
+ controller: ctrl,
+ style: const TextStyle(color: Colors.black, fontSize: 13),
+ decoration: InputDecoration(
+ filled: true,
+ fillColor: Colors.white,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 10, vertical: 10),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(4),
+ borderSide: BorderSide.none),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ ElevatedButton(
+ onPressed: () async {
+ final dir = await FilePicker.platform.getDirectoryPath();
+ if (dir != null) setState(() => ctrl.text = dir);
+ },
+ style: ElevatedButton.styleFrom(
+ backgroundColor: AppColors.accent,
+ foregroundColor: Colors.white,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 14, vertical: 11),
+ ),
+ child: const Text('选择目录', style: TextStyle(fontSize: 12)),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+}
diff --git a/fluttergamebox/lib/widgets/info_dialogs.dart b/fluttergamebox/lib/widgets/info_dialogs.dart
index 58950ab..e0ca214 100644
--- a/fluttergamebox/lib/widgets/info_dialogs.dart
+++ b/fluttergamebox/lib/widgets/info_dialogs.dart
@@ -3,6 +3,7 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:fluttergamebox/common/theme.dart';
+import 'package:fluttergamebox/utils/network_info.dart';
import 'package:fluttergamebox/utils/util.dart';
String _wmic(String cmd, String arg) {
@@ -45,14 +46,99 @@
return '00326-60000-00000-AA068';
}
-/// 电脑网络信息弹窗
+/// 电脑网络信息弹窗(获取真实网络信息)
void showNetworkInfoDialog(BuildContext context) {
- final lines = [
- '公网IP: 获取中...',
- '地区: 中国',
- '运营商: 联通',
- ];
- _greenInfoDialog(context, '电脑网络信息', Icons.wifi, lines);
+ showDialog(
+ context: context,
+ builder: (context) => const _NetworkInfoDialog(),
+ );
+}
+
+class _NetworkInfoDialog extends StatefulWidget {
+ const _NetworkInfoDialog();
+ @override
+ State<_NetworkInfoDialog> createState() => _NetworkInfoDialogState();
+}
+
+class _NetworkInfoDialogState extends State<_NetworkInfoDialog> {
+ List<String> _lines = ['正在获取网络信息...'];
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ Future<void> _load() async {
+ final n = await getNetworkInfo();
+ final lines = [
+ '连接方式: ${n.connType}',
+ '内网IP: ${n.localIp}',
+ '网关: ${n.gateway}',
+ 'DNS: ${n.dns}',
+ '公网IP: ${n.publicIp}',
+ '地区: ${n.location}',
+ '运营商: ${n.isp}',
+ ];
+ if (mounted) setState(() => _lines = lines);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ backgroundColor: const Color(0xFF14161F),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+ child: Container(
+ width: 420,
+ padding: EdgeInsets.zero,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // 标题栏
+ Container(
+ height: 40,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ decoration: BoxDecoration(
+ color: const Color(0xFF191C2B),
+ borderRadius:
+ const BorderRadius.vertical(top: Radius.circular(6)),
+ ),
+ child: Row(
+ children: [
+ const Icon(Icons.wifi, size: 16, color: AppColors.textGray),
+ const SizedBox(width: 8),
+ const Text('电脑网络信息',
+ style: TextStyle(color: Colors.white, fontSize: 13)),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => Navigator.pop(context),
+ child: const Icon(Icons.close,
+ size: 16, color: AppColors.textGray),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(20),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: _lines
+ .map((l) => Padding(
+ padding: const EdgeInsets.symmetric(vertical: 3),
+ child: Text(l,
+ style: const TextStyle(
+ color: Color(0xFF33FF66),
+ fontSize: 13,
+ fontFamily: 'Consolas')),
+ ))
+ .toList(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
}
void _greenInfoDialog(
diff --git a/server/admin/index.html b/server/admin/index.html
index 9766eed..5c6baf7 100644
--- a/server/admin/index.html
+++ b/server/admin/index.html
@@ -97,6 +97,8 @@
<button class="active" data-tab="keys" onclick="switchTab('keys')">密钥管理</button>
<button data-tab="games" onclick="switchTab('games')">游戏管理</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>
@@ -107,11 +109,11 @@
<div id="tab-keys" class="panel">
<h2>会员密钥</h2>
<div class="toolbar">
- <select id="genType"><option value="day">日卡</option><option value="month">月卡</option><option value="year">年卡</option></select>
+ <select id="genType"><option value="day">日卡</option><option value="month">月卡</option><option value="year">年卡</option><option value="forever">永久卡</option></select>
<input id="genCount" type="number" value="10" min="1" max="100" style="width:80px">
<button class="btn" onclick="generateKeys()">生成密钥</button>
<span style="flex:1"></span>
- <input id="keyKeyword" placeholder="搜索激活码">
+ <input id="keyKeyword" placeholder="搜索激活码/手机号">
<select id="keyStatus">
<option value="">全部状态</option>
<option value="0">未使用</option>
@@ -151,6 +153,28 @@
<tbody id="catTable"></tbody>
</table>
</div>
+
+ <!-- 公告设置 -->
+ <div id="tab-ann" class="panel hidden">
+ <h2>首页公告</h2>
+ <p style="color:#888;font-size:12px;margin-bottom:14px">客户端打开首页时自动弹出的系统公告;内容留空则不弹出。</p>
+ <div class="form-row">
+ <textarea id="annContent" style="min-height:180px" placeholder="请输入公告内容..."></textarea>
+ </div>
+ <button class="btn" onclick="saveAnnouncement()">保存公告</button>
+ </div>
+
+ <!-- 工具管理 -->
+ <div id="tab-tools" class="panel hidden">
+ <h2>工具管理</h2>
+ <div class="toolbar">
+ <button class="btn" onclick="showToolModal()">+ 添加工具</button>
+ </div>
+ <table>
+ <thead><tr><th>ID</th><th>封面</th><th>名称</th><th>大小</th><th>描述</th><th>下载文件</th><th>操作</th></tr></thead>
+ <tbody id="toolTable"></tbody>
+ </table>
+ </div>
</div>
</div>
@@ -206,6 +230,30 @@
<div id="toast" class="toast"></div>
+<!-- 工具编辑弹窗 -->
+<div id="toolModal" class="modal-mask hidden">
+ <div class="modal">
+ <h3 id="toolModalTitle">添加工具</h3>
+ <input type="hidden" id="t_id">
+ <div class="form-row"><label>工具名称 *</label><input id="t_name" placeholder="如:百度网盘"></div>
+ <div class="form-row"><label>大小(如 85.2MB)</label><input id="t_size"></div>
+ <div class="form-row"><label>封面图</label>
+ <input id="t_cover" placeholder="封面图URL,或点击上传" onchange="renderToolCover()">
+ <input type="file" accept="image/*" onchange="uploadSingle(this, 'image', 't_cover'); setTimeout(renderToolCover, 500)">
+ <div id="t_cover_list"></div>
+ </div>
+ <div class="form-row"><label>下载文件</label>
+ <input id="t_file_url" placeholder="安装包URL,或点击上传">
+ <input type="file" onchange="uploadSingle(this, 'file', 't_file_url')">
+ </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>
+ <button class="btn" onclick="saveTool()">保存</button>
+ </div>
+ </div>
+</div>
+
<script>
let token = localStorage.getItem('admin_token') || '';
let editingScreenshots = [], editingFiles = [];
@@ -247,11 +295,11 @@
function enterPanel() {
document.getElementById('loginPage').style.display = 'none';
document.getElementById('mainPage').style.display = 'flex';
- loadStats(); loadKeys(1); loadGames(); loadCategories();
+ loadStats(); loadKeys(1); loadGames(); loadCategories(); loadAnnouncement(); loadTools();
}
function switchTab(tab) {
document.querySelectorAll('.nav-tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
- ['keys','games','cats'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
+ ['keys','games','cats','ann','tools'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
}
async function loadStats() {
@@ -293,15 +341,17 @@
if (k.status === 0) { st = '未使用'; cls = 'tag-blue'; }
else if (k.expired) { st = '已过期'; cls = 'tag-red'; }
else { st = '使用中'; cls = 'tag-green'; }
+ if (k.frozen) st += ' · 已冻结';
return `<tr>
<td>${k.id}</td><td style="font-family:Consolas">${k.code}</td>
<td><span class="tag tag-gray">${k.card_name}</span></td>
- <td><span class="tag ${cls}">${st}</span></td>
+ <td><span class="tag ${k.frozen ? 'tag-red' : cls}">${st}</span></td>
<td>${k.phone || '-'}</td>
<td style="max-width:160px;overflow:hidden;text-overflow:ellipsis">${k.machine_code || '-'}</td>
<td>${k.expired_at_str || '-'}</td>
<td>${k.reset_count}</td>
<td>
+ <button class="btn btn-sm" onclick="freezeKey(${k.id})">${k.frozen ? '解冻' : '冻结'}</button>
${k.status === 1 ? `<button class="btn btn-sm" onclick="resetKey(${k.id})">重置(可再用)</button> ` : ''}
<button class="btn btn-sm btn-danger" onclick="deleteKey(${k.id})">删除</button>
</td></tr>`;
@@ -318,6 +368,12 @@
toast(res.msg, res.code !== 0);
loadKeys(keyPage);
}
+async function freezeKey(id) {
+ if (!confirm('确定冻结/解冻该密钥?冻结后该激活码无法使用。')) return;
+ const res = await api(`/admin/api/keys/${id}/freeze`, {method: 'POST'});
+ toast(res.msg, res.code !== 0);
+ loadKeys(keyPage);
+}
async function deleteKey(id) {
if (!confirm('确定删除该密钥?')) return;
const res = await api(`/admin/api/keys/${id}`, {method: 'DELETE'});
@@ -499,6 +555,72 @@
loadCategories();
}
+/* ---------- 公告 ---------- */
+async function loadAnnouncement() {
+ const res = await api('/admin/api/announcement');
+ if (res.code !== 0) return;
+ document.getElementById('annContent').value = (res.data && res.data.content) || '';
+}
+async function saveAnnouncement() {
+ const content = document.getElementById('annContent').value;
+ const res = await api('/admin/api/announcement', {method: 'POST', body: {content}});
+ toast(res.msg, res.code !== 0);
+}
+
+/* ---------- 工具管理 ---------- */
+async function loadTools() {
+ const res = await api('/admin/api/tools');
+ if (res.code !== 0) return;
+ const rows = res.data.map(t => `<tr>
+ <td>${t.id}</td>
+ <td><img src="${t.cover}" style="width:56px;height:36px;object-fit:cover;border-radius:4px" onerror="this.style.visibility='hidden'"></td>
+ <td>${t.name}</td>
+ <td>${t.size || '-'}</td>
+ <td style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${t.description || ''}">${t.description || '-'}</td>
+ <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${t.file_url || ''}">${t.file_url || '-'}</td>
+ <td>
+ <button class="btn btn-sm" onclick='showToolModal(${JSON.stringify(t).replace(/'/g,"'")})'>修改</button>
+ <button class="btn btn-sm btn-danger" onclick="deleteTool(${t.id})">删除</button>
+ </td></tr>`).join('');
+ document.getElementById('toolTable').innerHTML = rows || '<tr><td colspan="7" style="text-align:center;color:#666">暂无数据</td></tr>';
+}
+function renderToolCover() {
+ const url = document.getElementById('t_cover').value;
+ document.getElementById('t_cover_list').innerHTML = url ? `<div class="file-item"><img src="${url}"><span>${url}</span></div>` : '';
+}
+function showToolModal(t) {
+ document.getElementById('toolModalTitle').innerText = t ? '修改工具' : '添加工具';
+ document.getElementById('t_id').value = t ? t.id : '';
+ document.getElementById('t_name').value = t ? t.name : '';
+ 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_description').value = t ? (t.description || '') : '';
+ renderToolCover();
+ document.getElementById('toolModal').classList.remove('hidden');
+}
+function hideToolModal() { document.getElementById('toolModal').classList.add('hidden'); }
+async function saveTool() {
+ const body = {
+ id: parseInt(document.getElementById('t_id').value) || 0,
+ name: document.getElementById('t_name').value.trim(),
+ size: document.getElementById('t_size').value.trim(),
+ cover: document.getElementById('t_cover').value.trim(),
+ file_url: document.getElementById('t_file_url').value.trim(),
+ description: document.getElementById('t_description').value.trim(),
+ };
+ if (!body.name) return toast('请填写工具名称', true);
+ const res = await api('/admin/api/tools', {method: 'POST', body});
+ toast(res.msg, res.code !== 0);
+ if (res.code === 0) { hideToolModal(); loadTools(); }
+}
+async function deleteTool(id) {
+ if (!confirm('确定删除该工具?')) return;
+ const res = await api(`/admin/api/tools/${id}`, {method: 'DELETE'});
+ toast(res.msg, res.code !== 0);
+ loadTools();
+}
+
document.getElementById('adminPwd').addEventListener('keydown', e => { if (e.key === 'Enter') adminLogin(); });
if (token) enterPanel();
</script>
diff --git a/server/handlers/admin.go b/server/handlers/admin.go
index acaddb7..cd59794 100644
--- a/server/handlers/admin.go
+++ b/server/handlers/admin.go
@@ -47,7 +47,7 @@
CardType string `json:"card_type"` // day/month/year
Count int `json:"count"`
}
- if err := c.ShouldBindJSON(&req); err != nil || cardDuration(req.CardType) == 0 {
+ if err := c.ShouldBindJSON(&req); err != nil || !validCardType(req.CardType) {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "卡密类型错误"})
return
}
@@ -68,16 +68,24 @@
// ListKeys 密钥列表
func ListKeys(c *gin.Context) {
keyword := c.Query("keyword")
- status := c.Query("status") // ""全部 0未使用 1已使用 2已过期
+ status := c.Query("status") // ""全部 0未使用 1已使用(含永久) 2已过期
query := config.DB.Model(&models.MemberKey{})
if keyword != "" {
- query = query.Where("code LIKE ?", "%"+keyword+"%")
+ // 同时支持按激活码或绑定用户手机号搜索
+ var userIDs []uint
+ config.DB.Model(&models.User{}).Where("phone LIKE ?", "%"+keyword+"%").Pluck("id", &userIDs)
+ if len(userIDs) > 0 {
+ query = query.Where("code LIKE ? OR user_id IN ?", "%"+keyword+"%", userIDs)
+ } else {
+ query = query.Where("code LIKE ?", "%"+keyword+"%")
+ }
}
switch status {
case "0":
query = query.Where("status = ?", 0)
case "1":
- query = query.Where("status = ? AND expired_at > ?", 1, time.Now())
+ // 已使用且未过期(永久卡 expired_at 为 NULL)
+ query = query.Where("status = ? AND (expired_at IS NULL OR expired_at > ?)", 1, time.Now())
case "2":
query = query.Where("status = ? AND expired_at <= ?", 1, time.Now())
}
@@ -118,6 +126,10 @@
vo.Expired = k.ExpiredAt.Before(time.Now())
s := k.ExpiredAt.Format("2006-01-02 15:04:05")
vo.ExpiredAtStr = &s
+ } else if k.Status == 1 {
+ // 已使用的永久卡
+ s := "永久"
+ vo.ExpiredAtStr = &s
}
list = append(list, vo)
}
@@ -149,6 +161,74 @@
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
}
+// FreezeKey 冻结/解冻密钥(冻结后无法激活使用)
+func FreezeKey(c *gin.Context) {
+ id := c.Param("id")
+ var key models.MemberKey
+ if err := config.DB.First(&key, id).Error; err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "密钥不存在"})
+ return
+ }
+ target := !key.Frozen
+ config.DB.Model(&key).Update("frozen", target)
+ msg := "密钥已冻结,无法使用"
+ if !target {
+ msg = "密钥已解冻,可正常使用"
+ }
+ c.JSON(http.StatusOK, gin.H{"code": 0, "msg": msg})
+}
+
+// ---------- 工具管理 ----------
+
+// AdminListTools 工具列表
+func AdminListTools(c *gin.Context) {
+ var tools []models.Tool
+ config.DB.Order("id DESC").Find(&tools)
+ c.JSON(http.StatusOK, gin.H{"code": 0, "data": tools})
+}
+
+// AdminSaveTool 新增/编辑工具
+func AdminSaveTool(c *gin.Context) {
+ var req struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Size string `json:"size"`
+ Cover string `json:"cover"`
+ Description string `json:"description"`
+ FileURL string `json:"file_url"`
+ }
+ if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Name) == "" {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请填写工具名称"})
+ return
+ }
+ var tool models.Tool
+ if req.ID > 0 {
+ if err := config.DB.First(&tool, req.ID).Error; err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "工具不存在"})
+ return
+ }
+ } else {
+ tool = models.Tool{}
+ }
+ tool.Name = req.Name
+ tool.Size = req.Size
+ tool.Cover = req.Cover
+ tool.Description = req.Description
+ tool.FileURL = req.FileURL
+ if req.ID > 0 {
+ config.DB.Save(&tool)
+ } else {
+ config.DB.Create(&tool)
+ }
+ c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已保存"})
+}
+
+// AdminDeleteTool 删除工具
+func AdminDeleteTool(c *gin.Context) {
+ config.DB.Delete(&models.Tool{}, c.Param("id"))
+ c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
+}
+
// ---------- 游戏管理 ----------
func AdminListGames(c *gin.Context) {
@@ -296,4 +376,34 @@
}})
}
+// ---------- 公告管理 ----------
+
+// AdminGetAnnouncement 获取当前首页公告(最新一条,无则返回空内容)
+func AdminGetAnnouncement(c *gin.Context) {
+ var ann models.Announcement
+ if err := config.DB.Order("id DESC").First(&ann).Error; err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"content": ""}})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"code": 0, "data": ann})
+}
+
+// AdminSaveAnnouncement 保存首页公告(更新最新一条,无则新建;内容为空表示不弹出)
+func AdminSaveAnnouncement(c *gin.Context) {
+ var req struct {
+ Content string `json:"content"`
+ }
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误"})
+ return
+ }
+ var ann models.Announcement
+ if err := config.DB.Order("id DESC").First(&ann).Error; err == nil {
+ config.DB.Model(&ann).Update("content", req.Content)
+ } else {
+ config.DB.Create(&models.Announcement{Content: req.Content})
+ }
+ c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "公告已保存"})
+}
+
var _ = io.Discard
diff --git a/server/handlers/auth.go b/server/handlers/auth.go
index f6fe7c2..1961433 100644
--- a/server/handlers/auth.go
+++ b/server/handlers/auth.go
@@ -155,17 +155,24 @@
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户不存在"})
return
}
- // 查询会员有效期(取最大的未过期时间)
+ // 查询会员有效期(永久卡 expired_at 为 NULL;取最大的未过期时间)
var keys []models.MemberKey
- config.DB.Where("user_id = ? AND expired_at > ?", userID, time.Now()).Find(&keys)
+ config.DB.Where("user_id = ? AND (expired_at IS NULL OR expired_at > ?)", userID, time.Now()).Find(&keys)
+ permanent := false
var expire *time.Time
for i := range keys {
+ if keys[i].ExpiredAt == nil {
+ permanent = true
+ continue
+ }
if expire == nil || keys[i].ExpiredAt.After(*expire) {
expire = keys[i].ExpiredAt
}
}
- member := gin.H{"is_member": expire != nil}
- if expire != nil {
+ member := gin.H{"is_member": permanent || expire != nil}
+ if permanent {
+ member["expire_at"] = "永久"
+ } else if expire != nil {
member["expire_at"] = expire.Format("2006-01-02 15:04:05")
}
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
diff --git a/server/handlers/games.go b/server/handlers/games.go
index b448244..6b0f3d4 100644
--- a/server/handlers/games.go
+++ b/server/handlers/games.go
@@ -200,9 +200,9 @@
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "游戏不存在"})
return
}
- // 校验会员是否有效
+ // 校验会员是否有效(永久卡 expired_at 为 NULL)
var keys []models.MemberKey
- config.DB.Where("user_id = ? AND expired_at > ?", userID, time.Now()).Find(&keys)
+ config.DB.Where("user_id = ? AND (expired_at IS NULL OR expired_at > ?)", userID, time.Now()).Find(&keys)
if len(keys) == 0 {
c.JSON(http.StatusOK, gin.H{"code": 2, "msg": "您的会员已到期,无法下载游戏。请激活新的会员密钥!"})
return
diff --git a/server/handlers/keys.go b/server/handlers/keys.go
index fceea00..436f3b2 100644
--- a/server/handlers/keys.go
+++ b/server/handlers/keys.go
@@ -19,7 +19,16 @@
case "year":
return 365 * 24 * time.Hour
}
- return 0
+ return 0 // forever(永久卡)无固定时长,由调用方特殊处理
+}
+
+// validCardType 是否为合法卡类型
+func validCardType(cardType string) bool {
+ switch cardType {
+ case "day", "month", "year", "forever":
+ return true
+ }
+ return false
}
// ActivateKey 激活会员密钥(绑定机器)
@@ -42,20 +51,34 @@
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "激活码不存在,请检查后重新输入"})
return
}
+ // 冻结的密钥不可使用
+ if key.Frozen {
+ c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已被冻结,无法使用!"})
+ return
+ }
now := time.Now()
if key.Status == 0 {
// 未使用,直接激活
- expired := now.Add(cardDuration(key.CardType))
- config.DB.Model(&key).Updates(map[string]interface{}{
+ updates := map[string]interface{}{
"status": 1,
"user_id": userID,
"machine_code": req.MachineCode,
"activated_at": now,
- "expired_at": expired,
- })
+ }
+ // 永久卡不设置到期时间
+ if key.CardType == "forever" {
+ updates["expired_at"] = nil
+ } else {
+ updates["expired_at"] = now.Add(cardDuration(key.CardType))
+ }
+ config.DB.Model(&key).Updates(updates)
+ expireStr := "永久"
+ if expiredAt, ok := updates["expired_at"].(time.Time); ok {
+ expireStr = expiredAt.Format("2006-01-02 15:04:05")
+ }
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "激活成功!", "data": gin.H{
- "expire_at": expired.Format("2006-01-02 15:04:05"),
+ "expire_at": expireStr,
}})
return
}
@@ -70,7 +93,11 @@
return
}
// 同机器重复激活,返回当前有效期
+ expireStr := "永久"
+ if key.ExpiredAt != nil {
+ expireStr = key.ExpiredAt.Format("2006-01-02 15:04:05")
+ }
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "该激活码已在此设备激活", "data": gin.H{
- "expire_at": key.ExpiredAt.Format("2006-01-02 15:04:05"),
+ "expire_at": expireStr,
}})
}
diff --git a/server/main.go b/server/main.go
index f7130a4..3a1e2bc 100644
--- a/server/main.go
+++ b/server/main.go
@@ -69,8 +69,13 @@
a.GET("/keys", handlers.ListKeys)
a.POST("/keys/generate", handlers.GenerateKeys)
a.POST("/keys/:id/reset", handlers.ResetKey)
+ a.POST("/keys/:id/freeze", handlers.FreezeKey)
a.DELETE("/keys/:id", handlers.DeleteKey)
+ a.GET("/tools", handlers.AdminListTools)
+ a.POST("/tools", handlers.AdminSaveTool)
+ a.DELETE("/tools/:id", handlers.AdminDeleteTool)
+
a.GET("/games", handlers.AdminListGames)
a.POST("/games", handlers.AdminSaveGame)
a.DELETE("/games/:id", handlers.AdminDeleteGame)
@@ -79,6 +84,9 @@
a.POST("/categories", handlers.AdminSaveCategory)
a.DELETE("/categories/:id", handlers.AdminDeleteCategory)
+ a.GET("/announcement", handlers.AdminGetAnnouncement)
+ a.POST("/announcement", handlers.AdminSaveAnnouncement)
+
a.POST("/upload", handlers.UploadFile)
}
}
diff --git a/server/models/models.go b/server/models/models.go
index 3f955bf..48b2af7 100644
--- a/server/models/models.go
+++ b/server/models/models.go
@@ -62,12 +62,13 @@
type MemberKey struct {
ID uint `gorm:"primaryKey" json:"id"`
Code string `gorm:"uniqueIndex;size:50" json:"code"`
- CardType string `gorm:"size:20" json:"card_type"` // day/month/year
+ CardType string `gorm:"size:20" json:"card_type"` // day/month/year/forever
Status int `json:"status"` // 0未使用 1已使用
+ Frozen bool `gorm:"default:false" json:"frozen"` // 是否冻结(冻结后不可使用)
UserID uint `json:"user_id"`
MachineCode string `gorm:"size:100" json:"machine_code"`
ActivatedAt *time.Time `json:"activated_at"`
- ExpiredAt *time.Time `json:"expired_at"`
+ ExpiredAt *time.Time `json:"expired_at"` // nil 表示永久
ResetCount int `json:"reset_count"`
CreatedAt time.Time `json:"created_at"`
}
@@ -80,6 +81,8 @@
return "月卡"
case "year":
return "年卡"
+ case "forever":
+ return "永久卡"
}
return k.CardType
}
--
Gitblit v1.10.0