From 06445710da8bca536934c545b60558312c77dd3c Mon Sep 17 00:00:00 2001
From: driftinblock <3480428251@qq.com>
Date: Wed, 18 Nov 2026 21:31:08 +0800
Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0UI=EF=BC=8C=E4=BF=AE=E5=A4=8D?=
=?UTF-8?q?=E6=97=A0=E6=B3=95=E6=90=9C=E7=B4=A2=E6=A8=A1=E7=BB=84=E9=97=AE?=
=?UTF-8?q?=E9=A2=98=EF=BC=8C=E5=A2=9E=E5=8A=A0=E4=BA=86=E7=88=B1=E5=8F=91?=
=?UTF-8?q?=E7=94=B5=E7=AA=97=E5=8F=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 19 +-
android/app/src/main/AndroidManifest.xml | 2 +
.../src/main/res/drawable/ic_stat_monitor.xml | 11 +
lib/app.dart | 18 +-
lib/core/l10n/strings.dart | 76 ++++-
lib/core/services/notification_service.dart | 112 +++++++
lib/core/services/server_monitor_service.dart | 309 ++++++++++++++++++
lib/core/theme/app_theme.dart | 53 ++-
lib/core/utils/app_links.dart | 43 +++
lib/core/widgets/user_agreement_dialog.dart | 23 +-
lib/core/widgets/z_widgets.dart | 104 +++++-
lib/features/console/console_page.dart | 2 +-
lib/features/dashboard/dashboard_page.dart | 2 +-
lib/features/dashboard/server_picker_bar.dart | 2 +-
.../player_management/player_list_page.dart | 4 +-
.../server_list/server_form_dialog.dart | 2 +-
lib/features/settings/about_page.dart | 19 ++
.../settings/download_settings_page.dart | 4 +-
lib/features/settings/help_page.dart | 16 +-
lib/features/settings/server_log_page.dart | 4 +-
lib/features/settings/settings_page.dart | 288 +++++++++++++++-
lib/providers/download_provider.dart | 8 +-
lib/providers/theme_provider.dart | 73 +++--
pubspec.yaml | 5 +-
24 files changed, 1093 insertions(+), 106 deletions(-)
create mode 100644 android/app/src/main/res/drawable/ic_stat_monitor.xml
create mode 100644 lib/core/services/notification_service.dart
create mode 100644 lib/core/services/server_monitor_service.dart
create mode 100644 lib/core/utils/app_links.dart
diff --git a/README.md b/README.md
index c67b98e..7425c50 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,10 @@ ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。
| 控制台 | RCON 模式 | ✅ |
| 控制台 | 快速命令预设 | ✅ |
| 主题 | 浅色/深色/跟随系统 | ✅ |
+| 主题 | 多主题配色(ZL2 绿 / 海蓝 / 星紫 / 暖橙 / 樱粉)+ 胶囊开关式选项 | ✅ v2.0.3 新增 |
+| 支持 | 爱发电赞助 + 官方 QQ 群加群入口(关于页 / 设置页) | ✅ v2.0.3 新增 |
+| 状态监控 | 定时轮询服务器在线状态(30 秒 / 1 / 2 / 5 分钟可选) | ✅ v2.1 新增 |
+| 状态监控 | 离线 / 恢复 / 玩家上线系统通知(Android 13+ 运行时授权) | ✅ v2.1 新增 |
| 壁纸 | 自定义壁纸 | ✅ |
| 数据 | 加密存储 | ✅ |
| 模组管理 | SFTP 浏览 mods/plugins 目录 | ✅ v2.0 新增 |
@@ -32,7 +36,7 @@ ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。
| 下载中心 | 下载完成自动经 SFTP 上传到服务器对应目录 | ✅ v2.0 新增 |
| 终端 | SSH Shell(xterm 终端、快捷键栏、多会话标签、断线自动重连) | ✅ v2.0 新增 |
| UI | Dashboard 卡片式首页 + 底部导航(服务器/控制台/玩家/模组/终端/我的) | ✅ v2.0 新增 |
-| UI | 全站 ZL2 风格(分组圆角面板 / 两行式设置行 / 圆形绿底勾选钮 / 透明沉浸顶栏) | ✅ v2.0 新增 |
+| UI | 全站 ZL2 风格(分组圆角面板 / 两行式设置行 / 胶囊开关 / 透明沉浸顶栏) | ✅ v2.0 新增 |
| UI | 控制台日志级别着色(INFO 绿 / WARN 黄 / ERROR 红) | ✅ v2.0 新增 |
| 依赖仓库 | SQLite 依赖索引 + 增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测 | ✅ v2.0 新增 |
@@ -40,16 +44,17 @@ ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。
| 项目 | 说明 |
|------|------|
-| **版本** | 2.0.3 |
+| **版本** | 2.1.0 |
| **框架** | Flutter 3.x |
| **语言** | Dart 3.x |
| **目标平台** | Android 7.0+ / Web |
| **通信协议** | RCON (Minecraft 远程控制协议) + SSH/SFTP (dartssh2) |
| **本地存储** | Shared Preferences + Flutter Secure Storage + SQLite (依赖索引) |
| **状态管理** | Provider |
-| **主题** | Material 3 + ZL2 风格组件库(`core/widgets/z_widgets.dart`) |
+| **主题** | Material 3 + ZL2 风格组件库(`core/widgets/z_widgets.dart`)+ 5 套主题配色 |
| **网络** | Dio(Modrinth API / 镜像线路 / 下载队列) |
| **国际化** | 轻量 i18n(`core/l10n/strings.dart`,中 / 英) |
+| **通知** | flutter_local_notifications(状态监控提醒,Android 13+ 运行时授权) |
---
@@ -68,21 +73,27 @@ lib/
│ │ ├── jar_metadata.dart # jar 元数据解析(fabric.mod.json / plugin.yml)
│ │ ├── mirror_service.dart # 镜像线路(MCIM / 官方 / 自定义)+ 测速
│ │ ├── modrinth_api.dart # Modrinth API 客户端(镜像故障回退官方)
+│ │ ├── notification_service.dart # 系统通知(通道 / 权限 / 长文本)
+│ │ ├── server_monitor_service.dart # 状态监控(轮询 / 状态转移 / 抖动保护)
│ │ ├── sftp_service.dart # SFTP 文件传输
│ │ └── ssh_shell_service.dart # SSH Shell 会话
│ ├── theme/
│ │ └── app_theme.dart # Material 3 主题 + ZL2 配色
│ ├── utils/
+│ │ ├── app_links.dart # 外部链接配置(爱发电 / 官方 QQ 群)
│ │ ├── background_service.dart # 后台保活
│ │ ├── command_preset_service.dart # 控制台命令预设
│ │ ├── rcon_client.dart # RCON 客户端
│ │ ├── rcon_stream_parser.dart # RCON 流解析
+│ │ ├── release_notes.dart # 版本更新日志(按版本聚合)
+│ │ ├── update_info.dart # 更新信息模型
│ │ └── update_service.dart # Gitee Release 更新检查 / 安装
│ └── widgets/
│ ├── background_widget.dart # 全局壁纸背景(交叉淡入防闪)
│ ├── empty_state_page.dart # 空态占位页
+│ ├── update_dialog.dart # 版本更新弹窗(更新日志 / 下载进度)
│ ├── user_agreement_dialog.dart # 用户守则弹窗
-│ └── z_widgets.dart # ZL2 公共组件库(ZPanel / ZRow / ZToggle / ZAppBar / ZSheetRow …)
+│ └── z_widgets.dart # ZL2 公共组件库(ZPanel / ZRow / ZSwitch / ZAppBar / ZSheetRow …)
├── data/
│ └── services/
│ └── secure_storage_service.dart # 加密存储
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index b91a393..fd02a8a 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -5,6 +5,8 @@
+
+
+
+
+
diff --git a/lib/app.dart b/lib/app.dart
index 00dad26..96ba47c 100644
--- a/lib/app.dart
+++ b/lib/app.dart
@@ -9,10 +9,14 @@ import 'core/utils/update_service.dart';
import 'core/widgets/background_widget.dart';
import 'providers/wallpaper_provider.dart';
import 'core/widgets/user_agreement_dialog.dart'; // 新增
+import 'core/widgets/z_widgets.dart';
import 'features/shell/main_shell.dart';
import 'providers/theme_provider.dart';
import 'providers/language_provider.dart';
import 'providers/download_provider.dart';
+import 'providers/server_provider.dart';
+import 'providers/rcon_provider.dart';
+import 'core/services/server_monitor_service.dart';
import 'features/dashboard/server_picker_bar.dart';
/// 全局导航 Key
@@ -98,6 +102,14 @@ class ZVManagerAppState extends State {
// 这里绝不能再 create 新实例 —— 否则会生成一个空的影子 Provider,
// 导致更新后服务器列表"被清空"、添加时覆盖真实数据(v2.0 实测 bug)。
ChangeNotifierProvider(create: (_) => DownloadProvider()),
+ // 状态监控:复用 Bootstrap 里已预加载的 ServerProvider / RconProvider,
+ // 在 create 里惰性启动,避免拖慢冷启动。
+ ChangeNotifierProvider(
+ create: (ctx) => ServerMonitorService(
+ servers: ctx.read(),
+ rcon: ctx.read(),
+ )..load(),
+ ),
ChangeNotifierProvider(create: (_) => LanguageProvider()),
ChangeNotifierProvider(create: (_) => SelectedServerHolder()),
// 复用 main() 中预加载的实例,不能在这里 create 一个新的
@@ -107,12 +119,14 @@ class ZVManagerAppState extends State {
],
child: Consumer2(
builder: (context, themeProvider, languageProvider, child) {
+ // 全站强调色跟随当前主题配色(z_widgets 内组件共用同一个变量)
+ kZAccent = themeProvider.themeColor.seed;
return MaterialApp(
title: 'ZV Manager',
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
- theme: AppTheme.lightTheme,
- darkTheme: AppTheme.darkTheme,
+ theme: AppTheme.lightThemeFor(themeProvider.themeColor),
+ darkTheme: AppTheme.darkThemeFor(themeProvider.themeColor),
themeMode: themeProvider.flutterThemeMode,
locale: languageProvider.locale,
localizationsDelegates: const [
diff --git a/lib/core/l10n/strings.dart b/lib/core/l10n/strings.dart
index 71cd0c3..40a1b3f 100644
--- a/lib/core/l10n/strings.dart
+++ b/lib/core/l10n/strings.dart
@@ -166,6 +166,9 @@ class S {
'选择图片': 'Pick image',
'选择视频': 'Pick video',
'清除背景': 'Clear background',
+ '界面显示语言': 'Display language',
+ '选择一张图片或一段视频作为应用背景':
+ 'Pick an image or a video as the app background',
'使用教程(模组/终端等)': 'Tutorials (mods / terminal etc.)',
// ---- 模板插值 ----
'服务器「{0}」已断开连接!': 'Server "{0}" disconnected!',
@@ -253,6 +256,8 @@ class S {
'Q: Console connects but the mods page says no SSH? → Edit the server, enable SSH and fill in the credentials',
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线':
'Q: Connection failed? → Check firewall rules for the port, verify address/port, and confirm the server is online',
+ 'Q:开了监控却收不到通知?→ 检查系统是否允许本应用通知、是否开了省电限制':
+ 'Q: Monitoring is on but no alerts? → Check that notifications are allowed for this app and battery saving is not restricting it',
'SSH 拥有服务器完全控制权,请勿随意执行不熟悉的命令':
'SSH grants full server control; do not run unfamiliar commands carelessly',
'SSH 是服务器自带的远程管理服务,绝大多数独立服务器默认已开启(端口 22)':
@@ -268,7 +273,20 @@ class S {
'一、如何开启 RCON(必配,控制台/玩家管理需要)':
'1. How to enable RCON (required for console/player management)',
'一、软件性质与用途': '1. Nature and Purpose of the Software',
- '七、常见问题': '7. FAQ',
+ '七、状态监控与通知': '7. Status Monitoring and Notifications',
+ '进入「我的」→ 设置 → 「状态监控」,打开总开关':
+ 'Open Me → Settings → "Status monitoring" and turn the switch on',
+ '首次开启会申请通知权限(Android 13+),请点「允许」,否则提醒会被系统丢弃':
+ 'The first time you enable it, Android 13+ asks for notification permission — tap Allow, otherwise alerts are dropped',
+ '按需开启「服务器离线 / 服务器恢复 / 玩家上线」三类提醒':
+ 'Enable the offline / recovered / player-join alerts you want',
+ '「检查间隔」可选 30 秒 / 1 / 2 / 5 分钟,间隔越短发现越快、轮询压力越大':
+ '"Check interval" can be 30 s / 1 / 2 / 5 min; shorter is faster but polls more',
+ '点「立即检查一次」可手动验证 RCON 配置是否可用':
+ 'Tap "Check now" to verify the RCON configuration manually',
+ '提醒依赖 App 进程存活:彻底关闭 App 或被系统省电策略限制时不会推送':
+ 'Alerts need the app process alive: nothing is pushed once the app is fully closed or restricted by battery saving',
+ '八、常见问题': '8. FAQ',
'七、数据与隐私': '7. Data and Privacy',
'三、合法使用(重要)': '3. Lawful Use (Important)',
'三、模组 / 插件管理怎么用': '3. Using Mod / Plugin Management',
@@ -522,6 +540,62 @@ class S {
'请选择一台已配置 SSH 的服务器': 'Select a server with SSH configured',
'从 Gitee 获取最新版本': 'Fetch the latest version from Gitee',
'查看本应用使用的第三方库许可': 'View third-party licenses used by this app',
+ '支持作者 · 爱发电': 'Support us on Afdian',
+ '通过爱发电支持项目开发': 'Support development via Afdian',
+ '赞助链接待配置': 'Sponsor link not configured yet',
+ '加入官方 QQ 群': 'Join our QQ group',
+ '与开发者和其他用户交流': 'Chat with the developer and other users',
+ '群号已复制,打开 QQ 搜索加群':
+ 'Group number copied — open QQ and search to join',
+ // ---- 多主题 / 胶囊开关 ----
+ '深色模式': 'Dark mode',
+ '跟随系统': 'Follow system',
+ '主题配色': 'Theme color',
+ '开启后使用暗色界面': 'Use the dark interface',
+ '跟随系统开启时由系统决定,关闭后可手动切换':
+ 'Follows the system; turn off Follow system to set it manually',
+ '随系统的深色 / 浅色设置自动切换': 'Switch automatically with the system theme',
+ '切换全站强调色与界面色调': 'Change the accent color across the app',
+ 'ZL2 绿': 'ZL2 Green',
+ '海蓝': 'Ocean Blue',
+ '星紫': 'Violet',
+ '暖橙': 'Sunset Orange',
+ '樱粉': 'Sakura Pink',
+ // ---- 状态监控与通知 ----
+ '状态监控': 'Status monitoring',
+ '开启后定时检查服务器状态,并在变化时推送通知':
+ 'Periodically checks server status and pushes alerts on changes',
+ '每 {0}检查一次 · 最近 {1}': 'Every {0} · last check {1}',
+ '服务器离线提醒': 'Offline alerts',
+ '服务器掉线时推送系统通知':
+ 'Send a system notification when a server goes offline',
+ '服务器恢复提醒': 'Recovery alerts',
+ '服务器重新上线时推送通知':
+ 'Send a notification when a server comes back online',
+ '玩家上线提醒': 'Player join alerts',
+ '有新玩家进入服务器时推送通知':
+ 'Send a notification when a player joins a server',
+ '检查间隔': 'Check interval',
+ '间隔越短发现越快,对服务器的轮询压力也越大':
+ 'Shorter intervals detect changes faster but poll the server more',
+ '立即检查一次': 'Check now',
+ '正在检查…': 'Checking…',
+ '手动跑一轮检查,用来确认 RCON 配置是否可用':
+ 'Run one check manually to verify the RCON configuration',
+ '30 秒': '30 s',
+ '1 分钟': '1 min',
+ '2 分钟': '2 min',
+ '5 分钟': '5 min',
+ '尚未检查': 'not yet',
+ '检查完成:{0} 台服务器在线': 'Check complete: {0} server(s) online',
+ '未获得通知权限,提醒可能无法显示,请到系统设置中允许通知':
+ 'Notification permission was not granted; alerts may not appear',
+ '服务器离线': 'Server offline',
+ '服务器恢复': 'Server recovered',
+ '玩家上线': 'Player joined',
+ '「{0}」已离线,可能已停止运行': '"{0}" is offline and may have stopped',
+ '「{0}」已恢复在线': '"{0}" is back online',
+ '「{0}」:{1} 进入服务器': '"{0}": {1} joined the server',
};
static String t(String zh) => en ? (_en[zh] ?? zh) : zh;
diff --git a/lib/core/services/notification_service.dart b/lib/core/services/notification_service.dart
new file mode 100644
index 0000000..1e68653
--- /dev/null
+++ b/lib/core/services/notification_service.dart
@@ -0,0 +1,112 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+
+/// 系统通知服务:把服务器状态事件推送到 Android 通知栏。
+///
+/// 设计要点:
+/// - **绝不阻断主流程**:所有插件调用都包了 try/catch。Web 端、用户拒绝权限、
+/// 厂商 ROM 屏蔽通知时静默降级,只记一条 debugPrint,不让监控逻辑崩掉;
+/// - **单例**:监控服务与设置页共用同一个实例,避免重复注册通知通道;
+/// - **懒初始化**:只有真正要用时才初始化,不给冷启动增加负担
+/// (App 启动已经有一段 6 秒的加载兜底,不该再塞一个插件初始化进去)。
+class NotificationService {
+ NotificationService._();
+
+ static final NotificationService instance = NotificationService._();
+
+ /// 通知通道 id:Android 8+ 的通道一旦创建,重要性就只能由用户改,
+ /// 所以这里的 id 要保持永久稳定,换名字会让旧通道失效。
+ static const String _channelId = 'zv_server_monitor';
+ static const String _channelName = '服务器状态监控';
+ static const String _channelDesc = '服务器离线、恢复与玩家上线提醒';
+
+ final FlutterLocalNotificationsPlugin _plugin =
+ FlutterLocalNotificationsPlugin();
+
+ bool _initialized = false;
+ bool _permission = false;
+
+ /// 初始化成功且拿到通知权限,才认为可以真正弹通知。
+ bool get isReady => _initialized && _permission;
+
+ /// 初始化插件与通知通道。重复调用安全。
+ Future init() async {
+ if (kIsWeb || _initialized) return;
+ try {
+ // 图标必须指向 res/drawable 下的纯白剪影,见 ic_stat_monitor.xml
+ const settings = InitializationSettings(
+ android: AndroidInitializationSettings('ic_stat_monitor'),
+ );
+ await _plugin.initialize(settings);
+ _initialized = true;
+ } catch (e) {
+ debugPrint('通知服务初始化失败: $e');
+ }
+ }
+
+ /// 请求通知权限(Android 13+ 必须运行时授权;更低版本直接视为已授权)。
+ ///
+ /// 返回最终是否可用。授权被拒时不影响监控继续跑,只是不弹通知。
+ Future ensurePermission() async {
+ if (kIsWeb) return false;
+ await init();
+ if (!_initialized) return false;
+ if (_permission) return true;
+ try {
+ final android = _plugin.resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin>();
+ final granted = await android?.requestNotificationsPermission();
+ // 低版本系统该方法可能返回 null,此时按「已授权」处理
+ _permission = granted ?? true;
+ } catch (e) {
+ debugPrint('请求通知权限失败: $e');
+ _permission = false;
+ }
+ return _permission;
+ }
+
+ /// 静默检查「现在能不能发通知」:初始化插件 + 查询系统是否已允许,
+ /// **不会弹授权框**。用于 App 重启后恢复监控时判断,避免每次冷启动
+ /// 都拿系统权限弹窗打扰用户。
+ Future _ensureReady() async {
+ if (kIsWeb) return false;
+ await init();
+ if (!_initialized) return false;
+ if (_permission) return true;
+ try {
+ final android = _plugin.resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin>();
+ final enabled = await android?.areNotificationsEnabled();
+ _permission = enabled ?? true;
+ } catch (e) {
+ debugPrint('查询通知开关失败: $e');
+ _permission = false;
+ }
+ return _permission;
+ }
+
+ /// 弹一条通知。[id] 相同会覆盖上一条,调用方应使用递增 id。
+ Future show({
+ required int id,
+ required String title,
+ required String body,
+ }) async {
+ if (!await _ensureReady()) return;
+ final details = NotificationDetails(
+ android: AndroidNotificationDetails(
+ _channelId,
+ _channelName,
+ channelDescription: _channelDesc,
+ importance: Importance.high,
+ priority: Priority.high,
+ // 长文本(多个玩家同时上线)展开后能看全,而不是被截断
+ styleInformation: BigTextStyleInformation(body),
+ ),
+ );
+ try {
+ await _plugin.show(id, title, body, details);
+ } catch (e) {
+ debugPrint('发送通知失败: $e');
+ }
+ }
+}
diff --git a/lib/core/services/server_monitor_service.dart b/lib/core/services/server_monitor_service.dart
new file mode 100644
index 0000000..865444d
--- /dev/null
+++ b/lib/core/services/server_monitor_service.dart
@@ -0,0 +1,309 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+import '../../providers/rcon_provider.dart';
+import '../../providers/server_provider.dart';
+import '../l10n/strings.dart';
+import '../utils/rcon_client.dart';
+import 'notification_service.dart';
+
+/// 从 `list` 命令的返回里解析在线玩家名。
+///
+/// 只取最后一个冒号(兼容全角)之后的玩家段,再按逗号切分。
+/// 零人在线时服务端返回的玩家段为空,直接得到空列表。
+/// 解析不出的内容一律跳过,不抛异常 —— 监控是后台任务,不能因为
+/// 某个服务端改了输出格式就把整轮检查搞崩。
+List parseOnlinePlayerNames(String? info) {
+ if (info == null) return const [];
+ final cleaned = stripMinecraftCodes(info).trim();
+ final parts = cleaned.split(RegExp(r'[::]'));
+ if (parts.length < 2) return const [];
+ final section = parts.last.trim();
+ if (section.isEmpty) return const [];
+ return section
+ .split(RegExp(r'[,,]'))
+ .map((e) => e.trim())
+ .where((e) => e.isNotEmpty)
+ .toList();
+}
+
+/// 单台服务器的上一次观测快照。
+class _ServerSnapshot {
+ bool online;
+ Set players;
+
+ /// 最近一次弹通知的时间,用于抖动保护(避免网络抖动导致刷屏)。
+ DateTime? lastAlertAt;
+
+ _ServerSnapshot({
+ required this.online,
+ required this.players,
+ this.lastAlertAt,
+ });
+}
+
+/// 服务器状态监控:定时轮询所有已配置服务器,在状态变化时推送系统通知。
+///
+/// 监控规则(只对「状态变化」发通知,避免重复打扰):
+/// - 在线 → 离线:服务器离线提醒;
+/// - 离线 → 在线:服务器恢复提醒;
+/// - 在线且出现新玩家:玩家上线提醒(一次轮询内多人同时上线会合并成一条);
+/// - **首次观测只建立基线**,不发通知 —— 否则一开开关就会收到一串噪音。
+///
+/// 生命周期:由 App 层注册为 Provider,设置页开关控制启停。
+class ServerMonitorService extends ChangeNotifier {
+ ServerMonitorService({required this.servers, required this.rcon});
+
+ final ServerProvider servers;
+ final RconProvider rcon;
+
+ // ---------- 持久化 key(一旦发布就不要改名,否则老用户设置会丢) ----------
+ static const String _kEnabled = 'monitor_enabled';
+ static const String _kOffline = 'monitor_notify_offline';
+ static const String _kRecovered = 'monitor_notify_recovered';
+ static const String _kJoin = 'monitor_notify_join';
+ static const String _kInterval = 'monitor_interval_sec';
+
+ /// 可选轮询间隔(秒)。太短的间隔会给服务器 RCON 带来无谓压力。
+ static const List intervalOptions = [30, 60, 120, 300];
+
+ bool _enabled = false;
+ bool _notifyOffline = true;
+ bool _notifyRecovered = true;
+ bool _notifyJoin = true;
+ int _intervalSec = 60;
+
+ Timer? _timer;
+ bool _checking = false;
+ bool _disposed = false;
+ DateTime? _lastCheckAt;
+ int _onlineCount = 0;
+ int _notifySeq = 0;
+
+ final Map _snapshots = {};
+
+ bool get enabled => _enabled;
+ bool get notifyOffline => _notifyOffline;
+ bool get notifyRecovered => _notifyRecovered;
+ bool get notifyJoin => _notifyJoin;
+ int get intervalSec => _intervalSec;
+ bool get isChecking => _checking;
+ DateTime? get lastCheckAt => _lastCheckAt;
+
+ /// 最近一轮检查中被判定为在线的服务器数量。
+ int get onlineCount => _onlineCount;
+
+ /// 当前间隔的展示文案。
+ String get intervalLabel => labelForInterval(_intervalSec);
+
+ /// 把间隔秒数翻译成展示文案(设置页的选项弹层也用这一份,避免两处文案走偏)。
+ static String labelForInterval(int seconds) {
+ switch (seconds) {
+ case 30:
+ return S.t('30 秒');
+ case 120:
+ return S.t('2 分钟');
+ case 300:
+ return S.t('5 分钟');
+ default:
+ return S.t('1 分钟');
+ }
+ }
+
+ /// 从本地读取设置;若上次开启了监控则自动恢复运行。
+ Future load() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ _enabled = prefs.getBool(_kEnabled) ?? false;
+ _notifyOffline = prefs.getBool(_kOffline) ?? true;
+ _notifyRecovered = prefs.getBool(_kRecovered) ?? true;
+ _notifyJoin = prefs.getBool(_kJoin) ?? true;
+ final saved = prefs.getInt(_kInterval) ?? 60;
+ _intervalSec = intervalOptions.contains(saved) ? saved : 60;
+ } catch (e) {
+ debugPrint('读取监控设置失败: $e');
+ }
+ if (_enabled) _startTimer();
+ _notify();
+ }
+
+ Future setEnabled(bool value) async {
+ if (_enabled == value) return;
+ _enabled = value;
+ _notify();
+ await _persistBool(_kEnabled, value);
+ if (value) {
+ _startTimer();
+ // 开启后立刻检查一次,用户能马上看到效果,不用干等一个周期
+ await checkNow();
+ } else {
+ _timer?.cancel();
+ _timer = null;
+ // 关掉后清空快照:下次开启重新建立基线,避免拿旧状态误报离线
+ _snapshots.clear();
+ _onlineCount = 0;
+ _notify();
+ }
+ }
+
+ Future setNotifyOffline(bool value) async {
+ _notifyOffline = value;
+ _notify();
+ await _persistBool(_kOffline, value);
+ }
+
+ Future setNotifyRecovered(bool value) async {
+ _notifyRecovered = value;
+ _notify();
+ await _persistBool(_kRecovered, value);
+ }
+
+ Future setNotifyJoin(bool value) async {
+ _notifyJoin = value;
+ _notify();
+ await _persistBool(_kJoin, value);
+ }
+
+ Future setInterval(int seconds) async {
+ if (!intervalOptions.contains(seconds) || seconds == _intervalSec) return;
+ _intervalSec = seconds;
+ _notify();
+ await _persistInt(_kInterval, seconds);
+ if (_enabled) _startTimer();
+ }
+
+ void _startTimer() {
+ _timer?.cancel();
+ _timer = Timer.periodic(
+ Duration(seconds: _intervalSec),
+ (_) => checkNow(),
+ );
+ }
+
+ /// 立即执行一轮检查。
+ ///
+ /// 每台服务器单独 try/catch:一台超时不能影响其余服务器的检查。
+ Future checkNow() async {
+ if (_checking || _disposed) return;
+ _checking = true;
+ _notify();
+ try {
+ final list = servers.servers;
+ final seen = {};
+ var online = 0;
+ for (final server in list) {
+ if (_disposed) return;
+ seen.add(server.id);
+ try {
+ final status = await rcon.checkStatus(server);
+ if (status.online) online++;
+ await _evaluate(server, status);
+ } catch (e) {
+ debugPrint('检查服务器「${server.name}」失败: $e');
+ }
+ }
+ // 已删除的服务器不再保留快照,避免内存里堆积僵尸条目
+ _snapshots.removeWhere((id, _) => !seen.contains(id));
+ _onlineCount = online;
+ _lastCheckAt = DateTime.now();
+ } finally {
+ _checking = false;
+ _notify();
+ }
+ }
+
+ /// 对比上一轮快照,决定是否需要发通知。
+ Future _evaluate(ServerConfig server, ServerStatus status) async {
+ final players = status.online
+ ? parseOnlinePlayerNames(status.playerInfo).toSet()
+ : {};
+ final prev = _snapshots[server.id];
+
+ if (prev == null) {
+ // 首次观测:只记基线。否则刚开启监控就会收到「X 进入服务器」的假通知
+ _snapshots[server.id] = _ServerSnapshot(
+ online: status.online,
+ players: players,
+ );
+ return;
+ }
+
+ final now = DateTime.now();
+ final canAlert = prev.lastAlertAt == null ||
+ now.difference(prev.lastAlertAt!) >= const Duration(minutes: 2);
+
+ if (prev.online && !status.online) {
+ if (_notifyOffline && canAlert) {
+ await _send(
+ title: S.t('服务器离线'),
+ body: S.f('「{0}」已离线,可能已停止运行',