docs: 为核心协议层、服务层与主要页面补充代码注释,修复下载进度计算逻辑

This commit is contained in:
ZV Team committed 2026-10-27 20:46:03 +08:00
1 parent 7e618adf6c
commit 854f00038c
14 files changed
+244 -28

No files matched your search

+28 -14
View File
@@ -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);
+6 -1
View File
@@ -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<int>));
// 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<int>);
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);
+10 -3
View File
@@ -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<int> speedTest(String mirrorId) async {
final String probe = switch (mirrorId) {
'official' => 'https://api.modrinth.com/v2/project/sodium/version?limit=1',
+23
View File
@@ -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<List<ModrinthSearchResult>> 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<String> 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<String> gameVersions;
/// 兼容的加载器(fabric / forge / neoforge / quilt)
final List<String> loaders;
final DateTime datePublished;
final String? changelog;
/// 文件列表,每项含 url / filename / primary 等字段
final List<Map<String, dynamic>> files;
ModrinthVersion({
+14
View File
@@ -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<void> 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<void> upload(String localPath, String remotePath) async {
final sftp = _requireSftp();
final file = await sftp.open(
@@ -60,6 +68,8 @@ class SftpService {
}
/// 下载远程文件到本地路径。
///
/// [onProgress] 参数为 (已下载字节, 总字节);总字节未知时为 0。
Future<void> download(
String remotePath,
String localPath, {
@@ -85,6 +95,10 @@ class SftpService {
}
/// 读取远程文件文本内容(保留末尾 maxBytes 字节,适合大日志文件)。
///
/// 服务器日志动辄上百 MB,全量读取会撑爆内存且价值不大,
/// 因此超限时只保留尾部——排查崩溃时真正关心的是最后那段堆栈。
/// 截断位置会向前对齐到 UTF-8 字符边界,避免出现乱码。
Future<String> readString(
String remotePath, {
int maxBytes = 2 * 1024 * 1024,
+8 -2
View File
@@ -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<void> 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<void> _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<void> disconnect() async {