v2.0.0: 模组插件管理、下载引擎(镜像+队列)、SSH终端、UI改版与依赖仓库

This commit is contained in:
ZV Dev committed 2026-10-22 23:28:14 +08:00
1 parent b8f163aa3a
commit 33d137e33c
29 files changed
+3061 -30

No files matched your search

@@ -0,0 +1,228 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/services/dependency_index_service.dart';
import '../../providers/download_provider.dart';
import '../../providers/server_provider.dart';
/// 依赖仓库页:服务器本地仓库增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测。
class DependencyTreePage extends StatefulWidget {
final ServerConfig server;
const DependencyTreePage({super.key, required this.server});
@override
State<DependencyTreePage> createState() => _DependencyTreePageState();
}
class _DependencyTreePageState extends State<DependencyTreePage> {
List<IndexedMod>? _mods;
bool _syncing = false;
String? _syncInfo;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final mods = await DependencyIndexService.listForServer(widget.server.id);
if (!mounted) return;
setState(() => _mods = mods);
}
Future<void> _sync() async {
setState(() {
_syncing = true;
_syncInfo = null;
});
try {
final result = await DependencyIndexService.syncServer(widget.server);
if (!mounted) return;
setState(() {
_syncInfo = result.toString();
_syncing = false;
});
await _load();
} catch (e) {
if (!mounted) return;
setState(() {
_syncing = false;
_syncInfo = '同步失败:$e';
});
}
}
Future<void> _showTree(IndexedMod mod) async {
final tree = await DependencyIndexService.queryTree(widget.server.id, mod.modId);
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(16),
children: [
Text('${tree.mod.name ?? tree.mod.fileName} ${tree.mod.version ?? ''}',
style: Theme.of(context).textTheme.titleMedium),
const Divider(),
const Text('该模组依赖:'),
...tree.dependsOn.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
)),
if (tree.dependsOn.isEmpty) const Text('无', style: TextStyle(color: Colors.grey)),
const SizedBox(height: 8),
const Text('被以下模组依赖:'),
...tree.dependents.map((m) => ListTile(
dense: true,
leading: const Icon(Icons.link, size: 18),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
)),
if (tree.dependents.isEmpty) const Text('无', style: TextStyle(color: Colors.grey)),
if (tree.missing.isNotEmpty) ...[
const SizedBox(height: 8),
const Text('缺失依赖(可一键补齐):',
style: TextStyle(color: Colors.red, fontWeight: FontWeight.w600)),
...tree.missing.map((d) => ListTile(
dense: true,
leading: const Icon(Icons.warning_amber_rounded, color: Colors.red, size: 20),
title: Text(d),
trailing: TextButton(
onPressed: () => _fetchMissing(d),
child: const Text('从 Modrinth 补齐'),
),
)),
],
],
),
),
);
}
Future<void> _fetchMissing(String name) async {
final dp = context.read<DownloadProvider>();
try {
final results = await dp.search(name, projectType: 'mod', limit: 1);
if (results.isEmpty) throw '未找到 $name';
final project = results.first;
final versions = await dp.versions(project.projectId);
if (versions.isEmpty) throw '该项目没有可用版本';
final v = versions.first;
if (v.files.isEmpty) throw '没有可用文件';
final primary = v.files.firstWhere((f) => f['primary'] == true, orElse: () => v.files.first);
await dp.download(url: primary['url'], fileName: primary['filename'], projectType: 'mod');
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已下载 $name(${v.versionNumber})')));
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('补齐失败:$e')));
}
}
}
Future<void> _checkDuplicates() async {
final dups = await DependencyIndexService.findDuplicates(widget.server.id);
if (!mounted) return;
showModalBottomSheet(
context: context,
builder: (_) => SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(16),
children: [
Text('版本冲突 / 重复 jar', style: Theme.of(context).textTheme.titleMedium),
const Divider(),
if (dups.isEmpty) const Text('未发现重复'),
...dups.map((g) => ExpansionTile(
title: Text(g.modId,
style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.w600)),
subtitle: Text('${g.items.length} 个版本共存'),
children: g.items
.map((m) => ListTile(
dense: true,
title: Text(m.fileName),
subtitle: Text('版本 ${m.version ?? '未知'} · ${m.remotePath}'),
))
.toList(),
)),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('依赖仓库'),
actions: [
IconButton(
icon: const Icon(Icons.rule),
tooltip: '重复检测',
onPressed: _checkDuplicates,
),
],
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: Text(_syncInfo ?? '点击「同步」增量扫描服务器 mods/plugins 并建立依赖索引'),
),
FilledButton.icon(
icon: _syncing
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.sync),
label: const Text('同步'),
onPressed: _syncing ? null : _sync,
),
],
),
),
Expanded(
child: _mods == null
? const Center(child: CircularProgressIndicator())
: _mods!.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('索引为空,先点击「同步」'),
if (!widget.server.hasSsh)
const Padding(
padding: EdgeInsets.all(8),
child: Text('(该服务器未配置 SSH,无法同步)',
style: TextStyle(color: Colors.red)),
),
],
),
)
: ListView.builder(
itemCount: _mods!.length,
itemBuilder: (context, i) {
final m = _mods![i];
return ListTile(
leading: const Icon(Icons.inventory_2_outlined),
title: Text('${m.name ?? m.fileName} ${m.version ?? ''}'),
subtitle: Text(
'${m.fileName} · 依赖 ${m.depends.length} · 软依赖 ${m.softDepends.length}',
),
trailing: const Icon(Icons.account_tree_outlined),
onTap: () => _showTree(m),
);
},
),
),
],
),
);
}
}
@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import '../mod_manager/mod_provider.dart';
/// 模组详情页:展示 jar 元数据(名称 / 版本 / 作者 / 依赖 / 描述)。
class ModDetailPage extends StatelessWidget {
final RemoteJarFile file;
final ModProvider provider;
const ModDetailPage({super.key, required this.file, required this.provider});
@override
Widget build(BuildContext context) {
final meta = file.meta;
return Scaffold(
appBar: AppBar(title: Text(file.fileName)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
ListTile(
leading: const Icon(Icons.extension),
title: Text(meta.name ?? '未知名称',
style: Theme.of(context).textTheme.titleLarge),
subtitle: Text('版本 ${meta.version ?? '未知'}'),
),
const Divider(),
_kv('文件名', file.fileName),
_kv('大小', _fmtSize(file.size)),
_kv('修改时间', '${file.mtime.toLocal()}'),
_kv('作者', meta.authors ?? '未知'),
_kv('元数据来源', meta.source),
if (meta.description != null) _kv('描述', meta.description!),
const Divider(),
Text('硬依赖', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
if (meta.depends.isEmpty)
const Text('无')
else
Wrap(
spacing: 6,
children: meta.depends
.map((d) => Chip(label: Text(d)))
.toList(),
),
const SizedBox(height: 12),
Text('软依赖', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
if (meta.softDepends.isEmpty)
const Text('无')
else
Wrap(spacing: 6, children: meta.softDepends.map((d) => Chip(label: Text(d))).toList()),
],
),
);
}
Widget _kv(String k, String v) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 96, child: Text(k, style: const TextStyle(fontWeight: FontWeight.w600))),
Expanded(child: Text(v)),
],
),
);
String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
}
+254
View File
@@ -0,0 +1,254 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../dashboard/server_picker_bar.dart';
import 'mod_provider.dart';
import 'mod_detail_page.dart';
import 'dependency_tree_page.dart';
/// 模组/插件管理页:列出服务器 mods / plugins 目录中的 jar 文件,
/// 支持上传 / 删除 / 重命名 / 查看详情(M1)。
class ModListPage extends StatefulWidget {
const ModListPage({super.key});
@override
State<ModListPage> createState() => _ModListPageState();
}
class _ModListPageState extends State<ModListPage>
with AutomaticKeepAliveClientMixin {
ModProvider? _provider;
@override
bool get wantKeepAlive => true;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final server = context.read<SelectedServerHolder>().server;
if (server != null && (_provider == null || _provider!.server?.id != server.id)) {
_disposeProvider();
final p = ModProvider();
_provider = p;
p.open(server);
}
}
@override
void dispose() {
_disposeProvider();
super.dispose();
}
void _disposeProvider() {
_provider?.disconnect();
_provider?.dispose();
_provider = null;
}
@override
Widget build(BuildContext context) {
super.build(context);
final server = context.watch<SelectedServerHolder>().server;
if (server == null) {
return const Center(child: Text('请先在「服务器」页选择一台服务器'));
}
if (!server.hasSsh) {
return _NoSshHint(serverName: server.name);
}
final p = _provider;
if (p == null) return const SizedBox.shrink();
return ChangeNotifierProvider<ModProvider>.value(
value: p,
child: Consumer<ModProvider>(builder: (context, mod, _) {
return Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: const Text('模组管理'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: mod.loading ? null : mod.refresh,
tooltip: '刷新',
),
IconButton(
icon: const Icon(Icons.account_tree_outlined),
tooltip: '依赖仓库',
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => DependencyTreePage(server: server),
),
),
),
],
),
body: Column(
children: [
// mods / plugins 切换 + 排序
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
children: [
SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'mods', label: Text('mods')),
ButtonSegment(value: 'plugins', label: Text('plugins')),
],
selected: {mod.currentDir},
onSelectionChanged: (s) =>
mod.open(server, dir: s.first),
),
const Spacer(),
PopupMenuButton<ModSortMode>(
icon: const Icon(Icons.sort),
onSelected: (m) => mod.setSortMode(m),
itemBuilder: (_) => const [
PopupMenuItem(value: ModSortMode.name, child: Text('按名称')),
PopupMenuItem(value: ModSortMode.size, child: Text('按大小')),
PopupMenuItem(value: ModSortMode.mtime, child: Text('按修改时间')),
],
),
],
),
),
if (mod.loading) const LinearProgressIndicator(),
if (mod.error != null)
Padding(
padding: const EdgeInsets.all(12),
child: Text('加载失败:${mod.error}',
style: TextStyle(color: Theme.of(context).colorScheme.error)),
),
Expanded(
child: mod.files.isEmpty && !mod.loading
? const Center(child: Text('目录下没有 .jar 文件'))
: ListView.builder(
itemCount: mod.files.length,
itemBuilder: (context, i) {
final f = mod.files[i];
return ListTile(
leading: const Icon(Icons.extension_outlined),
title: Text(f.fileName),
subtitle: Text(
'${f.meta.name ?? '未知'} ${f.meta.version ?? ''}'
' · ${_fmtSize(f.size)}',
),
trailing: PopupMenuButton<String>(
onSelected: (a) => _onAction(context, mod, f, a),
itemBuilder: (_) => const [
PopupMenuItem(value: 'detail', child: Text('详情')),
PopupMenuItem(value: 'rename', child: Text('重命名')),
PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ModDetailPage(file: f, provider: mod),
),
),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
icon: const Icon(Icons.upload_file),
label: const Text('上传 jar'),
onPressed: mod.loading ? null : () => _upload(context, mod),
),
);
}),
);
}
Future<void> _upload(BuildContext context, ModProvider mod) async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jar'],
);
if (result == null || result.files.single.path == null) return;
try {
await mod.uploadJar(result.files.single.path!);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('上传失败:$e')));
}
}
}
Future<void> _onAction(
BuildContext context, ModProvider mod, RemoteJarFile f, String action) async {
switch (action) {
case 'delete':
final ok = await showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
title: const Text('确认删除'),
content: Text('确定要删除 ${f.fileName} 吗?此操作不可恢复。'),
actions: [
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
],
),
);
if (ok == true) await mod.deleteJar(f.fileName);
break;
case 'rename':
final ctrl = TextEditingController(text: f.fileName);
final newName = await showDialog<String>(
context: context,
builder: (_) => AlertDialog(
title: const Text('重命名'),
content: TextField(controller: ctrl, autofocus: true),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(context, ctrl.text.trim()),
child: const Text('确定')),
],
),
);
if (newName != null && newName.isNotEmpty && newName != f.fileName) {
await mod.renameJar(f.fileName, newName);
}
break;
}
}
String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
}
}
class _NoSshHint extends StatelessWidget {
final String serverName;
const _NoSshHint({required this.serverName});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.no_encryption_outlined, size: 56),
const SizedBox(height: 12),
Text('$serverName 未配置 SSH'),
const SizedBox(height: 8),
const Text(
'模组管理需要 SSH 连接。请在「服务器」页编辑该服务器,\n开启 SSH 并填写用户名和密码。',
textAlign: TextAlign.center,
),
],
),
),
);
}
}
+176
View File
@@ -0,0 +1,176 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import '../../core/services/jar_metadata.dart';
import '../../core/services/sftp_service.dart';
import '../../providers/server_provider.dart';
enum ModSortMode { name, size, mtime }
/// 模组/插件管理状态:通过 SFTP 列出 mods/plugins 目录的 jar 文件,
/// 本地缓存元数据解析结果。
class ModProvider extends ChangeNotifier {
ServerConfig? server;
String currentDir = 'mods'; // mods | plugins
final Map<String, RemoteJarFile> _files = {};
bool loading = false;
String? error;
ModSortMode sortMode = ModSortMode.name;
void setSortMode(ModSortMode mode) {
sortMode = mode;
notifyListeners();
}
final SftpService _sftp = SftpService();
List<RemoteJarFile> get files {
final list = _files.values.toList();
list.sort((a, b) => switch (sortMode) {
ModSortMode.name => a.fileName.toLowerCase().compareTo(b.fileName.toLowerCase()),
ModSortMode.size => b.size.compareTo(a.size),
ModSortMode.mtime => b.mtime.compareTo(a.mtime),
});
return list;
}
Future<void> open(ServerConfig s, {String dir = 'mods'}) async {
server = s;
currentDir = dir;
await refresh();
}
String get _remoteBase {
final user = server!.sshUser;
final home = user == 'root' ? '/root' : '/home/$user';
return '$home/$currentDir';
}
Future<void> refresh() async {
final s = server;
if (s == null || !s.hasSsh) return;
loading = true;
error = null;
notifyListeners();
try {
await _sftp.connect(s);
final items = await _sftp.listDir(_remoteBase);
_files.clear();
for (final item in items) {
if (item.attr.isDirectory || !item.filename.endsWith('.jar')) continue;
_files[item.filename] = RemoteJarFile(
fileName: item.filename,
remotePath: '$_remoteBase/${item.filename}',
size: item.attr.size ?? 0,
mtime: DateTime.fromMillisecondsSinceEpoch((item.attr.modifyTime ?? 0) * 1000),
);
}
// 后台解析元数据(复用本地缓存)
final cacheDir = await _cacheDir();
for (final f in _files.values) {
final meta = await _metadataFor(f, cacheDir);
f.meta = meta;
}
loading = false;
notifyListeners();
} catch (e) {
error = e.toString();
loading = false;
notifyListeners();
}
}
/// 首次进入时下载 jar 解析元数据并缓存到本地,之后按 (name,size,mtime) 复用。
Future<JarMetadata> _metadataFor(RemoteJarFile f, Directory cacheDir) async {
final cacheFile = File('${cacheDir.path}/${f.cacheKey}.meta.json');
if (await cacheFile.exists()) {
try {
return JarMetaCache.fromJsonString(await cacheFile.readAsString());
} catch (_) {}
}
try {
final tmp = File('${cacheDir.path}/${f.cacheKey}.jar');
await _sftp.download(f.remotePath, tmp.path);
final meta = JarMetadata.parse(tmp.path);
await tmp.delete();
await cacheFile.writeAsString(meta.toJsonString());
return meta;
} catch (_) {
return JarMetadata.empty;
}
}
Future<Directory> _cacheDir() async {
final base = await getApplicationDocumentsDirectory();
final dir = Directory('${base.path}/jar_meta_cache');
if (!await dir.exists()) await dir.create(recursive: true);
return dir;
}
/// 上传本地 jar。
Future<void> uploadJar(String localPath) async {
final name = localPath.split(Platform.pathSeparator).last;
await _sftp.upload(localPath, '$_remoteBase/$name');
await refresh();
}
/// 删除远程 jar。
Future<void> deleteJar(String fileName) async {
await _sftp.delete('$_remoteBase/$fileName');
_files.remove(fileName);
notifyListeners();
}
/// 重命名远程 jar。
Future<void> renameJar(String oldName, String newName) async {
await _sftp.rename('$_remoteBase/$oldName', newName);
await refresh();
}
Future<void> disconnect() => _sftp.disconnect();
}
/// 远程 jar 文件描述。
class RemoteJarFile {
final String fileName;
final String remotePath;
final int size;
final DateTime mtime;
JarMetadata meta = JarMetadata.empty;
RemoteJarFile({
required this.fileName,
required this.remotePath,
required this.size,
required this.mtime,
});
String get cacheKey =>
'${fileName.hashCode}_${size}_${mtime.millisecondsSinceEpoch ~/ 1000}';
}
extension JarMetaCache on JarMetadata {
String toJsonString() => jsonEncode({
'name': name,
'version': version,
'authors': authors,
'description': description,
'depends': depends,
'softDepends': softDepends,
'source': source,
});
static JarMetadata fromJsonString(String s) {
final m = jsonDecode(s) as Map<String, dynamic>;
return JarMetadata(
name: m['name'],
version: m['version'],
authors: m['authors'],
description: m['description'],
depends: List<String>.from(m['depends'] ?? const []),
softDepends: List<String>.from(m['softDepends'] ?? const []),
source: m['source'] ?? 'cache',
);
}
}