From 854f00038c8e200ef33ad34a1b0ac22c43da9585 Mon Sep 17 00:00:00 2001 From: ZV Team Date: Tue, 27 Oct 2026 20:46:03 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E4=B8=BA=E6=A0=B8=E5=BF=83=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E5=B1=82=E3=80=81=E6=9C=8D=E5=8A=A1=E5=B1=82=E4=B8=8E?= =?UTF-8?q?=E4=B8=BB=E8=A6=81=E9=A1=B5=E9=9D=A2=E8=A1=A5=E5=85=85=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=B3=A8=E9=87=8A=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=B8=8B?= =?UTF-8?q?=E8=BD=BD=E8=BF=9B=E5=BA=A6=E8=AE=A1=E7=AE=97=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/core/services/download_manager.dart | 42 ++++++++++------ lib/core/services/jar_metadata.dart | 7 ++- lib/core/services/mirror_service.dart | 13 +++-- lib/core/services/modrinth_api.dart | 23 +++++++++ lib/core/services/sftp_service.dart | 14 ++++++ lib/core/services/ssh_shell_service.dart | 10 +++- lib/core/utils/rcon_client.dart | 49 ++++++++++++++++++- lib/core/utils/rcon_stream_parser.dart | 28 +++++++++++ lib/data/services/secure_storage_service.dart | 12 +++++ lib/features/console/console_page.dart | 37 +++++++++++--- lib/providers/language_provider.dart | 5 ++ lib/providers/server_provider.dart | 16 ++++++ lib/providers/theme_provider.dart | 5 ++ lib/providers/wallpaper_provider.dart | 11 +++++ 14 files changed, 244 insertions(+), 28 deletions(-) diff --git a/lib/core/services/download_manager.dart b/lib/core/services/download_manager.dart index 3bc2d94..bbb8db4 100644 --- a/lib/core/services/download_manager.dart +++ b/lib/core/services/download_manager.dart @@ -9,15 +9,25 @@ import '../../core/l10n/strings.dart'; enum DownloadStatus { queued, running, paused, completed, failed, canceled } /// 单个下载任务。 +/// +/// 进度语义:进度以 `.part` 临时文件为基础, +/// [receivedBytes] 始终表示"该文件已落盘的字节数"(含续传前已存在的部分), +/// [totalBytes] 表示文件完整大小(未知时为 0)。 class DownloadTask { final String id; - final String url; // 直链(已镜像改写) + + /// 直链(已按当前镜像线路改写) + final String url; final String fileName; final String savePath; - final String? sftpRemoteDir; // 完成后自动上传到服务器的目录(需 SSH) + + /// 完成后自动上传到服务器的目录(需 SSH;为空则不上传) + final String? sftpRemoteDir; int totalBytes; int receivedBytes = 0; - double speed = 0; // bytes/s + + /// 实时速度,单位 bytes/s,由 500ms 采样窗口计算 + double speed = 0; DownloadStatus status = DownloadStatus.queued; String? error; @@ -175,7 +185,7 @@ class DownloadManager extends ChangeNotifier { var lastTick = DateTime.now(); var lastBytes = existing; - final resp = await _dio.download( + await _dio.download( task.url, '${task.savePath}.part', cancelToken: token, @@ -188,13 +198,20 @@ class DownloadManager extends ChangeNotifier { ), onReceiveProgress: (count, total) { task.receivedBytes = existing + count; - // 服务端可能不支持 Range:206 才是续传,200 时 total 为完整大小 - task.totalBytes = existing > 0 && total == task.receivedBytes - ? total - : (total > 0 ? total + (total == count ? 0 : 0) : total); - if (existing > 0 && total > 0 && task.totalBytes <= existing) { - task.totalBytes = existing + total; + // 断点续传时 dio 的 total 只统计「本次请求」的剩余字节, + // 因此需加上已有的 existing;不支持 Range 时服务端返回 200, + // 此时 total 已是完整文件大小,直接用即可。 + if (total > 0) { + task.totalBytes = existing > 0 && count <= total + ? existing + total + : total; } + // 兜底:若推算出的总量反而小于已收字节,说明服务端行为异常, + // 直接把已收量当作总量,避免进度条超过 100%。 + if (task.totalBytes > 0 && task.totalBytes < task.receivedBytes) { + task.totalBytes = task.receivedBytes; + } + // 节流:每 500ms 采样一次速度并刷新 UI,避免高频 notify 卡顿 final now = DateTime.now(); final dt = now.difference(lastTick).inMilliseconds; if (dt >= 500) { @@ -205,10 +222,7 @@ class DownloadManager extends ChangeNotifier { } }, ); - // 200 响应(非续传)时重置已收字节 - if (resp.statusCode == 200 && existing > 0 && task.receivedBytes < existing) { - task.receivedBytes = task.receivedBytes; - } + // 全部下载完成后把 .part 改名为正式文件(原子操作,避免半成品被当成完整文件) task.totalBytes = task.receivedBytes; await partial.rename(task.savePath); _updateStatus(task.id, DownloadStatus.completed); diff --git a/lib/core/services/jar_metadata.dart b/lib/core/services/jar_metadata.dart index 95c0a72..c145782 100644 --- a/lib/core/services/jar_metadata.dart +++ b/lib/core/services/jar_metadata.dart @@ -41,11 +41,14 @@ class JarMetadata { static JarMetadata parseArchive(Archive archive) => _fromArchive(archive); static JarMetadata _fromArchive(Archive archive) { + // 按加载器优先级依次尝试:先认 mod 描述文件,再退回插件描述文件, + // 最后尝试 Forge 的 toml。任何一步成功即返回,不再往下找。 // 1) Fabric / Quilt:fabric.mod.json for (final entry in ['fabric.mod.json', 'quilt.mod.json']) { final f = archive.findFile(entry); if (f != null) { final json = jsonDecode(utf8.decode(f.content as List)); + // Quilt 把真实信息放在 quilt_loader 下,Fabric 则直接在根上 final loader = json['quilt_loader']; final root = loader ?? json; final meta = root['metadata'] ?? {}; @@ -78,18 +81,20 @@ class JarMetadata { } } - // 3) Forge:META-INF/mods.toml / mcmod.info + // 3) Forge:META-INF/mods.toml / mcmod.info for (final entry in ['META-INF/mods.toml', 'mcmod.info']) { final f = archive.findFile(entry); if (f != null) { final text = utf8.decode(f.content as List); if (entry.endsWith('.toml')) { + // toml 无现成解析库,用正则抓关键字段即可满足展示需求 final name = RegExp(r'''^\s*displayName\s*=\s*["']([^"']+)''', multiLine: true).firstMatch(text)?.group(1); final ver = RegExp(r'''^\s*version\s*=\s*["']([^"']+)''', multiLine: true).firstMatch(text)?.group(1); final deps = RegExp(r'''^\s*modId\s*=\s*["']([^"']+)''', multiLine: true) .allMatches(text) .map((m) => m.group(1)!) .toList(); + // 第一个 modId 通常是模组自己,依赖从第二个开始 return JarMetadata(name: name, version: ver, depends: deps.skip(1).toList(), source: entry); } final json = jsonDecode(text); diff --git a/lib/core/services/mirror_service.dart b/lib/core/services/mirror_service.dart index 9daf0f8..9cfa58d 100644 --- a/lib/core/services/mirror_service.dart +++ b/lib/core/services/mirror_service.dart @@ -41,9 +41,13 @@ class MirrorService extends ChangeNotifier { notifyListeners(); } - /// 把 Modrinth 官方域名改写为镜像域名。 - /// MCIM 镜像规则:api.modrinth.com → modrinth-api.mcimirror.top - /// cdn.modrinth.com → modrinth-cdn.mcimirror.top +/// 把 Modrinth 官方域名改写为镜像域名。 + /// + /// 镜像规则: + /// - MCIM:api.modrinth.com → modrinth-api.mcimirror.top + /// cdn.modrinth.com → modrinth-cdn.mcimirror.top + /// - official:原样返回 + /// - custom:以自定义 base 替换 scheme/host,保留路径与查询串 String rewrite(String url) { final uri = Uri.parse(url); if (_current == 'official') return url; @@ -68,6 +72,9 @@ class MirrorService extends ChangeNotifier { } /// 测速:对镜像的 api 域名发 HEAD 请求,返回毫秒数;失败返回 -1。 + /// + /// 用 sodium(高下载量项目)作为探针,保证端点有效且有缓存命中, + /// 测得的是"网络往返 + 响应"的真实可用性。 Future speedTest(String mirrorId) async { final String probe = switch (mirrorId) { 'official' => 'https://api.modrinth.com/v2/project/sodium/version?limit=1', diff --git a/lib/core/services/modrinth_api.dart b/lib/core/services/modrinth_api.dart index 1d86d9a..7227c58 100644 --- a/lib/core/services/modrinth_api.dart +++ b/lib/core/services/modrinth_api.dart @@ -9,6 +9,7 @@ class ModrinthApi { Dio get _dio { final d = Dio(BaseOptions( + // 镜像线路偶尔抖动,给足超时时间,避免用户看到莫名失败 connectTimeout: const Duration(seconds: 15), receiveTimeout: const Duration(seconds: 30), )); @@ -16,6 +17,7 @@ class ModrinthApi { onRequest: (options, handler) { // 镜像改写:api.modrinth.com / cdn.modrinth.com → 镜像节点 options.path = mirror.rewrite(options.uri.toString()); + // Modrinth 要求标明客户端身份,否则可能被限流 options.headers['User-Agent'] = 'ZVManager/2.0 (gitee.com/driftinblock/zvmanager)'; handler.next(options); }, @@ -24,6 +26,9 @@ class ModrinthApi { } /// 搜索项目。facets 例:[["versions:1.20.1"], ["categories:fabric"], ["project_type:mod"]] + /// + /// Modrinth 的 facets 是「AND 组合、组内 OR」的结构, + /// 因此项目类型/版本/加载器各占一组即可实现"三者同时满足"的筛选。 Future> search({ required String query, String projectType = 'mod', @@ -60,13 +65,19 @@ class ModrinthApi { } } +/// 在项目搜索中会出现多页结果,这里仅取 limit 条(分页由上层滚动加载扩展)。 class ModrinthSearchResult { + /// 项目短名,可用于拼 URL(如 /mod/sodium) final String slug; final String title; final String description; final List categories; final int downloads; + + /// 项目图标,部分项目无图标返回 null final String? iconUrl; + + /// 项目唯一 id,查版本时用 final String projectId; ModrinthSearchResult({ @@ -90,14 +101,26 @@ class ModrinthSearchResult { ); } +/// Modrinth 的一个发布版本。 class ModrinthVersion { final String id; + + /// 版本号(如 0.5.11) final String versionNumber; + + /// 版本展示名(通常是版本号 + 说明) final String name; + + /// 兼容的 MC 版本列表(如 ['1.20.1', '1.20.2']) final List gameVersions; + + /// 兼容的加载器(fabric / forge / neoforge / quilt) final List loaders; + final DateTime datePublished; final String? changelog; + + /// 文件列表,每项含 url / filename / primary 等字段 final List> files; ModrinthVersion({ diff --git a/lib/core/services/sftp_service.dart b/lib/core/services/sftp_service.dart index 10368c0..92f1265 100644 --- a/lib/core/services/sftp_service.dart +++ b/lib/core/services/sftp_service.dart @@ -11,11 +11,15 @@ import '../../core/l10n/strings.dart'; class SftpService { SSHClient? _client; SftpClient? _sftp; + + /// 当前连接绑定的服务器,用于判断能否复用已有连接 ServerConfig? _bound; bool get isConnected => _client != null && !_client!.isClosed; /// 连接到指定服务器的 SSH。失败抛异常。 + /// + /// 如果已经连到同一台服务器则直接复用,避免重复握手(SSH 握手较慢)。 Future connect(ServerConfig server) async { if (isConnected && _bound?.id == server.id) return; await disconnect(); @@ -27,6 +31,7 @@ class SftpService { _client = SSHClient( socket, username: server.sshUser, + // 目前仅支持密码认证;密钥认证需在设置里扩展 onPasswordRequest: () => server.sshPassword, ); _sftp = await _client!.sftp(); @@ -39,6 +44,9 @@ class SftpService { } /// 上传本地文件到远程路径。 + /// + /// 采用 create + truncate 模式覆盖写入;流式读取本地文件, + /// 大文件不会一次性读进内存。 Future upload(String localPath, String remotePath) async { final sftp = _requireSftp(); final file = await sftp.open( @@ -60,6 +68,8 @@ class SftpService { } /// 下载远程文件到本地路径。 + /// + /// [onProgress] 参数为 (已下载字节, 总字节);总字节未知时为 0。 Future download( String remotePath, String localPath, { @@ -85,6 +95,10 @@ class SftpService { } /// 读取远程文件文本内容(保留末尾 maxBytes 字节,适合大日志文件)。 + /// + /// 服务器日志动辄上百 MB,全量读取会撑爆内存且价值不大, + /// 因此超限时只保留尾部——排查崩溃时真正关心的是最后那段堆栈。 + /// 截断位置会向前对齐到 UTF-8 字符边界,避免出现乱码。 Future readString( String remotePath, { int maxBytes = 2 * 1024 * 1024, diff --git a/lib/core/services/ssh_shell_service.dart b/lib/core/services/ssh_shell_service.dart index 9f5243f..1cb50f5 100644 --- a/lib/core/services/ssh_shell_service.dart +++ b/lib/core/services/ssh_shell_service.dart @@ -14,6 +14,9 @@ class SshShellService { bool get isConnected => _client != null && !_client!.isClosed; /// 建立 PTY 会话。输出通过 [onOutput] 回调(UTF-8 解码后)。 + /// + /// - [keepAliveInterval]:15 秒发一次 keepalive,防止移动网络 NAT 超时踢掉空闲连接; + /// - PTY 类型固定 xterm-256color,让服务端程序输出彩色与全屏界面(如 htop)。 Future connect( ServerConfig server, { required void Function(String) onOutput, @@ -40,6 +43,7 @@ class SshShellService { ); _session = shell; + // stdout 正常输出;连接结束(onDone)时触发自动重连 shell.stdout.listen( (data) => onOutput(utf8.decode(data, allowMalformed: true)), onDone: () { @@ -48,9 +52,11 @@ class SshShellService { }, onError: (_) => onDisconnected?.call(), ); + // stderr 与 stdout 合并到同一个终端缓冲区,符合真实终端表现 shell.stderr.listen((data) => onOutput(utf8.decode(data, allowMalformed: true))); } + /// 自动重连:最多 3 次,间隔 2s → 4s → 6s 递增。 Future _tryReconnect( ServerConfig server, { required void Function(String) onOutput, @@ -67,11 +73,11 @@ class SshShellService { } } - /// 写入用户输入。 + /// 写入用户输入(按键、粘贴内容)。 void write(String input) => _session?.write(Uint8List.fromList(utf8.encode(input))); - /// 终端窗口尺寸变化。 + /// 终端窗口尺寸变化(软键盘弹出、横竖屏切换时调用)。 void resize(int cols, int rows) => _session?.resizeTerminal(cols, rows); Future disconnect() async { diff --git a/lib/core/utils/rcon_client.dart b/lib/core/utils/rcon_client.dart index b915512..9684a2c 100644 --- a/lib/core/utils/rcon_client.dart +++ b/lib/core/utils/rcon_client.dart @@ -8,25 +8,49 @@ import 'rcon_stream_parser.dart'; import '../../core/l10n/strings.dart'; /// 去除 Minecraft 消息中的颜色/格式码(§ 后跟一个有效字符)。 +/// +/// 服务端命令回显常带 `§a`(绿)、`§l`(加粗)等格式符, +/// 直接显示在 Flutter 文本里会变成乱码方块,这里统一剥掉。 String stripMinecraftCodes(String input) { return input.replaceAll(RegExp(r'\u00a7[0-9A-Fa-fK-ORk-or]'), ''); } +/// RCON 客户端:与 Minecraft 服务端建立长连接,发送控制台命令。 +/// +/// 生命周期: +/// ``` +/// connect() → executeCommand(...) × N → disconnect() +/// ↑______ 心跳失败自动重连 ______| +/// ``` +/// +/// 关键设计: +/// - **请求配对**:每条命令分配自增 id,响应按 id 找回对应的 Completer; +/// - **心跳保活**:每 30 秒发一次 `list`,失败即判定掉线; +/// - **指数退避重连**:1s → 2s → 4s … 封顶 60s,最多 10 次。 class RconClient { Socket? _socket; + + /// 请求 id 自增计数器,用于把响应和请求配对 int _requestId = 0; + bool _isAuthenticated = false; + + /// 在途请求表:id → 等待响应的 Completer final Map> _pendingRequests = {}; Timer? _heartbeatTimer; Timer? _reconnectTimer; int _reconnectAttempts = 0; static const _maxReconnectAttempts = 10; + + /// 心跳间隔:太短会给服务端造成无谓负担,太长则掉线发现不及时 static const _heartbeatInterval = Duration(seconds: 30); + /// 连接断开 / 重连成功的外部回调,供 UI 层更新状态 VoidCallback? onDisconnected; VoidCallback? onReconnected; + // 缓存连接参数,用于自动重连 String? _host; int? _port; String? _password; @@ -34,6 +58,9 @@ class RconClient { bool get isConnected => _isAuthenticated && _socket != null; + /// 建立 TCP 连接并完成 RCON 认证。 + /// + /// 返回 true 表示认证成功;抛异常表示网络层连不上。 Future connect( String host, int port, @@ -46,18 +73,22 @@ class RconClient { _autoReconnect = autoReconnect; try { + // 5 秒超时:避免弱网下界面长时间卡在加载态 _socket = await Socket.connect( host, port, timeout: const Duration(seconds: 5), ); + // 绑定解析器:收到完整包后,按 id 唤醒等待中的请求 _socket!.transform(RconStreamParser()).listen((parsed) { final completer = _pendingRequests.remove(parsed.id); completer?.complete(parsed); }); + // type=3 为认证包,payload 即密码(明文,故 RCON 必须走内网或 SSH 隧道) final authResponse = await _sendPacket(3, password); + // 认证失败时服务端返回 id = -1,这是协议层的约定 _isAuthenticated = authResponse != null && authResponse.id != -1; if (_isAuthenticated) { @@ -71,14 +102,17 @@ class RconClient { } } + /// 执行一条控制台命令,返回服务端原文(可能为 null 表示超时)。 Future executeCommand(String command) async { if (!_isAuthenticated || _socket == null) { throw Exception(S.t('RCON 未连接或未认证')); } + // type=2 为命令包 final response = await _sendPacket(2, command); return response?.payload; } + /// 主动断开:取消定时器、销毁 socket、清空认证状态。 void disconnect() { _heartbeatTimer?.cancel(); _reconnectTimer?.cancel(); @@ -88,6 +122,7 @@ class RconClient { _isAuthenticated = false; } + /// 启动心跳:周期性发 `list`(最轻量的命令),失败即视为掉线。 void _startHeartbeat() { _heartbeatTimer?.cancel(); _heartbeatTimer = Timer.periodic(_heartbeatInterval, (_) async { @@ -99,6 +134,7 @@ class RconClient { }); } + /// 掉线处理:通知 UI,并按指数退避安排重连。 void _handleDisconnect() { _heartbeatTimer?.cancel(); onDisconnected?.call(); @@ -106,6 +142,7 @@ class RconClient { if (!_autoReconnect || _reconnectAttempts >= _maxReconnectAttempts) return; _reconnectAttempts++; + // 指数退避:2^(n-1) 秒,最长 60 秒;避免服务端刚崩溃时被反复重连打爆 final delay = Duration( seconds: min(60, pow(2, _reconnectAttempts - 1).toInt()), ); @@ -123,14 +160,17 @@ class RconClient { }); } + /// 发送一个包并等待对应 id 的响应(5 秒超时)。 + /// + /// 超时说明连接已不可用,直接销毁连接,由调用方或重连机制重建。 Future _sendPacket(int type, String payload) async { final id = ++_requestId; final packet = _buildPacket(id, type, payload); final completer = Completer(); - + _pendingRequests[id] = completer; _socket!.add(packet); - + return completer.future.timeout( const Duration(seconds: 5), onTimeout: () { @@ -142,6 +182,10 @@ class RconClient { ); } + /// 按协议拼装二进制包(小端序)。 + /// + /// 结构:length | id | type | payload | 0x00 0x00 + /// 其中 length = 4(id) + 4(type) + payload 长度 + 2(结束符)。 Uint8List _buildPacket(int id, int type, String payload) { final payloadBytes = utf8.encode(payload); final length = 4 + 4 + payloadBytes.length + 2; @@ -160,6 +204,7 @@ class RconClient { buffer.add(typeData.buffer.asUint8List()); buffer.add(payloadBytes); + // 协议要求以两个 0x00 结尾 buffer.add([0, 0]); return buffer.toBytes(); diff --git a/lib/core/utils/rcon_stream_parser.dart b/lib/core/utils/rcon_stream_parser.dart index 1351646..539ff13 100644 --- a/lib/core/utils/rcon_stream_parser.dart +++ b/lib/core/utils/rcon_stream_parser.dart @@ -2,10 +2,24 @@ import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; +/// 一条已解析的 RCON 数据包。 +/// +/// RCON 协议(Source RCON)线上格式为小端序: +/// ``` +/// [4B 包长 length][4B 请求 id][4B 包类型 type][payload...][2B 结束符 0x00 0x00] +/// ``` +/// 其中 `length` 只统计其后的部分(id + type + payload + 2 字节结束符)。 class RconPacket { + /// 包体长度(不含开头的 4 字节自身) final int length; + + /// 请求 id,用于把响应与请求配对;认证失败时服务器返回 -1 final int id; + + /// 包类型:2=执行命令,3=认证,0=响应 final int type; + + /// 解码后的正文(已剔除末尾结束符) final String payload; RconPacket({ @@ -16,6 +30,14 @@ class RconPacket { }); } +/// 把 TCP 的字节流切分成一条条 [RconPacket]。 +/// +/// TCP 是流式协议,一次 `data` 事件可能带来半个包,也可能带来多个包, +/// 因此这里维护一个 [BytesBuilder] 缓冲区: +/// 1. 新数据追加到缓冲区; +/// 2. 循环从头部读 4 字节长度 → 判断缓冲区是否够一整包; +/// 3. 不够就 `break` 等下一次数据;够就切出来解析,继续下一个; +/// 4. 剩余未消费的尾巴放回缓冲区。 class RconStreamParser extends StreamTransformerBase { @override Stream bind(Stream stream) async* { @@ -25,21 +47,26 @@ class RconStreamParser extends StreamTransformerBase { buffer.add(chunk); var bytes = buffer.toBytes(); + // 至少要有 4 字节才能读出包长 while (bytes.length >= 4) { final byteData = ByteData.sublistView(bytes); final packetLength = byteData.getInt32(0, Endian.little); + // 整包长度 = 长度字段自身的 4 字节 + 包体长度 final totalSize = 4 + packetLength; + // 半包:等更多数据到达 if (bytes.length < totalSize) break; final packetBytes = bytes.sublist(4, totalSize); final packetData = ByteData.sublistView(packetBytes); + // 最小合法包体为 10 字节(id 4 + type 4 + 结束符 2) if (packetBytes.length >= 10) { yield RconPacket( length: packetLength, id: packetData.getInt32(0, Endian.little), type: packetData.getInt32(4, Endian.little), + // 去掉末尾 2 字节结束符;allowMalformed 防止服务端发来非 UTF-8 时整条流崩溃 payload: utf8.decode( packetBytes.sublist(8, packetBytes.length - 2), allowMalformed: true, @@ -50,6 +77,7 @@ class RconStreamParser extends StreamTransformerBase { bytes = bytes.sublist(totalSize); } + // 用剩余未消费的字节重建缓冲区 buffer.clear(); if (bytes.isNotEmpty) buffer.add(bytes); } diff --git a/lib/data/services/secure_storage_service.dart b/lib/data/services/secure_storage_service.dart index 54ed25d..f8a68d8 100644 --- a/lib/data/services/secure_storage_service.dart +++ b/lib/data/services/secure_storage_service.dart @@ -4,17 +4,27 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../providers/server_provider.dart'; +/// 服务器配置的加密持久化。 +/// +/// 服务器配置里含 RCON 密码和 SSH 密码,属于敏感信息, +/// 因此走 [FlutterSecureStorage](Android Keystore / iOS Keychain), +/// 而不是普通的 SharedPreferences 明文存储。 class SecureStorageService { + /// 当前使用的加密存储 key static const _key = 'mc_servers_encrypted'; + + /// 旧版本明文存储 key(迁移用,读取一次后即删除) static const _legacyKey = 'mc_servers'; static const _storage = FlutterSecureStorage( aOptions: AndroidOptions(), iOptions: IOSOptions( + // first_unlock_this_device:开机首次解锁后可读,且不随 iCloud 备份迁移到其他设备 accessibility: KeychainAccessibility.first_unlock_this_device, ), ); + /// 读取服务器列表,必要时把旧版明文数据迁移到加密存储。 static Future> loadServers() async { final encrypted = await _storage.read(key: _key); if (encrypted != null) { @@ -29,6 +39,7 @@ class SecureStorageService { } } + // 迁移路径:v1 用 SharedPreferences 明文存储,读到后转存加密存储并清理旧数据 final prefs = await SharedPreferences.getInstance(); final legacy = prefs.getString(_legacyKey); if (legacy != null) { @@ -42,6 +53,7 @@ class SecureStorageService { return []; } + /// 覆盖写入全部服务器配置(列表整体序列化,非增量更新)。 static Future saveServers(List servers) async { final encoded = jsonEncode(servers.map((s) => s.toJson()).toList()); await _storage.write(key: _key, value: encoded); diff --git a/lib/features/console/console_page.dart b/lib/features/console/console_page.dart index d0ef9bc..d2757f1 100644 --- a/lib/features/console/console_page.dart +++ b/lib/features/console/console_page.dart @@ -4,6 +4,10 @@ import '../../core/utils/command_preset_service.dart'; import '../../core/utils/rcon_client.dart'; import '../../core/l10n/strings.dart'; +/// 控制台页:命令输入 + 输出回显 + 命令历史 + Tab 补全 + 快捷指令。 +/// +/// 输出只保存在内存里(最多 [_maxLines] 行),退出页面即清空—— +/// 真正的持久化日志请看「设置 → 服务器日志」(读服务器 logs 目录)。 class ConsolePage extends StatefulWidget { final RconClient rconClient; const ConsolePage({super.key, required this.rconClient}); @@ -15,11 +19,19 @@ class ConsolePage extends StatefulWidget { class _ConsolePageState extends State { final _controller = TextEditingController(); final _scrollController = ScrollController(); + + /// 已执行过的命令,供上下键翻阅 final _history = []; + + /// 当前浏览到的历史位置;等于 length 表示"正在输入新命令" int _historyIndex = -1; final _outputLines = <_LogLine>[]; + + /// 输出行数上限,防止长时间运行后内存无限增长 + static const _maxLines = 500; List _presets = []; + /// Tab 补全候选:常用服务端命令 static const _commands = [ 'help', 'list', 'stop', 'say', 'op', 'deop', 'kick', 'ban', 'pardon', 'gamemode', 'tp', 'give', 'time set', 'weather', 'difficulty', @@ -28,14 +40,15 @@ class _ConsolePageState extends State { @override void initState() { super.initState(); + // 连接状态变化直接写入输出区,用户能看到断线与恢复的时间点 widget.rconClient.onDisconnected = () { if (mounted) { - setState(() => _outputLines.add(_LogLine(text: S.t('[警告] 连接断开,正在重连...'), isError: true))); + setState(() => _append(_LogLine(text: S.t('[警告] 连接断开,正在重连...'), isError: true))); } }; widget.rconClient.onReconnected = () { if (mounted) { - setState(() => _outputLines.add(_LogLine(text: S.t('[信息] 重连成功'), isCommand: false))); + setState(() => _append(_LogLine(text: S.t('[信息] 重连成功'), isCommand: false))); } }; _loadPresets(); @@ -53,6 +66,14 @@ class _ConsolePageState extends State { super.dispose(); } + /// 追加一行输出,超过上限时丢弃最早的行。 + void _append(_LogLine line) { + _outputLines.add(line); + if (_outputLines.length > _maxLines) { + _outputLines.removeRange(0, _outputLines.length - _maxLines); + } + } + void _scrollToBottom() { WidgetsBinding.instance.addPostFrameCallback((_) { if (_scrollController.hasClients) { @@ -73,31 +94,33 @@ class _ConsolePageState extends State { } Future _sendCommand(String cmd) async { + // 去重:连续执行同一条命令时不重复记入历史 if (_history.isEmpty || _history.last != cmd) _history.add(cmd); _historyIndex = _history.length; setState(() { - _outputLines.add(_LogLine(text: '> $cmd', isCommand: true)); + _append(_LogLine(text: '> $cmd', isCommand: true)); }); _scrollToBottom(); try { final response = await widget.rconClient.executeCommand(cmd); setState(() { - _outputLines.add(_LogLine( + _append(_LogLine( text: stripMinecraftCodes(response ?? S.t('(无响应)')), isCommand: false, )); }); } catch (e) { setState(() { - _outputLines.add(_LogLine(text: S.f('[错误] {0}', [e.toString()]), isCommand: false, isError: true)); + _append(_LogLine(text: S.f('[错误] {0}', [e.toString()]), isCommand: false, isError: true)); }); } _scrollToBottom(); } void _onTabPressed() { + // 简单的前缀补全:只有唯一匹配时直接补全,多个匹配则列出候选 final input = _controller.text.trim(); if (input.isEmpty) return; @@ -107,12 +130,14 @@ class _ConsolePageState extends State { _controller.selection = TextSelection.fromPosition(TextPosition(offset: matches.first.length)); } else if (matches.length > 1) { setState(() { - _outputLines.add(_LogLine(text: S.f('建议:{0}', [matches.join(", ")]), isCommand: false)); + _append(_LogLine(text: S.f('建议:{0}', [matches.join(", ")]), isCommand: false)); }); _scrollToBottom(); } } + /// 上下键翻阅历史:up 往更早的命令走,down 往更新的走; + /// 走到最新位置之后即为空白(相当于"取消翻阅")。 void _onHistoryNavigate(bool up) { if (_history.isEmpty) return; setState(() { diff --git a/lib/providers/language_provider.dart b/lib/providers/language_provider.dart index 9c94344..8c2f13d 100644 --- a/lib/providers/language_provider.dart +++ b/lib/providers/language_provider.dart @@ -4,6 +4,9 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../core/l10n/strings.dart'; /// 应用语言设置:跟随系统 / 简体中文 / English,持久化保存。 +/// +/// 切换语言时同步更新全局开关 [S.en],这样非 Widget 场景 +/// (如 Service 里抛出的错误文案)也能取到正确的翻译。 class LanguageProvider extends ChangeNotifier { static const _key = 'app_language'; LanguageMode _mode = LanguageMode.system; @@ -20,6 +23,8 @@ class LanguageProvider extends ChangeNotifier { /// 当前是否英文(用于硬编码 UI 文案的双语切换)。 bool get isEnglish => _mode == LanguageMode.en; + /// 启动时恢复语言设置;注意这里不 notifyListeners, + /// 因为通常在 runApp 之前调用,避免无意义的重建。 Future load() async { final prefs = await SharedPreferences.getInstance(); final v = prefs.getString(_key); diff --git a/lib/providers/server_provider.dart b/lib/providers/server_provider.dart index eb751c6..b8d6672 100644 --- a/lib/providers/server_provider.dart +++ b/lib/providers/server_provider.dart @@ -1,6 +1,13 @@ import 'package:flutter/foundation.dart'; import '../data/services/secure_storage_service.dart'; +/// 一台 Minecraft 服务器的连接配置。 +/// +/// 包含两组凭据: +/// - **RCON**(host / port / password):控制台命令、玩家管理; +/// - **SSH**(ssh* 字段):SFTP 文件操作、终端、日志。 +/// +/// 两组凭据相互独立,只填 RCON 也能正常使用控制台与玩家功能。 class ServerConfig { final String id; final String name; @@ -41,6 +48,7 @@ class ServerConfig { 'sshPassword': sshPassword, }; + /// 从旧版本存档反序列化时,SSH 字段可能不存在,全部给默认值以兼容升级。 factory ServerConfig.fromJson(Map json) => ServerConfig( id: json['id'], name: json['name'], @@ -54,8 +62,14 @@ class ServerConfig { ); } +/// 服务器列表状态:增删改查 + 持久化。 +/// +/// 所有写操作都会立即落盘([SecureStorageService]), +/// 保证进程被杀后配置不丢。 class ServerProvider extends ChangeNotifier { List _servers = []; + + /// 对外暴露不可变视图,防止 UI 层直接修改内部列表导致状态不同步。 List get servers => List.unmodifiable(_servers); Future loadServers() async { @@ -69,6 +83,7 @@ class ServerProvider extends ChangeNotifier { notifyListeners(); } + /// 按 id 匹配替换(id 由创建时生成,编辑不改变 id)。 Future updateServer(ServerConfig server) async { final index = _servers.indexWhere((s) => s.id == server.id); if (index != -1) _servers[index] = server; @@ -82,6 +97,7 @@ class ServerProvider extends ChangeNotifier { notifyListeners(); } + /// 按 id 查找;找不到(如服务器已被删除)返回 null。 ServerConfig? byId(String? id) { if (id == null) return null; try { diff --git a/lib/providers/theme_provider.dart b/lib/providers/theme_provider.dart index 698dd3f..6f43cbb 100644 --- a/lib/providers/theme_provider.dart +++ b/lib/providers/theme_provider.dart @@ -2,14 +2,18 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../core/theme/app_theme.dart'; +/// 主题模式状态:亮色 / 暗色 / 跟随系统,选择结果持久化到本地。 class ThemeProvider extends ChangeNotifier { static const _key = 'app_theme_mode'; AppThemeMode _themeMode = AppThemeMode.system; AppThemeMode get themeMode => _themeMode; + /// 转成 MaterialApp 需要的 ThemeMode ThemeMode get flutterThemeMode => AppTheme.toFlutterThemeMode(_themeMode); + /// 启动时读取上次保存的主题模式。 + /// 读不到或值非法(如版本升级后枚举重命名)时回退到「跟随系统」。 Future loadThemeMode() async { final prefs = await SharedPreferences.getInstance(); final value = prefs.getString(_key); @@ -22,6 +26,7 @@ class ThemeProvider extends ChangeNotifier { } } + /// 切换主题模式:先刷新 UI 再异步落盘,避免点击后有明显延迟感。 Future setThemeMode(AppThemeMode mode) async { if (_themeMode != mode) { _themeMode = mode; diff --git a/lib/providers/wallpaper_provider.dart b/lib/providers/wallpaper_provider.dart index e7d48e9..0fbba49 100644 --- a/lib/providers/wallpaper_provider.dart +++ b/lib/providers/wallpaper_provider.dart @@ -1,8 +1,14 @@ import 'package:flutter/material.dart'; import '../core/utils/background_service.dart'; +/// 自定义背景(壁纸)状态。 +/// +/// 壁纸由原生侧(MethodChannel)负责读写,这里只做内存缓存 + 通知刷新, +/// 避免每次 build 都跨平台调用。 class WallpaperProvider extends ChangeNotifier { String? _wallpaperPath; + + /// 壁纸类型:'image' / 'video'(视频壁纸由原生层渲染) String? _wallpaperType; String? get wallpaperPath => _wallpaperPath; @@ -10,6 +16,7 @@ class WallpaperProvider extends ChangeNotifier { WallpaperProvider(); + /// 启动时从原生侧读取已设置的壁纸。 Future loadWallpaper() async { final data = await BackgroundService.getBackground(); _wallpaperType = data['type']; @@ -17,6 +24,7 @@ class WallpaperProvider extends ChangeNotifier { notifyListeners(); } + /// 设置自定义壁纸,同时写入原生侧持久存储。 Future setCustomWallpaper(String path, {String type = 'image'}) async { await BackgroundService.setBackground(type, path); _wallpaperType = type; @@ -24,6 +32,7 @@ class WallpaperProvider extends ChangeNotifier { notifyListeners(); } + /// 恢复默认背景。 Future resetWallpaper() async { await BackgroundService.clearBackground(); _wallpaperType = null; @@ -31,5 +40,7 @@ class WallpaperProvider extends ChangeNotifier { notifyListeners(); } + /// 是否设置了自定义壁纸——页面据此决定要不要把 Scaffold 背景设为透明, + /// 以便露出底层的壁纸图层。 bool get hasWallpaper => _wallpaperPath != null; }