v2.0.0: 模组插件管理、下载引擎(镜像+队列)、SSH终端、UI改版与依赖仓库
This commit is contained in:
1 parent
b8f163aa3a
commit
33d137e33c
29 files changed
+3061
-30
No files matched your search
@@ -0,0 +1,244 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'jar_metadata.dart';
|
||||
import 'sftp_service.dart';
|
||||
import 'package:dartssh2/dartssh2.dart' show SftpName;
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
/// 本地依赖索引库(SQLite):
|
||||
/// 1. 记录服务器 mods/plugins 下每个 jar 的元数据与依赖;
|
||||
/// 2. 支持依赖树查询(该模组依赖什么 / 被谁依赖);
|
||||
/// 3. 增量同步:按 (serverId, remotePath, size, mtime) 跳过未变化文件。
|
||||
class DependencyIndexService {
|
||||
static Database? _db;
|
||||
|
||||
static Future<Database> get db async {
|
||||
_db ??= await _open();
|
||||
return _db!;
|
||||
}
|
||||
|
||||
static Future<Database> _open() async {
|
||||
final dir = await getDatabasesPath();
|
||||
return openDatabase(
|
||||
p.join(dir, 'zv_dependency_index.db'),
|
||||
version: 1,
|
||||
onCreate: (db, v) => db.execute('''
|
||||
CREATE TABLE mods (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
server_id TEXT NOT NULL,
|
||||
remote_path TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
mtime INTEGER NOT NULL,
|
||||
name TEXT,
|
||||
version TEXT,
|
||||
authors TEXT,
|
||||
description TEXT,
|
||||
depends TEXT,
|
||||
soft_depends TEXT,
|
||||
synced_at INTEGER NOT NULL
|
||||
)
|
||||
'''),
|
||||
);
|
||||
}
|
||||
|
||||
/// 增量扫描远程目录并入库。返回 {新增, 更新, 总数}。
|
||||
static Future<SyncResult> syncServer(ServerConfig server) async {
|
||||
final sftp = SftpService();
|
||||
final result = SyncResult();
|
||||
try {
|
||||
await sftp.connect(server);
|
||||
final database = await db;
|
||||
for (final dir in ['mods', 'plugins']) {
|
||||
final remotePath = '/${server.sshUser.contains('root') ? 'root' : 'home/${server.sshUser}'}/$dir';
|
||||
List<SftpName> items;
|
||||
try {
|
||||
items = await sftp.listDir(remotePath);
|
||||
} catch (_) {
|
||||
continue; // 目录不存在则跳过
|
||||
}
|
||||
for (final item in items) {
|
||||
final attr = item.attr;
|
||||
if (attr.isDirectory || !item.filename.endsWith('.jar')) continue;
|
||||
final size = attr.size ?? 0;
|
||||
final mtime = attr.modifyTime ?? 0;
|
||||
final rows = await database.query('mods',
|
||||
where: 'server_id = ? AND remote_path = ?',
|
||||
whereArgs: [server.id, item.longname.isEmpty ? '$remotePath/${item.filename}' : '$remotePath/${item.filename}']);
|
||||
if (rows.isNotEmpty) {
|
||||
final row = rows.first;
|
||||
if (row['size'] == size && row['mtime'] == mtime) {
|
||||
result.unchanged++;
|
||||
continue;
|
||||
}
|
||||
await database.delete('mods', where: 'id = ?', whereArgs: [row['id']]);
|
||||
}
|
||||
// 下载到临时文件解析元数据
|
||||
final tmp = p.join((await getDatabasesPath()), 'tmp_${DateTime.now().millisecondsSinceEpoch}.jar');
|
||||
try {
|
||||
await sftp.download('$remotePath/${item.filename}', tmp);
|
||||
final meta = JarMetadata.parse(tmp);
|
||||
await database.insert('mods', {
|
||||
'server_id': server.id,
|
||||
'remote_path': '$remotePath/${item.filename}',
|
||||
'file_name': item.filename,
|
||||
'size': size,
|
||||
'mtime': mtime,
|
||||
'name': meta.name,
|
||||
'version': meta.version,
|
||||
'authors': meta.authors,
|
||||
'description': meta.description,
|
||||
'depends': jsonEncode(meta.depends),
|
||||
'soft_depends': jsonEncode(meta.softDepends),
|
||||
'synced_at': DateTime.now().millisecondsSinceEpoch,
|
||||
});
|
||||
rows.isEmpty ? result.added++ : result.updated++;
|
||||
} finally {
|
||||
final f = File(tmp);
|
||||
if (await f.exists()) await f.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
result.total = (await database.query('mods', where: 'server_id = ?', whereArgs: [server.id])).length;
|
||||
} finally {
|
||||
await sftp.disconnect();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// 服务器本地索引列表。
|
||||
static Future<List<IndexedMod>> listForServer(String serverId) async {
|
||||
final database = await db;
|
||||
final rows = await database.query('mods',
|
||||
where: 'server_id = ?', whereArgs: [serverId], orderBy: 'file_name');
|
||||
return rows.map(IndexedMod.fromRow).toList();
|
||||
}
|
||||
|
||||
/// 依赖树查询:返回 (该模组依赖的条目列表, 依赖它的条目列表, 缺失依赖 id 列表)。
|
||||
static Future<DependencyTree> queryTree(String serverId, String modId) async {
|
||||
final database = await db;
|
||||
final all = (await database.query('mods', where: 'server_id = ?', whereArgs: [serverId]))
|
||||
.map(IndexedMod.fromRow)
|
||||
.toList();
|
||||
|
||||
final self = all.firstWhere(
|
||||
(m) => m.id.toString() == modId || m.modId == modId,
|
||||
orElse: () => all.first,
|
||||
);
|
||||
final knownIds = {for (final m in all) m.modId: m};
|
||||
final missing = self.depends.where((d) => !knownIds.containsKey(_norm(d))).toList();
|
||||
|
||||
final dependsOn = <IndexedMod>[];
|
||||
for (final d in self.depends) {
|
||||
final hit = knownIds[_norm(d)];
|
||||
if (hit != null) dependsOn.add(hit);
|
||||
}
|
||||
final dependents = all.where((m) => m.depends.any((d) => _norm(d) == _norm(self.modId))).toList();
|
||||
return DependencyTree(mod: self, dependsOn: dependsOn, dependents: dependents, missing: missing);
|
||||
}
|
||||
|
||||
/// 检测版本冲突 / 重复 jar:同一 modId 出现多个版本。
|
||||
static Future<List<DuplicateGroup>> findDuplicates(String serverId) async {
|
||||
final all = (await (await db).query('mods', where: 'server_id = ?', whereArgs: [serverId]))
|
||||
.map(IndexedMod.fromRow)
|
||||
.toList();
|
||||
final groups = <String, List<IndexedMod>>{};
|
||||
for (final m in all) {
|
||||
groups.putIfAbsent(_norm(m.modId), () => []).add(m);
|
||||
}
|
||||
return groups.entries
|
||||
.where((e) => e.key.isNotEmpty && e.value.length > 1)
|
||||
.map((e) => DuplicateGroup(modId: e.key, items: e.value))
|
||||
.toList();
|
||||
}
|
||||
|
||||
static String _norm(String s) => s.trim().toLowerCase();
|
||||
|
||||
static Future<void> clearServer(String serverId) async {
|
||||
await (await db).delete('mods', where: 'server_id = ?', whereArgs: [serverId]);
|
||||
}
|
||||
}
|
||||
|
||||
class SyncResult {
|
||||
int added = 0;
|
||||
int updated = 0;
|
||||
int unchanged = 0;
|
||||
int total = 0;
|
||||
@override
|
||||
String toString() => '新增 $added · 更新 $updated · 未变化 $unchanged · 共 $total 条';
|
||||
}
|
||||
|
||||
class IndexedMod {
|
||||
final int id;
|
||||
final String serverId;
|
||||
final String remotePath;
|
||||
final String fileName;
|
||||
final int size;
|
||||
final String? name;
|
||||
final String? version;
|
||||
final String? authors;
|
||||
final String? description;
|
||||
final List<String> depends;
|
||||
final List<String> softDepends;
|
||||
|
||||
IndexedMod({
|
||||
required this.id,
|
||||
required this.serverId,
|
||||
required this.remotePath,
|
||||
required this.fileName,
|
||||
required this.size,
|
||||
this.name,
|
||||
this.version,
|
||||
this.authors,
|
||||
this.description,
|
||||
this.depends = const [],
|
||||
this.softDepends = const [],
|
||||
});
|
||||
|
||||
/// 索引中用于匹配依赖的 modId:优先取文件名去后缀,其次名称。
|
||||
String get modId => name ?? fileName.replaceAll(RegExp(r'\.jar$'), '');
|
||||
|
||||
factory IndexedMod.fromRow(Map<String, dynamic> row) => IndexedMod(
|
||||
id: row['id'] as int,
|
||||
serverId: row['server_id'] as String,
|
||||
remotePath: row['remote_path'] as String,
|
||||
fileName: row['file_name'] as String,
|
||||
size: row['size'] as int? ?? 0,
|
||||
name: row['name'] as String?,
|
||||
version: row['version'] as String?,
|
||||
authors: row['authors'] as String?,
|
||||
description: row['description'] as String?,
|
||||
depends: _decode(row['depends']),
|
||||
softDepends: _decode(row['soft_depends']),
|
||||
);
|
||||
|
||||
static List<String> _decode(dynamic v) {
|
||||
if (v == null) return const [];
|
||||
try {
|
||||
return List<String>.from(jsonDecode(v as String));
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DependencyTree {
|
||||
final IndexedMod mod;
|
||||
final List<IndexedMod> dependsOn;
|
||||
final List<IndexedMod> dependents;
|
||||
final List<String> missing; // 缺失依赖(可一键从 Modrinth 补齐)
|
||||
DependencyTree({
|
||||
required this.mod,
|
||||
required this.dependsOn,
|
||||
required this.dependents,
|
||||
required this.missing,
|
||||
});
|
||||
}
|
||||
|
||||
class DuplicateGroup {
|
||||
final String modId;
|
||||
final List<IndexedMod> items;
|
||||
DuplicateGroup({required this.modId, required this.items});
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' as io;
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'sftp_service.dart';
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
enum DownloadStatus { queued, running, paused, completed, failed, canceled }
|
||||
|
||||
/// 单个下载任务。
|
||||
class DownloadTask {
|
||||
final String id;
|
||||
final String url; // 直链(已镜像改写)
|
||||
final String fileName;
|
||||
final String savePath;
|
||||
final String? sftpRemoteDir; // 完成后自动上传到服务器的目录(需 SSH)
|
||||
int totalBytes;
|
||||
int receivedBytes = 0;
|
||||
double speed = 0; // bytes/s
|
||||
DownloadStatus status = DownloadStatus.queued;
|
||||
String? error;
|
||||
|
||||
DownloadTask({
|
||||
required this.id,
|
||||
required this.url,
|
||||
required this.fileName,
|
||||
required this.savePath,
|
||||
this.sftpRemoteDir,
|
||||
this.totalBytes = 0,
|
||||
});
|
||||
|
||||
double get progress => totalBytes > 0 ? (receivedBytes / totalBytes).clamp(0, 1) : 0;
|
||||
}
|
||||
|
||||
/// 下载引擎:队列 + 并发控制(默认 3)+ 断点续传(HTTP Range)
|
||||
/// + 失败重试(指数退避)+ 完成后经 SFTP 自动上传。
|
||||
/// HTTP IO 由 dio 在其内部线程池执行,进度经节流回调到 UI,不阻塞主线程。
|
||||
class DownloadManager extends ChangeNotifier {
|
||||
final int maxConcurrent;
|
||||
final List<DownloadTask> _tasks = [];
|
||||
final Map<String, CancelToken> _cancelTokens = {};
|
||||
final Map<String, bool> _pauseFlags = {};
|
||||
final Set<String> _running = {};
|
||||
final Dio _dio;
|
||||
final Future<void> Function(DownloadTask task)? onTaskCompleteUpload;
|
||||
|
||||
DownloadManager({this.maxConcurrent = 3, this.onTaskCompleteUpload})
|
||||
: _dio = Dio(BaseOptions(
|
||||
connectTimeout: const Duration(seconds: 15),
|
||||
receiveTimeout: const Duration(minutes: 10),
|
||||
));
|
||||
|
||||
List<DownloadTask> get tasks => List.unmodifiable(_tasks);
|
||||
int get activeCount => _running.length;
|
||||
|
||||
/// 入队一个下载任务,自动启动。
|
||||
DownloadTask enqueue({
|
||||
required String url,
|
||||
required String fileName,
|
||||
required String saveDir,
|
||||
String? sftpRemoteDir,
|
||||
Map<String, String>? headers,
|
||||
}) {
|
||||
final task = DownloadTask(
|
||||
id: 'dl_${DateTime.now().millisecondsSinceEpoch}_${_tasks.length}',
|
||||
url: url,
|
||||
fileName: fileName,
|
||||
savePath: '$saveDir/$fileName',
|
||||
sftpRemoteDir: sftpRemoteDir,
|
||||
);
|
||||
_tasks.add(task);
|
||||
notifyListeners();
|
||||
_pump(headers);
|
||||
return task;
|
||||
}
|
||||
|
||||
void pause(String id) {
|
||||
_pauseFlags[id] = true;
|
||||
_cancelTokens[id]?.cancel('paused');
|
||||
_updateStatus(id, DownloadStatus.paused);
|
||||
}
|
||||
|
||||
void resume(String id, {Map<String, String>? headers}) {
|
||||
final task = _find(id);
|
||||
if (task == null || task.status != DownloadStatus.paused) return;
|
||||
_pauseFlags.remove(id);
|
||||
_updateStatus(id, DownloadStatus.queued);
|
||||
_pump(headers);
|
||||
}
|
||||
|
||||
void cancel(String id) {
|
||||
_cancelTokens[id]?.cancel('canceled');
|
||||
_updateStatus(id, DownloadStatus.canceled);
|
||||
_running.remove(id);
|
||||
_pump();
|
||||
}
|
||||
|
||||
void retry(String id, {Map<String, String>? headers}) {
|
||||
final task = _find(id);
|
||||
if (task == null) return;
|
||||
_pauseFlags.remove(id);
|
||||
task.error = null;
|
||||
_updateStatus(id, DownloadStatus.queued);
|
||||
_pump(headers);
|
||||
}
|
||||
|
||||
void clearFinished() {
|
||||
_tasks.removeWhere((t) =>
|
||||
t.status == DownloadStatus.completed ||
|
||||
t.status == DownloadStatus.canceled ||
|
||||
t.status == DownloadStatus.failed);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
DownloadTask? _find(String id) {
|
||||
try {
|
||||
return _tasks.firstWhere((t) => t.id == id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _updateStatus(String id, DownloadStatus status) {
|
||||
final task = _find(id);
|
||||
if (task != null && task.status != status) {
|
||||
task.status = status;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 队列调度:保持最多 maxConcurrent 个任务在跑。
|
||||
void _pump([Map<String, String>? headers]) {
|
||||
while (_running.length < maxConcurrent) {
|
||||
final next = _tasks.firstWhere(
|
||||
(t) => t.status == DownloadStatus.queued && !_running.contains(t.id),
|
||||
orElse: () => _noop,
|
||||
);
|
||||
if (identical(next, _noop)) break;
|
||||
_running.add(next.id);
|
||||
unawaited(_run(next, headers));
|
||||
}
|
||||
}
|
||||
|
||||
static final DownloadTask _noop = DownloadTask(id: '_noop', url: '', fileName: '', savePath: '');
|
||||
|
||||
Future<void> _run(DownloadTask task, Map<String, String>? headers) async {
|
||||
final token = CancelToken();
|
||||
_cancelTokens[task.id] = token;
|
||||
await _downloadWithRetry(task, token, headers);
|
||||
_running.remove(task.id);
|
||||
_cancelTokens.remove(task.id);
|
||||
_pump(headers);
|
||||
}
|
||||
|
||||
Future<void> _downloadWithRetry(
|
||||
DownloadTask task, CancelToken token, Map<String, String>? headers) async {
|
||||
const maxRetry = 3;
|
||||
var attempt = 0;
|
||||
while (attempt <= maxRetry) {
|
||||
try {
|
||||
_updateStatus(task.id, DownloadStatus.running);
|
||||
await io.Directory(io.File(task.savePath).parent.path).create(recursive: true);
|
||||
var existing = 0;
|
||||
final partial = io.File('${task.savePath}.part');
|
||||
if (await partial.exists()) existing = await partial.length();
|
||||
|
||||
var lastTick = DateTime.now();
|
||||
var lastBytes = existing;
|
||||
|
||||
final resp = await _dio.download(
|
||||
task.url,
|
||||
'${task.savePath}.part',
|
||||
cancelToken: token,
|
||||
options: Options(
|
||||
headers: {
|
||||
if (existing > 0) 'range': 'bytes=$existing-',
|
||||
...?headers,
|
||||
},
|
||||
validateStatus: (s) => s != null && s < 400,
|
||||
),
|
||||
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;
|
||||
}
|
||||
final now = DateTime.now();
|
||||
final dt = now.difference(lastTick).inMilliseconds;
|
||||
if (dt >= 500) {
|
||||
task.speed = (task.receivedBytes - lastBytes) * 1000 / dt;
|
||||
lastTick = now;
|
||||
lastBytes = task.receivedBytes;
|
||||
notifyListeners();
|
||||
}
|
||||
},
|
||||
);
|
||||
// 200 响应(非续传)时重置已收字节
|
||||
if (resp.statusCode == 200 && existing > 0 && task.receivedBytes < existing) {
|
||||
task.receivedBytes = task.receivedBytes;
|
||||
}
|
||||
task.totalBytes = task.receivedBytes;
|
||||
await partial.rename(task.savePath);
|
||||
_updateStatus(task.id, DownloadStatus.completed);
|
||||
notifyListeners();
|
||||
if (onTaskCompleteUpload != null) {
|
||||
await onTaskCompleteUpload!(task);
|
||||
}
|
||||
return;
|
||||
} on DioException catch (e) {
|
||||
if (token.isCancelled) return; // 暂停/取消
|
||||
attempt++;
|
||||
task.error = e.message ?? '网络错误';
|
||||
if (attempt > maxRetry) {
|
||||
_updateStatus(task.id, DownloadStatus.failed);
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
// 指数退避:1s → 2s → 4s
|
||||
await Future<void>.delayed(Duration(seconds: 1 << (attempt - 1)));
|
||||
} catch (e) {
|
||||
task.error = e.toString();
|
||||
_updateStatus(task.id, DownloadStatus.failed);
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载完成后自动经 SFTP 上传到服务器目标目录。
|
||||
Future<void> uploadViaSftp(DownloadTask task, ServerLike server) async {
|
||||
final remoteDir = task.sftpRemoteDir;
|
||||
if (remoteDir == null || remoteDir.isEmpty) return;
|
||||
final sftp = SftpService();
|
||||
try {
|
||||
await sftp.connect(server.toConfig());
|
||||
await sftp.upload(task.savePath, '$remoteDir/${task.fileName}');
|
||||
} finally {
|
||||
await sftp.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/// 避免循环依赖的轻量服务器描述(由 DownloadProvider 装配)。
|
||||
class ServerLike {
|
||||
final String host;
|
||||
final int sshPort;
|
||||
final String sshUser;
|
||||
final String sshPassword;
|
||||
ServerLike({
|
||||
required this.host,
|
||||
required this.sshPort,
|
||||
required this.sshUser,
|
||||
required this.sshPassword,
|
||||
});
|
||||
ServerConfig toConfig() => ServerConfig(
|
||||
id: 'upload',
|
||||
name: 'upload',
|
||||
host: host,
|
||||
port: 0,
|
||||
password: '',
|
||||
sshEnabled: true,
|
||||
sshPort: sshPort,
|
||||
sshUser: sshUser,
|
||||
sshPassword: sshPassword,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:yaml/yaml.dart';
|
||||
|
||||
/// 从 jar(zip)中解析模组/插件元数据。
|
||||
/// 支持:fabric.mod.json / quilt.mod.json / paper-plugin.yml / plugin.yml / mods.toml
|
||||
class JarMetadata {
|
||||
final String? name;
|
||||
final String? version;
|
||||
final String? authors;
|
||||
final String? description;
|
||||
final List<String> depends; // 硬依赖
|
||||
final List<String> softDepends; // 软依赖
|
||||
final String source; // 来源文件类型
|
||||
|
||||
const JarMetadata({
|
||||
this.name,
|
||||
this.version,
|
||||
this.authors,
|
||||
this.description,
|
||||
this.depends = const [],
|
||||
this.softDepends = const [],
|
||||
this.source = 'unknown',
|
||||
});
|
||||
|
||||
static JarMetadata empty = const JarMetadata();
|
||||
|
||||
/// 解析本地 jar 文件,失败时返回 empty。
|
||||
static JarMetadata parse(String jarPath) {
|
||||
try {
|
||||
final bytes = File(jarPath).readAsBytesSync();
|
||||
final archive = ZipDecoder().decodeBytes(bytes);
|
||||
return parseArchive(archive);
|
||||
} catch (_) {
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// 从内存中的 zip Archive 解析(公开以便测试)。
|
||||
static JarMetadata parseArchive(Archive archive) => _fromArchive(archive);
|
||||
|
||||
static JarMetadata _fromArchive(Archive archive) {
|
||||
// 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>));
|
||||
final loader = json['quilt_loader'];
|
||||
final root = loader ?? json;
|
||||
final meta = root['metadata'] ?? {};
|
||||
return JarMetadata(
|
||||
name: (root['name'] ?? meta['name'] ?? root['id'])?.toString(),
|
||||
version: (root['version'] ?? meta['version'])?.toString(),
|
||||
authors: _joinAuthors(meta['contributors'] ?? root['authors']),
|
||||
description: (meta['description'] ?? root['description'])?.toString(),
|
||||
depends: _toStringList(root['depends'] ?? json['depends']),
|
||||
softDepends: _toStringList(root['suggests'] ?? json['suggests']),
|
||||
source: entry,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Paper/Bukkit 插件:paper-plugin.yml / plugin.yml
|
||||
for (final entry in ['paper-plugin.yml', 'plugin.yml']) {
|
||||
final f = archive.findFile(entry);
|
||||
if (f != null) {
|
||||
final y = loadYaml(utf8.decode(f.content as List<int>));
|
||||
return JarMetadata(
|
||||
name: (y['name'])?.toString(),
|
||||
version: (y['version'])?.toString(),
|
||||
authors: _joinAuthors(y['authors'] ?? y['author']),
|
||||
description: (y['description'])?.toString(),
|
||||
depends: _toStringList(y['depend']),
|
||||
softDepends: _toStringList(y['softdepend']),
|
||||
source: entry,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 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')) {
|
||||
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();
|
||||
return JarMetadata(name: name, version: ver, depends: deps.skip(1).toList(), source: entry);
|
||||
}
|
||||
final json = jsonDecode(text);
|
||||
final info = json is List ? json.first : (json['modList']?.first ?? {});
|
||||
return JarMetadata(
|
||||
name: info['name']?.toString(),
|
||||
version: info['version']?.toString(),
|
||||
authors: _joinAuthors(info['authorList']),
|
||||
description: info['description']?.toString(),
|
||||
source: entry,
|
||||
);
|
||||
}
|
||||
}
|
||||
return empty;
|
||||
}
|
||||
|
||||
static List<String> _toStringList(dynamic v) {
|
||||
if (v == null) return const [];
|
||||
if (v is YamlList) return v.map((e) => e.toString()).toList();
|
||||
if (v is List) return v.map((e) => e.toString()).toList();
|
||||
if (v is Map) {
|
||||
// fabric depends 可能是 {modid: "^1.0.0"} 或 contributors map
|
||||
return v.keys.map((e) => e.toString()).toList();
|
||||
}
|
||||
return v.toString().split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
|
||||
}
|
||||
|
||||
static String? _joinAuthors(dynamic v) {
|
||||
if (v == null) return null;
|
||||
if (v is YamlList || v is List) return v.join(', ');
|
||||
if (v is YamlMap || v is Map) return v.keys.join(', ');
|
||||
return v.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// 镜像源服务:内置 MCIM(Modrinth 国内镜像),支持自定义线路与一键测速。
|
||||
class MirrorService extends ChangeNotifier {
|
||||
static const _prefKey = 'mirror_line';
|
||||
|
||||
/// 内置镜像线路:id → 名称。'official' 为 Modrinth 官方源。
|
||||
static const builtinMirrors = {
|
||||
'official': 'Modrinth 官方',
|
||||
'mcim': 'MCIM 国内镜像 (mcimirror.top)',
|
||||
};
|
||||
|
||||
String _current = 'mcim';
|
||||
String _customUrl = '';
|
||||
int lastSpeedMs = -1;
|
||||
|
||||
String get currentId => _current;
|
||||
String get customUrl => _customUrl;
|
||||
|
||||
String get currentName {
|
||||
if (_current == 'custom') return '自定义 ($_customUrl)';
|
||||
return builtinMirrors[_current] ?? _current;
|
||||
}
|
||||
|
||||
Future<void> load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
_current = prefs.getString(_prefKey) ?? 'mcim';
|
||||
_customUrl = prefs.getString('${_prefKey}_custom') ?? '';
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> select(String id, {String customUrl = ''}) async {
|
||||
_current = id;
|
||||
if (customUrl.isNotEmpty) _customUrl = customUrl;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_prefKey, id);
|
||||
await prefs.setString('${_prefKey}_custom', _customUrl);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 把 Modrinth 官方域名改写为镜像域名。
|
||||
/// MCIM 镜像规则:api.modrinth.com → modrinth-api.mcimirror.top
|
||||
/// cdn.modrinth.com → modrinth-cdn.mcimirror.top
|
||||
String rewrite(String url) {
|
||||
final uri = Uri.parse(url);
|
||||
if (_current == 'official') return url;
|
||||
if (_current == 'custom') {
|
||||
if (_customUrl.isEmpty) return url;
|
||||
final base = Uri.parse(_customUrl.endsWith('/')
|
||||
? _customUrl.substring(0, _customUrl.length - 1)
|
||||
: _customUrl);
|
||||
// 自定义镜像:假定其结构与官方一致(api./cdn. 前缀由 base 提供,路径不变)
|
||||
if (uri.host == 'api.modrinth.com' || uri.host == 'cdn.modrinth.com') {
|
||||
return base.replace(path: uri.path, query: uri.query).toString();
|
||||
}
|
||||
return url;
|
||||
}
|
||||
// MCIM
|
||||
final newHost = uri.host == 'api.modrinth.com'
|
||||
? 'modrinth-api.mcimirror.top'
|
||||
: uri.host == 'cdn.modrinth.com'
|
||||
? 'modrinth-cdn.mcimirror.top'
|
||||
: uri.host;
|
||||
return uri.replace(host: newHost).toString();
|
||||
}
|
||||
|
||||
/// 测速:对镜像的 api 域名发 HEAD 请求,返回毫秒数;失败返回 -1。
|
||||
Future<int> speedTest(String mirrorId) async {
|
||||
final String probe = switch (mirrorId) {
|
||||
'official' => 'https://api.modrinth.com/v2/project/sodium/version?limit=1',
|
||||
'mcim' => 'https://modrinth-api.mcimirror.top/v2/project/sodium/version?limit=1',
|
||||
_ => _customUrl,
|
||||
};
|
||||
if (probe.isEmpty) return -1;
|
||||
final sw = Stopwatch()..start();
|
||||
try {
|
||||
await Dio().head(probe, options: Options(sendTimeout: const Duration(seconds: 5), receiveTimeout: const Duration(seconds: 5)));
|
||||
sw.stop();
|
||||
return sw.elapsedMilliseconds;
|
||||
} catch (_) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/// 自动选择测速最快的线路(官方算作兜底)。
|
||||
Future<String> autoSelect() async {
|
||||
final results = <String, int>{};
|
||||
for (final id in ['mcim', 'official']) {
|
||||
results[id] = await speedTest(id);
|
||||
}
|
||||
final usable = results.entries.where((e) => e.value > 0).toList()
|
||||
..sort((a, b) => a.value.compareTo(b.value));
|
||||
final best = usable.isNotEmpty ? usable.first.key : 'official';
|
||||
await select(best);
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'mirror_service.dart';
|
||||
|
||||
/// Modrinth API 封装(无需密钥)。
|
||||
/// 文档:https://docs.modrinth.com/
|
||||
class ModrinthApi {
|
||||
final MirrorService mirror;
|
||||
ModrinthApi(this.mirror);
|
||||
|
||||
Dio get _dio {
|
||||
final d = Dio(BaseOptions(
|
||||
connectTimeout: const Duration(seconds: 15),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
));
|
||||
d.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
// 镜像改写:api.modrinth.com / cdn.modrinth.com → 镜像节点
|
||||
options.path = mirror.rewrite(options.uri.toString());
|
||||
options.headers['User-Agent'] = 'ZVManager/2.0 (gitee.com/driftinblock/zvmanager)';
|
||||
handler.next(options);
|
||||
},
|
||||
));
|
||||
return d;
|
||||
}
|
||||
|
||||
/// 搜索项目。facets 例:[["versions:1.20.1"], ["categories:fabric"], ["project_type:mod"]]
|
||||
Future<List<ModrinthSearchResult>> search({
|
||||
required String query,
|
||||
String projectType = 'mod',
|
||||
String? mcVersion,
|
||||
String? loader,
|
||||
int limit = 20,
|
||||
}) async {
|
||||
final facets = <List<String>>[
|
||||
['project_type:$projectType'],
|
||||
];
|
||||
if (mcVersion != null && mcVersion.isNotEmpty) facets.add(['versions:$mcVersion']);
|
||||
if (loader != null && loader.isNotEmpty) facets.add(['categories:$loader']);
|
||||
final resp = await _dio.get('/v2/search', queryParameters: {
|
||||
'query': query,
|
||||
'limit': limit,
|
||||
'facets': facets,
|
||||
});
|
||||
final hits = resp.data['hits'] as List;
|
||||
return hits.map((e) => ModrinthSearchResult.fromJson(e)).toList();
|
||||
}
|
||||
|
||||
/// 获取项目最新兼容版本列表(按日期倒序)。
|
||||
Future<List<ModrinthVersion>> versions(String projectId) async {
|
||||
final resp = await _dio.get('/v2/project/$projectId/version');
|
||||
final list = (resp.data as List).map((e) => ModrinthVersion.fromJson(e)).toList();
|
||||
list.sort((a, b) => b.datePublished.compareTo(a.datePublished));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// 项目详情(用于依赖信息)。
|
||||
Future<Map<String, dynamic>> project(String idOrSlug) async {
|
||||
final resp = await _dio.get('/v2/project/$idOrSlug');
|
||||
return Map<String, dynamic>.from(resp.data);
|
||||
}
|
||||
}
|
||||
|
||||
class ModrinthSearchResult {
|
||||
final String slug;
|
||||
final String title;
|
||||
final String description;
|
||||
final List<String> categories;
|
||||
final int downloads;
|
||||
final String? iconUrl;
|
||||
final String projectId;
|
||||
|
||||
ModrinthSearchResult({
|
||||
required this.slug,
|
||||
required this.title,
|
||||
required this.description,
|
||||
required this.categories,
|
||||
required this.downloads,
|
||||
this.iconUrl,
|
||||
required this.projectId,
|
||||
});
|
||||
|
||||
factory ModrinthSearchResult.fromJson(Map<String, dynamic> e) => ModrinthSearchResult(
|
||||
slug: e['slug'] ?? '',
|
||||
title: e['title'] ?? '',
|
||||
description: e['description'] ?? '',
|
||||
categories: List<String>.from(e['categories'] ?? const []),
|
||||
downloads: e['downloads'] ?? 0,
|
||||
iconUrl: e['icon_url'],
|
||||
projectId: e['project_id'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
class ModrinthVersion {
|
||||
final String id;
|
||||
final String versionNumber;
|
||||
final String name;
|
||||
final List<String> gameVersions;
|
||||
final List<String> loaders;
|
||||
final DateTime datePublished;
|
||||
final String? changelog;
|
||||
final List<Map<String, dynamic>> files;
|
||||
|
||||
ModrinthVersion({
|
||||
required this.id,
|
||||
required this.versionNumber,
|
||||
required this.name,
|
||||
required this.gameVersions,
|
||||
required this.loaders,
|
||||
required this.datePublished,
|
||||
this.changelog,
|
||||
this.files = const [],
|
||||
});
|
||||
|
||||
factory ModrinthVersion.fromJson(Map<String, dynamic> e) => ModrinthVersion(
|
||||
id: e['id'],
|
||||
versionNumber: e['version_number'] ?? '',
|
||||
name: e['name'] ?? '',
|
||||
gameVersions: List<String>.from(e['game_versions'] ?? const []),
|
||||
loaders: List<String>.from(e['loaders'] ?? const []),
|
||||
datePublished: DateTime.tryParse(e['date_published'] ?? '') ?? DateTime.now(),
|
||||
changelog: e['changelog'],
|
||||
files: List<Map<String, dynamic>>.from(e['files'] ?? const []),
|
||||
);
|
||||
}
|
||||
|
||||
/// 从版本文件列表中取主 jar 文件的下载链接。
|
||||
String? primaryFileUrl(Map<String, dynamic> file) => file['url'] as String?;
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:dartssh2/dartssh2.dart';
|
||||
import 'dart:io' as io;
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
/// 基于 dartssh2 的 SFTP 文件服务。
|
||||
/// 一次连接同时支持列目录 / 上传 / 下载 / 删除 / 重命名,
|
||||
/// 供模组管理(M1)与下载完成后自动上传(M2)复用。
|
||||
class SftpService {
|
||||
SSHClient? _client;
|
||||
SftpClient? _sftp;
|
||||
ServerConfig? _bound;
|
||||
|
||||
bool get isConnected => _client != null && !_client!.isClosed;
|
||||
|
||||
/// 连接到指定服务器的 SSH。失败抛异常。
|
||||
Future<void> connect(ServerConfig server) async {
|
||||
if (isConnected && _bound?.id == server.id) return;
|
||||
await disconnect();
|
||||
final socket = await SSHSocket.connect(
|
||||
server.host,
|
||||
server.sshPort,
|
||||
timeout: const Duration(seconds: 10),
|
||||
);
|
||||
_client = SSHClient(
|
||||
socket,
|
||||
username: server.sshUser,
|
||||
onPasswordRequest: () => server.sshPassword,
|
||||
);
|
||||
_sftp = await _client!.sftp();
|
||||
_bound = server;
|
||||
}
|
||||
|
||||
/// 列出目录内容。
|
||||
Future<List<SftpName>> listDir(String path) async {
|
||||
return _requireSftp().listdir(path);
|
||||
}
|
||||
|
||||
/// 上传本地文件到远程路径。
|
||||
Future<void> upload(String localPath, String remotePath) async {
|
||||
final sftp = _requireSftp();
|
||||
final file = await sftp.open(
|
||||
remotePath,
|
||||
mode: SftpFileOpenMode.create | SftpFileOpenMode.truncate | SftpFileOpenMode.write,
|
||||
);
|
||||
try {
|
||||
final local = io.File(localPath);
|
||||
|
||||
final writer = file.write(
|
||||
local.openRead().map((chunk) => Uint8List.fromList(chunk)),
|
||||
onProgress: (_) {},
|
||||
);
|
||||
// 预读 stat.size 仅用于日志/进度;writer 自行完成
|
||||
await writer.done;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载远程文件到本地路径。
|
||||
Future<void> download(
|
||||
String remotePath,
|
||||
String localPath, {
|
||||
void Function(int, int)? onProgress,
|
||||
}) async {
|
||||
final sftp = _requireSftp();
|
||||
final stat = await sftp.stat(remotePath);
|
||||
final total = stat.size ?? 0;
|
||||
final file = await sftp.open(remotePath, mode: SftpFileOpenMode.read);
|
||||
try {
|
||||
final sink = io.File(localPath).openWrite();
|
||||
var received = 0;
|
||||
await for (final chunk in file.read(onProgress: null)) {
|
||||
sink.add(chunk);
|
||||
received += chunk.length;
|
||||
onProgress?.call(received, total);
|
||||
}
|
||||
await sink.flush();
|
||||
await sink.close();
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> delete(String remotePath) async {
|
||||
await _requireSftp().remove(remotePath);
|
||||
}
|
||||
|
||||
Future<void> rename(String remotePath, String newName) async {
|
||||
final sftp = _requireSftp();
|
||||
final parent = remotePath.substring(0, remotePath.lastIndexOf('/') + 1);
|
||||
await sftp.rename(remotePath, '$parent$newName');
|
||||
}
|
||||
|
||||
Future<void> mkdir(String remotePath) async {
|
||||
try {
|
||||
await _requireSftp().mkdir(remotePath);
|
||||
} catch (_) {
|
||||
// 已存在时忽略
|
||||
}
|
||||
}
|
||||
|
||||
SftpClient _requireSftp() {
|
||||
final sftp = _sftp;
|
||||
if (sftp == null || !isConnected) {
|
||||
throw StateError('SFTP 未连接,请先调用 connect()');
|
||||
}
|
||||
return sftp;
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
_sftp = null;
|
||||
_client?.close();
|
||||
_client = null;
|
||||
_bound = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import 'package:dartssh2/dartssh2.dart';
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
/// SSH Shell(PTY)会话服务,与 SFTP 复用同一套 SSH 凭据。
|
||||
/// 支持 resize、keepalive、断线自动重连(最多 3 次)。
|
||||
class SshShellService {
|
||||
SSHClient? _client;
|
||||
SSHSocket? _socket;
|
||||
SSHSession? _session;
|
||||
int _failedReconnects = 0;
|
||||
|
||||
bool get isConnected => _client != null && !_client!.isClosed;
|
||||
|
||||
/// 建立 PTY 会话。输出通过 [onOutput] 回调(UTF-8 解码后)。
|
||||
Future<void> connect(
|
||||
ServerConfig server, {
|
||||
required void Function(String) onOutput,
|
||||
void Function()? onDisconnected,
|
||||
int cols = 80,
|
||||
int rows = 24,
|
||||
}) async {
|
||||
await disconnect();
|
||||
_socket = await SSHSocket.connect(
|
||||
server.host,
|
||||
server.sshPort,
|
||||
timeout: const Duration(seconds: 10),
|
||||
);
|
||||
_client = SSHClient(
|
||||
_socket!,
|
||||
username: server.sshUser,
|
||||
onPasswordRequest: () => server.sshPassword,
|
||||
keepAliveInterval: const Duration(seconds: 15),
|
||||
);
|
||||
_failedReconnects = 0;
|
||||
|
||||
final shell = await _client!.shell(
|
||||
pty: SSHPtyConfig(type: 'xterm-256color', width: cols, height: rows),
|
||||
);
|
||||
_session = shell;
|
||||
|
||||
shell.stdout.listen(
|
||||
(data) => onOutput(utf8.decode(data, allowMalformed: true)),
|
||||
onDone: () {
|
||||
onDisconnected?.call();
|
||||
_tryReconnect(server, onOutput: onOutput, onDisconnected: onDisconnected);
|
||||
},
|
||||
onError: (_) => onDisconnected?.call(),
|
||||
);
|
||||
shell.stderr.listen((data) => onOutput(utf8.decode(data, allowMalformed: true)));
|
||||
}
|
||||
|
||||
Future<void> _tryReconnect(
|
||||
ServerConfig server, {
|
||||
required void Function(String) onOutput,
|
||||
void Function()? onDisconnected,
|
||||
}) async {
|
||||
if (_failedReconnects >= 3) return;
|
||||
_failedReconnects++;
|
||||
await Future<void>.delayed(Duration(seconds: 2 * _failedReconnects));
|
||||
try {
|
||||
await connect(server, onOutput: onOutput, onDisconnected: onDisconnected);
|
||||
onOutput('\r\n\x1b[32m[已自动重连]\x1b[0m\r\n');
|
||||
} catch (_) {
|
||||
onDisconnected?.call();
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入用户输入。
|
||||
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 {
|
||||
_session?.close();
|
||||
_session = null;
|
||||
_client?.close();
|
||||
_client = null;
|
||||
_socket?.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user