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,37 @@
|
||||
# This is a generated file; do not edit or check into version control.
|
||||
file_picker=/root/.pub-cache/hosted/pub.flutter-io.cn/file_picker-8.3.7/
|
||||
file_selector_linux=/root/.pub-cache/hosted/pub.flutter-io.cn/file_selector_linux-0.9.3+2/
|
||||
file_selector_macos=/root/.pub-cache/hosted/pub.flutter-io.cn/file_selector_macos-0.9.4+2/
|
||||
file_selector_windows=/root/.pub-cache/hosted/pub.flutter-io.cn/file_selector_windows-0.9.3+4/
|
||||
flutter_plugin_android_lifecycle=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_plugin_android_lifecycle-2.0.26/
|
||||
flutter_secure_storage=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_secure_storage-9.2.4/
|
||||
flutter_secure_storage_linux=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_secure_storage_linux-1.2.3/
|
||||
flutter_secure_storage_macos=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_secure_storage_macos-3.1.3/
|
||||
flutter_secure_storage_web=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_secure_storage_web-1.2.1/
|
||||
flutter_secure_storage_windows=/root/.pub-cache/hosted/pub.flutter-io.cn/flutter_secure_storage_windows-3.1.2/
|
||||
image_picker=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker-1.1.2/
|
||||
image_picker_android=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_android-0.8.12+21/
|
||||
image_picker_for_web=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_for_web-3.0.6/
|
||||
image_picker_ios=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_ios-0.8.12+2/
|
||||
image_picker_linux=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_linux-0.2.1+2/
|
||||
image_picker_macos=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_macos-0.2.1+2/
|
||||
image_picker_windows=/root/.pub-cache/hosted/pub.flutter-io.cn/image_picker_windows-0.2.1+1/
|
||||
package_info_plus=/root/.pub-cache/hosted/pub.flutter-io.cn/package_info_plus-8.3.1/
|
||||
path_provider=/root/.pub-cache/hosted/pub.flutter-io.cn/path_provider-2.1.5/
|
||||
path_provider_android=/root/.pub-cache/hosted/pub.flutter-io.cn/path_provider_android-2.2.15/
|
||||
path_provider_foundation=/root/.pub-cache/hosted/pub.flutter-io.cn/path_provider_foundation-2.4.1/
|
||||
path_provider_linux=/root/.pub-cache/hosted/pub.flutter-io.cn/path_provider_linux-2.2.1/
|
||||
path_provider_windows=/root/.pub-cache/hosted/pub.flutter-io.cn/path_provider_windows-2.3.0/
|
||||
shared_preferences=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences-2.5.3/
|
||||
shared_preferences_android=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences_android-2.4.7/
|
||||
shared_preferences_foundation=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences_foundation-2.5.4/
|
||||
shared_preferences_linux=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences_linux-2.4.1/
|
||||
shared_preferences_web=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences_web-2.4.3/
|
||||
shared_preferences_windows=/root/.pub-cache/hosted/pub.flutter-io.cn/shared_preferences_windows-2.4.1/
|
||||
sqflite=/root/.pub-cache/hosted/pub.flutter-io.cn/sqflite-2.4.1/
|
||||
sqflite_android=/root/.pub-cache/hosted/pub.flutter-io.cn/sqflite_android-2.4.0/
|
||||
sqflite_darwin=/root/.pub-cache/hosted/pub.flutter-io.cn/sqflite_darwin-2.4.1+1/
|
||||
video_player=/root/.pub-cache/hosted/pub.flutter-io.cn/video_player-2.9.5/
|
||||
video_player_android=/root/.pub-cache/hosted/pub.flutter-io.cn/video_player_android-2.7.16/
|
||||
video_player_avfoundation=/root/.pub-cache/hosted/pub.flutter-io.cn/video_player_avfoundation-2.7.1/
|
||||
video_player_web=/root/.pub-cache/hosted/pub.flutter-io.cn/video_player_web-2.3.5/
|
||||
@@ -22,7 +22,17 @@ ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。
|
||||
| 控制台 | 快速命令预设
|
||||
| 主题 | 浅色/深色/跟随系统
|
||||
| 壁纸 | 自定义壁纸
|
||||
| 数据 | 加密存储
|
||||
| 数据 | 加密存储 | 模组管理 | SFTP 浏览 mods/plugins 目录 | ✅ v2.0 新增 |
|
||||
| 模组管理 | 上传/删除/重命名 jar | ✅ v2.0 新增 |
|
||||
| 模组管理 | 解析 fabric.mod.json / plugin.yml 元数据(名称/版本/作者/依赖) | ✅ v2.0 新增 |
|
||||
| 下载中心 | Modrinth 搜索与下载(支持 MC 版本/加载器筛选) | ✅ v2.0 新增 |
|
||||
| 下载中心 | 多任务并发队列(默认 3)、断点续传、失败指数退避重试 | ✅ v2.0 新增 |
|
||||
| 下载中心 | 镜像线路(MCIM 国内镜像 / 自定义)+ 一键测速自动选线 | ✅ v2.0 新增 |
|
||||
| 下载中心 | 下载完成自动经 SFTP 上传到服务器对应目录 | ✅ v2.0 新增 |
|
||||
| 终端 | SSH Shell(xterm 终端、快捷键栏、多会话标签、断线自动重连) | ✅ v2.0 新增 |
|
||||
| UI | Dashboard 卡片式首页 + 底部导航(服务器/控制台/玩家/模组/终端/我的) | ✅ v2.0 新增 |
|
||||
| UI | 控制台日志级别着色(INFO 绿 / WARN 黄 / ERROR 红) | ✅ v2.0 新增 |
|
||||
| 依赖仓库 | SQLite 依赖索引 + 增量同步 + 依赖树查询 + 缺失依赖一键补齐 + 重复检测 | ✅ v2.0 新增 |
|
||||
|
||||
技术栈
|
||||
|
||||
@@ -31,8 +41,8 @@ ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。
|
||||
| **框架** | Flutter 3.x |
|
||||
| **语言** | Dart 3.x |
|
||||
| **目标平台** | Android 7.0+ / Web |
|
||||
| **通信协议** | RCON (Minecraft 远程控制协议) |
|
||||
| **本地存储** | Shared Preferences + Flutter Secure Storage |
|
||||
| **通信协议** | RCON (Minecraft 远程控制协议) + SSH/SFTP (dartssh2) |
|
||||
| **本地存储** | Shared Preferences + Flutter Secure Storage + SQLite (依赖索引) |
|
||||
| **状态管理** | Provider |
|
||||
| **主题** | Material 3 |
|
||||
|
||||
|
||||
+9
-3
@@ -9,9 +9,12 @@ import 'core/utils/update_service.dart';
|
||||
import 'core/widgets/background_widget.dart';
|
||||
import 'providers/wallpaper_provider.dart';
|
||||
import 'core/widgets/user_agreement_dialog.dart'; // 新增
|
||||
import 'features/server_list/server_list_page.dart';
|
||||
import 'features/shell/main_shell.dart';
|
||||
import 'providers/theme_provider.dart';
|
||||
import 'providers/server_provider.dart';
|
||||
import 'providers/rcon_provider.dart';
|
||||
import 'providers/download_provider.dart';
|
||||
import 'features/dashboard/server_picker_bar.dart';
|
||||
|
||||
/// 全局导航 Key
|
||||
final navigatorKey = GlobalKey<NavigatorState>();
|
||||
@@ -94,6 +97,9 @@ class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => ThemeProvider()),
|
||||
ChangeNotifierProvider(create: (_) => ServerProvider()),
|
||||
ChangeNotifierProvider(create: (_) => RconProvider()),
|
||||
ChangeNotifierProvider(create: (_) => DownloadProvider()),
|
||||
ChangeNotifierProvider(create: (_) => SelectedServerHolder()),
|
||||
// 复用 main() 中预加载的实例,不能在这里 create 一个新的
|
||||
ChangeNotifierProvider<WallpaperProvider>.value(
|
||||
value: widget.wallpaperProvider,
|
||||
@@ -118,7 +124,7 @@ class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
Locale('zh', 'CN'),
|
||||
Locale('en', 'US'),
|
||||
],
|
||||
home: const ServerListPage(),
|
||||
home: const MainShell(),
|
||||
builder: (context, child) {
|
||||
child ??= const SizedBox.shrink();
|
||||
return BackgroundWidget(
|
||||
@@ -131,7 +137,7 @@ class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
// withOpacity 在新版 Flutter 已废弃,统一用 withValues
|
||||
color: Colors.black.withValues(alpha: 0.6),
|
||||
color: Colors.black.withOpacity(0.6),
|
||||
child: Center(
|
||||
child: UserAgreementDialog(onAgree: _onAgree),
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -310,7 +310,7 @@ class BackgroundWidgetState extends State<BackgroundWidget>
|
||||
),
|
||||
|
||||
if (showingVideo)
|
||||
IgnorePointer(child: ColoredBox(color: Colors.black.withValues(alpha: 0.3))),
|
||||
IgnorePointer(child: ColoredBox(color: Colors.black.withOpacity(0.3))),
|
||||
|
||||
_wrapWithTransparentTheme(widget.child),
|
||||
],
|
||||
|
||||
@@ -166,7 +166,7 @@ class _ConsolePageState extends State<ConsolePage> {
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(12),
|
||||
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
|
||||
color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
itemCount: _outputLines.length,
|
||||
@@ -181,7 +181,8 @@ class _ConsolePageState extends State<ConsolePage> {
|
||||
? theme.colorScheme.error
|
||||
: line.isCommand
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurface,
|
||||
// 按日志级别前缀着色:WARN 黄 / ERROR 红 / INFO 绿
|
||||
: _logLevelColor(line.text) ?? theme.colorScheme.onSurface,
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -242,6 +243,22 @@ class _LogLine {
|
||||
_LogLine({required this.text, this.isCommand = false, this.isError = false});
|
||||
}
|
||||
|
||||
/// 按日志前缀识别级别并返回对应颜色(INFO 绿 / WARN 黄 / ERROR 红)。
|
||||
Color? _logLevelColor(String text) {
|
||||
final upper = text.toUpperCase();
|
||||
// 兼容 [WARN]、[WARN/...]、WARN : 等常见格式
|
||||
if (upper.contains('ERROR') || upper.contains('FATAL') || upper.contains('SEVERE')) {
|
||||
return Colors.red;
|
||||
}
|
||||
if (upper.contains(RegExp(r'\bWARN(ING)?\b'))) {
|
||||
return Colors.orange;
|
||||
}
|
||||
if (upper.contains(RegExp(r'\bINFO\b'))) {
|
||||
return Colors.green;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 快速命令预设栏:横向滚动的预设按钮 + 管理入口。
|
||||
class _PresetBar extends StatelessWidget {
|
||||
final List<QuickCommandPreset> presets;
|
||||
@@ -273,7 +290,7 @@ class _PresetBar extends StatelessWidget {
|
||||
label: Text(preset.label),
|
||||
labelStyle: TextStyle(fontSize: 13, color: theme.colorScheme.onSecondaryContainer),
|
||||
visualDensity: VisualDensity.compact,
|
||||
backgroundColor: theme.colorScheme.secondaryContainer.withValues(alpha: 0.5),
|
||||
backgroundColor: theme.colorScheme.secondaryContainer.withOpacity(0.5),
|
||||
onPressed: () => onSend(preset.command),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../providers/rcon_provider.dart';
|
||||
import '../../providers/server_provider.dart';
|
||||
import '../download/download_page.dart';
|
||||
import '../mod_manager/mod_list_page.dart';
|
||||
import '../terminal/terminal_page.dart';
|
||||
import 'server_picker_bar.dart';
|
||||
|
||||
/// 服务器 Dashboard:卡片式布局展示选中服务器的
|
||||
/// 在线状态 / 延迟 / 在线人数 / TPS / 磁盘(后续 Shell 采集)+ 快捷入口(M4)。
|
||||
class DashboardPage extends StatefulWidget {
|
||||
const DashboardPage({super.key});
|
||||
|
||||
@override
|
||||
State<DashboardPage> createState() => _DashboardPageState();
|
||||
}
|
||||
|
||||
class _DashboardPageState extends State<DashboardPage> {
|
||||
Map<String, ServerStatus> _status = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_refreshAll();
|
||||
}
|
||||
|
||||
Future<void> _refreshAll() async {
|
||||
final rcon = context.read<RconProvider>();
|
||||
final servers = context.read<ServerProvider>().servers;
|
||||
final map = <String, ServerStatus>{};
|
||||
for (final s in servers) {
|
||||
map[s.id] = await rcon.checkStatus(s);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() => _status = map);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final servers = context.watch<ServerProvider>().servers;
|
||||
final holder = context.watch<SelectedServerHolder>();
|
||||
final selected = holder.server ?? (servers.isNotEmpty ? servers.first : null);
|
||||
final status = selected != null ? _status[selected.id] : null;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
appBar: AppBar(
|
||||
title: const Text('ZV Manager'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: '刷新状态',
|
||||
onPressed: _refreshAll,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: servers.isEmpty
|
||||
? const Center(child: Text('还没有服务器,去「服务器」页添加吧'))
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(12),
|
||||
children: [
|
||||
// 服务器选择器
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.dns),
|
||||
title: Text(selected?.name ?? '未选择'),
|
||||
subtitle: Text('${selected?.host ?? '-'}:${selected?.port ?? '-'}'),
|
||||
trailing: DropdownButton<ServerConfig>(
|
||||
underline: const SizedBox.shrink(),
|
||||
hint: const Text('切换'),
|
||||
items: servers
|
||||
.map((s) => DropdownMenuItem(value: s, child: Text(s.name)))
|
||||
.toList(),
|
||||
onChanged: (s) {
|
||||
holder.select(s);
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 状态卡片
|
||||
GridView.count(
|
||||
crossAxisCount: 2,
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
childAspectRatio: 1.8,
|
||||
mainAxisSpacing: 8,
|
||||
crossAxisSpacing: 8,
|
||||
children: [
|
||||
_statusCard(
|
||||
icon: status?.online == true ? Icons.circle : Icons.circle_outlined,
|
||||
color: status?.online == true ? Colors.green : Colors.red,
|
||||
label: status?.online == true ? '在线' : '离线',
|
||||
sub: status == null ? '—' : '${status.latencyMs}ms',
|
||||
),
|
||||
_statusCard(
|
||||
icon: Icons.person,
|
||||
color: Colors.blue,
|
||||
label: '在线人数',
|
||||
sub: '${status?.playerCount ?? 0}',
|
||||
),
|
||||
_statusCard(
|
||||
icon: Icons.speed,
|
||||
color: Colors.orange,
|
||||
label: 'TPS',
|
||||
sub: status?.tps?.toStringAsFixed(1) ?? '—',
|
||||
),
|
||||
_statusCard(
|
||||
icon: Icons.storage,
|
||||
color: Colors.purple,
|
||||
label: '磁盘',
|
||||
sub: '需 SSH 终端',
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 服务器卡片列表(点击选中)
|
||||
Text('服务器', style: Theme.of(context).textTheme.titleMedium),
|
||||
...servers.map((s) {
|
||||
final st = _status[s.id];
|
||||
final isSel = selected?.id == s.id;
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: ListTile(
|
||||
selected: isSel,
|
||||
leading: Icon(
|
||||
st?.online == true ? Icons.circle : Icons.circle_outlined,
|
||||
color: st?.online == true ? Colors.green : Colors.red,
|
||||
),
|
||||
title: Text(s.name),
|
||||
subtitle: Text(
|
||||
st?.online == true
|
||||
? '在线 · ${st!.latencyMs}ms · ${st.playerCount} 人'
|
||||
'${st.tps != null ? " · TPS ${st.tps!.toStringAsFixed(1)}" : ""}'
|
||||
: '离线',
|
||||
),
|
||||
trailing: isSel ? const Icon(Icons.check) : null,
|
||||
onTap: () {
|
||||
holder.select(s);
|
||||
setState(() {});
|
||||
},
|
||||
),
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 8),
|
||||
// 快捷入口
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(Icons.download_outlined),
|
||||
title: const Text('下载中心'),
|
||||
subtitle: const Text('Modrinth 搜索 · 镜像加速'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const DownloadPage()),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.terminal),
|
||||
title: const Text('远程终端'),
|
||||
subtitle: const Text('SSH Shell'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const TerminalPage()),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.extension_outlined),
|
||||
title: const Text('模组管理'),
|
||||
subtitle: const Text('上传 / 删除 / 查看依赖'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const ModListPage()),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _statusCard({
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required String label,
|
||||
required String sub,
|
||||
}) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
Icon(icon, color: color, size: 18),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
]),
|
||||
const SizedBox(height: 6),
|
||||
Text(sub, style: Theme.of(context).textTheme.headlineSmall),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../../providers/server_provider.dart';
|
||||
|
||||
/// 跨页签共享的「当前选中服务器」。
|
||||
/// Dashboard / 模组 / 终端 / 下载上传目标等页签共用此状态。
|
||||
class SelectedServerHolder extends ChangeNotifier {
|
||||
ServerConfig? _server;
|
||||
|
||||
ServerConfig? get server => _server;
|
||||
|
||||
void select(ServerConfig? s) {
|
||||
_server = s;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../core/services/modrinth_api.dart';
|
||||
import '../../providers/download_provider.dart';
|
||||
import '../../core/services/download_manager.dart';
|
||||
|
||||
/// 下载中心:Modrinth 搜索 + 镜像线路选择 + 下载任务队列(M2)。
|
||||
class DownloadPage extends StatefulWidget {
|
||||
const DownloadPage({super.key});
|
||||
|
||||
@override
|
||||
State<DownloadPage> createState() => _DownloadPageState();
|
||||
}
|
||||
|
||||
class _DownloadPageState extends State<DownloadPage> {
|
||||
final _searchCtrl = TextEditingController();
|
||||
List<ModrinthSearchResult>? _results;
|
||||
bool _searching = false;
|
||||
String _projectType = 'mod';
|
||||
String? _mcVersion;
|
||||
String? _loader;
|
||||
|
||||
static const _mcVersions = ['1.21.4', '1.21.1', '1.20.6', '1.20.4', '1.20.1', '1.19.4', '1.18.2', '1.16.5'];
|
||||
static const _loaders = ['fabric', 'forge', 'quilt', 'neoforge', 'paper', 'bukkit', 'spigot'];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<DownloadProvider>().init();
|
||||
}
|
||||
|
||||
Future<void> _search() async {
|
||||
final query = _searchCtrl.text.trim();
|
||||
if (query.isEmpty) return;
|
||||
setState(() {
|
||||
_searching = true;
|
||||
_results = null;
|
||||
});
|
||||
try {
|
||||
final dp = context.read<DownloadProvider>();
|
||||
final results = await dp.search(
|
||||
query,
|
||||
projectType: _projectType,
|
||||
mcVersion: _mcVersion,
|
||||
loader: _loader,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_results = results;
|
||||
_searching = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _searching = false);
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('搜索失败:$e')));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dp = context.read<DownloadProvider>();
|
||||
return DefaultTabController(
|
||||
length: 2,
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
appBar: AppBar(
|
||||
title: const Text('下载中心'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.speed),
|
||||
tooltip: '镜像线路:${dp.mirror.currentName}',
|
||||
onPressed: _showMirrorDialog,
|
||||
),
|
||||
],
|
||||
bottom: const TabBar(tabs: [Tab(text: '搜索下载'), Tab(text: '任务队列')]),
|
||||
),
|
||||
body: TabBarView(children: [_buildSearchTab(), _buildQueueTab(dp)]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSearchTab() {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _searchCtrl,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '搜索 Modrinth 模组/插件,如 sodium',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
onSubmitted: (_) => _search(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(onPressed: _searching ? null : _search, child: const Text('搜索')),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
_dropdown<String>(
|
||||
value: _projectType,
|
||||
items: const {'mod': '模组', 'plugin': '插件'},
|
||||
onChanged: (v) => setState(() => _projectType = v!),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_dropdown<String>(
|
||||
value: _mcVersion,
|
||||
hint: 'MC 版本',
|
||||
items: {for (final v in _mcVersions) v: v},
|
||||
onChanged: (v) => setState(() => _mcVersion = v),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_dropdown<String>(
|
||||
value: _loader,
|
||||
hint: '加载器',
|
||||
items: {for (final v in _loaders) v: v},
|
||||
onChanged: (v) => setState(() => _loader = v),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _searching
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _results == null
|
||||
? const Center(child: Text('输入关键词开始搜索'))
|
||||
: _results!.isEmpty
|
||||
? const Center(child: Text('没有结果'))
|
||||
: ListView.builder(
|
||||
itemCount: _results!.length,
|
||||
itemBuilder: (context, i) {
|
||||
final r = _results![i];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.extension),
|
||||
title: Text(r.title),
|
||||
subtitle: Text(r.description, maxLines: 2, overflow: TextOverflow.ellipsis),
|
||||
trailing: Text('${r.downloads}',
|
||||
style: Theme.of(context).textTheme.bodySmall),
|
||||
onTap: () => _showVersionSheet(r),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _dropdown<T>({
|
||||
required T? value,
|
||||
required Map<String, String> items,
|
||||
String? hint,
|
||||
required ValueChanged<T?> onChanged,
|
||||
}) {
|
||||
return Expanded(
|
||||
child: DropdownButtonFormField<T>(
|
||||
value: value,
|
||||
isDense: true,
|
||||
decoration: InputDecoration(hintText: hint, border: const OutlineInputBorder(), isDense: true),
|
||||
items: items.entries
|
||||
.map((e) => DropdownMenuItem<T>(value: e.key as T, child: Text(e.value, overflow: TextOverflow.ellipsis)))
|
||||
.toList(),
|
||||
onChanged: onChanged,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 版本选择底部弹层。
|
||||
Future<void> _showVersionSheet(ModrinthSearchResult r) async {
|
||||
final dp = context.read<DownloadProvider>();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('正在获取版本列表...'), duration: Duration(seconds: 1)),
|
||||
);
|
||||
try {
|
||||
final versions = await dp.versions(r.projectId);
|
||||
if (!mounted) return;
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (_) => SafeArea(
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text('选择 ${r.title} 的版本', style: Theme.of(context).textTheme.titleMedium),
|
||||
),
|
||||
...versions.take(15).map((v) => ListTile(
|
||||
title: Text(v.versionNumber),
|
||||
subtitle: Text('${v.loaders.join('/')} · ${v.gameVersions.take(3).join(', ')}'),
|
||||
trailing: const Icon(Icons.download),
|
||||
onTap: () => _downloadVersion(v),
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('获取版本失败:$e')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _downloadVersion(ModrinthVersion v) async {
|
||||
Navigator.pop(context);
|
||||
final dp = context.read<DownloadProvider>();
|
||||
// 取主 jar 文件
|
||||
final files = v.files;
|
||||
if (files.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('该版本没有可用文件')));
|
||||
return;
|
||||
}
|
||||
final primary = files.firstWhere((f) => f['primary'] == true, orElse: () => files.first);
|
||||
final url = primary['url'] as String;
|
||||
final fileName = primary['filename'] as String;
|
||||
await dp.download(url: url, fileName: fileName, projectType: _projectType);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已加入下载队列:$fileName')));
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildQueueTab(DownloadProvider dp) {
|
||||
return AnimatedBuilder(
|
||||
animation: dp.manager,
|
||||
builder: (context, _) {
|
||||
final tasks = dp.manager.tasks;
|
||||
if (tasks.isEmpty) return const Center(child: Text('暂无下载任务'));
|
||||
return ListView.builder(
|
||||
itemCount: tasks.length,
|
||||
itemBuilder: (context, i) {
|
||||
final t = tasks[i];
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Text(t.fileName, overflow: TextOverflow.ellipsis)),
|
||||
_statusChip(t.status),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
LinearProgressIndicator(value: t.progress),
|
||||
const SizedBox(height: 6),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'${_fmt(t.receivedBytes)} / ${_fmt(t.totalBytes)}'
|
||||
'${t.status == DownloadStatus.running ? " · ${_fmt(t.speed)}/s" : ""}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const Spacer(),
|
||||
if (t.status == DownloadStatus.running)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.pause),
|
||||
tooltip: '暂停',
|
||||
onPressed: () => dp.manager.pause(t.id),
|
||||
),
|
||||
if (t.status == DownloadStatus.paused)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
tooltip: '继续',
|
||||
onPressed: () => dp.manager.resume(t.id),
|
||||
),
|
||||
if (t.status == DownloadStatus.failed)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.replay),
|
||||
tooltip: '重试',
|
||||
onPressed: () => dp.manager.retry(t.id),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: '取消',
|
||||
onPressed: () => dp.manager.cancel(t.id),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (t.error != null)
|
||||
Text(t.error!, style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _statusChip(DownloadStatus s) {
|
||||
final (label, color) = switch (s) {
|
||||
DownloadStatus.queued => ('排队中', Colors.grey),
|
||||
DownloadStatus.running => ('下载中', Colors.blue),
|
||||
DownloadStatus.paused => ('已暂停', Colors.orange),
|
||||
DownloadStatus.completed => ('已完成', Colors.green),
|
||||
DownloadStatus.failed => ('失败', Colors.red),
|
||||
DownloadStatus.canceled => ('已取消', Colors.grey),
|
||||
};
|
||||
return Chip(label: Text(label, style: const TextStyle(fontSize: 12)), backgroundColor: color.withOpacity(0.15), visualDensity: VisualDensity.compact);
|
||||
}
|
||||
|
||||
String _fmt(num bytes) {
|
||||
if (bytes < 1024) return '$bytes B';
|
||||
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
|
||||
return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
|
||||
}
|
||||
|
||||
Future<void> _showMirrorDialog() async {
|
||||
final dp = context.read<DownloadProvider>();
|
||||
final mirror = dp.mirror;
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (_) => StatefulBuilder(
|
||||
builder: (context, setDialogState) => AlertDialog(
|
||||
title: const Text('镜像线路'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
RadioListTile<String>(
|
||||
title: const Text('Modrinth 官方'),
|
||||
value: 'official',
|
||||
groupValue: mirror.currentId,
|
||||
onChanged: (v) async {
|
||||
await mirror.select(v!);
|
||||
setDialogState(() {});
|
||||
},
|
||||
),
|
||||
RadioListTile<String>(
|
||||
title: const Text('MCIM 国内镜像'),
|
||||
value: 'mcim',
|
||||
groupValue: mirror.currentId,
|
||||
onChanged: (v) async {
|
||||
await mirror.select(v!);
|
||||
setDialogState(() {});
|
||||
},
|
||||
),
|
||||
RadioListTile<String>(
|
||||
title: const Text('自定义镜像'),
|
||||
value: 'custom',
|
||||
groupValue: mirror.currentId,
|
||||
onChanged: (v) async {
|
||||
final ctrl = TextEditingController(text: mirror.customUrl);
|
||||
final url = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('自定义镜像地址'),
|
||||
content: TextField(controller: ctrl, decoration: const InputDecoration(hintText: 'https://your-mirror.example.com')),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(onPressed: () => Navigator.pop(context, ctrl.text.trim()), child: const Text('确定')),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (url != null && url.isNotEmpty) {
|
||||
await mirror.select('custom', customUrl: url);
|
||||
}
|
||||
setDialogState(() {});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
icon: const Icon(Icons.bolt),
|
||||
label: const Text('一键测速并选择最快线路'),
|
||||
onPressed: () async {
|
||||
await mirror.autoSelect();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已选择最快线路:${mirror.currentName}(${mirror.lastSpeedMs}ms)')),
|
||||
);
|
||||
}
|
||||
setDialogState(() {});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
FilledButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ class ServerCard extends StatelessWidget {
|
||||
|
||||
// 卡片底色跟随主题表面色,浮一层极淡的品牌色,避免纯白/纯黑显得生硬。
|
||||
final Color base = Color.alphaBlend(
|
||||
scheme.primary.withValues(alpha: online ? 0.06 : 0.02),
|
||||
scheme.primary.withOpacity(online ? 0.06 : 0.02),
|
||||
scheme.surface,
|
||||
);
|
||||
|
||||
@@ -102,13 +102,13 @@ class ServerCard extends StatelessWidget {
|
||||
color: base,
|
||||
border: Border.all(
|
||||
color: online
|
||||
? scheme.primary.withValues(alpha: 0.38)
|
||||
: scheme.outlineVariant.withValues(alpha: 0.55),
|
||||
? scheme.primary.withOpacity(0.38)
|
||||
: scheme.outlineVariant.withOpacity(0.55),
|
||||
width: online ? 1.4 : 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: online ? 0.08 : 0.04),
|
||||
color: Colors.black.withOpacity(online ? 0.08 : 0.04),
|
||||
blurRadius: online ? 18 : 10,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
@@ -158,9 +158,9 @@ class ServerCard extends StatelessWidget {
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: _statusColor.withValues(alpha: 0.13),
|
||||
color: _statusColor.withOpacity(0.13),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: _statusColor.withValues(alpha: 0.28)),
|
||||
border: Border.all(color: _statusColor.withOpacity(0.28)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -177,7 +177,7 @@ class ServerCard extends StatelessWidget {
|
||||
Text(
|
||||
'${latencyMs}ms',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: _statusColor.withValues(alpha: 0.75),
|
||||
color: _statusColor.withOpacity(0.75),
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
@@ -393,7 +393,7 @@ class _StatusDotState extends State<_StatusDot>
|
||||
color: widget.color,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: widget.color.withValues(alpha: glow),
|
||||
color: widget.color.withOpacity(glow),
|
||||
blurRadius: 10,
|
||||
spreadRadius: 3,
|
||||
),
|
||||
@@ -422,8 +422,8 @@ class _Pill extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bg = emphasized
|
||||
? color.withValues(alpha: 0.14)
|
||||
: color.withValues(alpha: 0.08);
|
||||
? color.withOpacity(0.14)
|
||||
: color.withOpacity(0.08);
|
||||
|
||||
final content = Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
|
||||
|
||||
@@ -17,6 +17,12 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
|
||||
late TextEditingController _portCtrl;
|
||||
late TextEditingController _passCtrl;
|
||||
bool _obscurePassword = true;
|
||||
// SSH 可选配置(模组管理 / 终端需要)
|
||||
bool _sshEnabled = false;
|
||||
bool _obscureSshPassword = true;
|
||||
late TextEditingController _sshPortCtrl;
|
||||
late TextEditingController _sshUserCtrl;
|
||||
late TextEditingController _sshPasswordCtrl;
|
||||
|
||||
bool get isEditing => widget.existingServer != null;
|
||||
|
||||
@@ -28,6 +34,10 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
|
||||
_hostCtrl = TextEditingController(text: s?.host ?? '');
|
||||
_portCtrl = TextEditingController(text: s?.port.toString() ?? '25575');
|
||||
_passCtrl = TextEditingController(text: s?.password ?? '');
|
||||
_sshEnabled = s?.sshEnabled ?? false;
|
||||
_sshPortCtrl = TextEditingController(text: s?.sshPort.toString() ?? '22');
|
||||
_sshUserCtrl = TextEditingController(text: s?.sshUser ?? '');
|
||||
_sshPasswordCtrl = TextEditingController(text: s?.sshPassword ?? '');
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -36,6 +46,9 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
|
||||
_hostCtrl.dispose();
|
||||
_portCtrl.dispose();
|
||||
_passCtrl.dispose();
|
||||
_sshPortCtrl.dispose();
|
||||
_sshUserCtrl.dispose();
|
||||
_sshPasswordCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -60,6 +73,10 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
|
||||
host: _hostCtrl.text.trim(),
|
||||
port: int.parse(_portCtrl.text.trim()),
|
||||
password: _passCtrl.text,
|
||||
sshEnabled: _sshEnabled,
|
||||
sshPort: int.tryParse(_sshPortCtrl.text.trim()) ?? 22,
|
||||
sshUser: _sshUserCtrl.text.trim(),
|
||||
sshPassword: _sshPasswordCtrl.text,
|
||||
);
|
||||
|
||||
Navigator.pop(context, server);
|
||||
@@ -111,6 +128,51 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) => _submit(),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('SSH 连接(可选)'),
|
||||
subtitle: const Text('用于模组插件管理与远程终端'),
|
||||
value: _sshEnabled,
|
||||
onChanged: (v) => setState(() => _sshEnabled = v),
|
||||
),
|
||||
if (_sshEnabled) ...[
|
||||
TextFormField(
|
||||
controller: _sshPortCtrl,
|
||||
decoration: const InputDecoration(labelText: 'SSH 端口', hintText: '默认 22'),
|
||||
keyboardType: TextInputType.number,
|
||||
validator: (v) {
|
||||
if (!_sshEnabled) return null;
|
||||
return _validatePort(v);
|
||||
},
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _sshUserCtrl,
|
||||
decoration: const InputDecoration(labelText: 'SSH 用户名', hintText: '例如 root'),
|
||||
validator: (v) => _sshEnabled ? _validateRequired(v, 'SSH 用户名') : null,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextFormField(
|
||||
controller: _sshPasswordCtrl,
|
||||
obscureText: _obscureSshPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'SSH 密码',
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscureSshPassword
|
||||
? Icons.visibility_off_outlined
|
||||
: Icons.visibility_outlined),
|
||||
onPressed: () =>
|
||||
setState(() => _obscureSshPassword = !_obscureSshPassword),
|
||||
),
|
||||
),
|
||||
validator: (v) => _sshEnabled ? _validateRequired(v, 'SSH 密码') : null,
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) => _submit(),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -265,9 +265,9 @@ class _EmptyState extends StatelessWidget {
|
||||
height: 84,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: scheme.primary.withValues(alpha: 0.08),
|
||||
color: scheme.primary.withOpacity(0.08),
|
||||
border: Border.all(
|
||||
color: scheme.primary.withValues(alpha: 0.18),
|
||||
color: scheme.primary.withOpacity(0.18),
|
||||
),
|
||||
),
|
||||
child: Icon(Icons.dns_outlined, size: 36, color: scheme.primary),
|
||||
|
||||
@@ -132,10 +132,10 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
|
||||
Future<void> _pickVideo() async {
|
||||
final result = await FilePicker.pickFile(type: FileType.video);
|
||||
final result = await FilePicker.platform.pickFiles(type: FileType.video);
|
||||
if (result == null) return;
|
||||
|
||||
final filePath = result.path;
|
||||
final filePath = result.files.single.path;
|
||||
if (filePath == null) return;
|
||||
|
||||
final path = await _saveFileToAssets(filePath, 'video');
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../core/utils/rcon_client.dart';
|
||||
import '../../providers/rcon_provider.dart';
|
||||
|
||||
import '../console/console_page.dart';
|
||||
import '../dashboard/dashboard_page.dart';
|
||||
import '../mod_manager/mod_list_page.dart';
|
||||
import '../player_management/player_list_page.dart';
|
||||
import '../settings/settings_page.dart';
|
||||
import '../terminal/terminal_page.dart';
|
||||
import '../dashboard/server_picker_bar.dart';
|
||||
|
||||
/// 主导航壳:底部导航「服务器 · 控制台 · 玩家 · 模组 · 终端 · 我的」(M4)。
|
||||
class MainShell extends StatefulWidget {
|
||||
const MainShell({super.key});
|
||||
|
||||
@override
|
||||
State<MainShell> createState() => _MainShellState();
|
||||
}
|
||||
|
||||
class _MainShellState extends State<MainShell> {
|
||||
int _index = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final pages = [
|
||||
const DashboardPage(),
|
||||
const _ConsoleTab(),
|
||||
const _PlayerTab(),
|
||||
const ModListPage(),
|
||||
const TerminalPage(),
|
||||
const SettingsPage(),
|
||||
];
|
||||
return Scaffold(
|
||||
body: IndexedStack(index: _index, children: pages),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: _index,
|
||||
onDestinationSelected: (i) => setState(() => _index = i),
|
||||
destinations: const [
|
||||
NavigationDestination(icon: Icon(Icons.dns_outlined), selectedIcon: Icon(Icons.dns), label: '服务器'),
|
||||
NavigationDestination(icon: Icon(Icons.terminal_outlined), selectedIcon: Icon(Icons.terminal), label: '控制台'),
|
||||
NavigationDestination(icon: Icon(Icons.group_outlined), selectedIcon: Icon(Icons.group), label: '玩家'),
|
||||
NavigationDestination(icon: Icon(Icons.extension_outlined), selectedIcon: Icon(Icons.extension), label: '模组'),
|
||||
NavigationDestination(icon: Icon(Icons.terminal), selectedIcon: Icon(Icons.terminal), label: '终端'),
|
||||
NavigationDestination(icon: Icon(Icons.settings_outlined), selectedIcon: Icon(Icons.settings), label: '我的'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 控制台页签:选中服务器后通过 RconProvider 拿连接。
|
||||
class _ConsoleTab extends StatelessWidget {
|
||||
const _ConsoleTab();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final holder = context.watch<SelectedServerHolder>();
|
||||
final rcon = context.read<RconProvider>();
|
||||
final server = holder.server;
|
||||
if (server == null) {
|
||||
return const _NeedServerHint();
|
||||
}
|
||||
return FutureBuilder<RconClient>(
|
||||
future: rcon.getClient(server),
|
||||
builder: (context, snap) {
|
||||
if (snap.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snap.hasError) {
|
||||
return Center(child: Text('RCON 连接失败:${snap.error}'));
|
||||
}
|
||||
return ConsolePage(rconClient: snap.data!);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 玩家页签。
|
||||
class _PlayerTab extends StatelessWidget {
|
||||
const _PlayerTab();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final holder = context.watch<SelectedServerHolder>();
|
||||
final rcon = context.read<RconProvider>();
|
||||
final server = holder.server;
|
||||
if (server == null) {
|
||||
return const _NeedServerHint();
|
||||
}
|
||||
return FutureBuilder<RconClient>(
|
||||
future: rcon.getClient(server),
|
||||
builder: (context, snap) {
|
||||
if (snap.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snap.hasError) {
|
||||
return Center(child: Text('RCON 连接失败:${snap.error}'));
|
||||
}
|
||||
return PlayerListPage(rconClient: snap.data!);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NeedServerHint extends StatelessWidget {
|
||||
const _NeedServerHint();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Center(child: Text('请先在「服务器」页选择一台服务器'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
import 'package:xterm/ui.dart' show TerminalView;
|
||||
import '../../core/services/ssh_shell_service.dart';
|
||||
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
|
||||
/// SSH 终端页:xterm 终端 + 快捷键栏 + 多服务器会话标签(M3)。
|
||||
class TerminalPage extends StatefulWidget {
|
||||
const TerminalPage({super.key});
|
||||
|
||||
@override
|
||||
State<TerminalPage> createState() => _TerminalPageState();
|
||||
}
|
||||
|
||||
class _TerminalPageState extends State<TerminalPage>
|
||||
with AutomaticKeepAliveClientMixin {
|
||||
final Map<String, _Session> _sessions = {};
|
||||
String? _activeId;
|
||||
List<ServerConfig> _sshServers = const [];
|
||||
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
final servers = context.watch<ServerProvider>().servers.where((s) => s.hasSsh).toList();
|
||||
_sshServers = servers;
|
||||
if (servers.isNotEmpty && (_activeId == null || !_sessions.containsKey(_activeId))) {
|
||||
_openSession(servers.first);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final s in _sessions.values) {
|
||||
s.service.disconnect();
|
||||
s.terminal.onOutput = null;
|
||||
}
|
||||
_sessions.clear();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _openSession(ServerConfig server) async {
|
||||
if (_sessions.containsKey(server.id)) {
|
||||
setState(() => _activeId = server.id);
|
||||
return;
|
||||
}
|
||||
final session = _Session(server);
|
||||
_sessions[server.id] = session;
|
||||
setState(() => _activeId = server.id);
|
||||
_connect(session);
|
||||
}
|
||||
|
||||
Future<void> _connect(_Session session) async {
|
||||
try {
|
||||
await session.service.connect(
|
||||
session.server,
|
||||
onOutput: (data) => session.terminal.write(data),
|
||||
onDisconnected: () {
|
||||
session.terminal.write('\r\n\x1b[31m[连接已断开]\x1b[0m\r\n');
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
session.terminal.write('\r\n\x1b[31m连接失败:$e\x1b[0m\r\n');
|
||||
}
|
||||
}
|
||||
|
||||
void _sendKey(String data) {
|
||||
final s = _sessions[_activeId];
|
||||
if (s == null) return;
|
||||
s.service.write(data);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context);
|
||||
if (_sshServers.isEmpty) {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Text('没有配置 SSH 的服务器。\n\n请在「服务器」页编辑服务器,开启 SSH 后即可使用终端。',
|
||||
textAlign: TextAlign.center),
|
||||
),
|
||||
);
|
||||
}
|
||||
final active = _sessions[_activeId];
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
appBar: AppBar(
|
||||
title: const Text('终端'),
|
||||
actions: [
|
||||
PopupMenuButton<ServerConfig>(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: '新会话',
|
||||
onSelected: _openSession,
|
||||
itemBuilder: (_) => _sshServers
|
||||
.map((s) => PopupMenuItem(value: s, child: Text(s.name)))
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
bottom: _sessions.isEmpty
|
||||
? null
|
||||
: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(44),
|
||||
child: SizedBox(
|
||||
height: 44,
|
||||
child: ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
children: _sessions.values.map((s) {
|
||||
final selected = s.server.id == _activeId;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),
|
||||
child: ChoiceChip(
|
||||
label: Text(s.server.name),
|
||||
selected: selected,
|
||||
onSelected: (_) => setState(() => _activeId = s.server.id),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
body: active == null
|
||||
? const Center(child: Text('选择一台服务器开始会话'))
|
||||
: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TerminalView(
|
||||
active.terminal,
|
||||
autofocus: true,
|
||||
),
|
||||
),
|
||||
_buildQuickBar(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 快捷键栏:Tab / Ctrl+C / Ctrl+D / 上下历史 / 常用命令。
|
||||
Widget _buildQuickBar() {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest.withOpacity(0.5),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: SizedBox(
|
||||
height: 44,
|
||||
child: ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
children: [
|
||||
_key('Tab', '\t'),
|
||||
_key('Ctrl+C', '\x03'),
|
||||
_key('Ctrl+D', '\x04'),
|
||||
_key('↑', '\x1b[A'),
|
||||
_key('↓', '\x1b[B'),
|
||||
_key('htop', 'htop\n'),
|
||||
_key('df -h', 'df -h\n'),
|
||||
_key('screen -r', 'screen -r\n'),
|
||||
_key('clear', 'clear\n'),
|
||||
_key('Esc', '\x1b'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _key(String label, String data) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
child: ActionChip(
|
||||
label: Text(label),
|
||||
onPressed: () => _sendKey(data),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 一个终端会话 = 一台服务器 + 终端缓冲 + SSH 服务。
|
||||
class _Session {
|
||||
final ServerConfig server;
|
||||
final Terminal terminal = Terminal(maxLines: 5000);
|
||||
final SshShellService service = SshShellService();
|
||||
|
||||
_Session(this.server) {
|
||||
terminal.onOutput = (data) => service.write(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import '../../core/services/download_manager.dart';
|
||||
import '../../core/services/modrinth_api.dart';
|
||||
import '../../core/services/mirror_service.dart';
|
||||
import '../../providers/server_provider.dart';
|
||||
|
||||
/// 下载中心状态:镜像源选择 + Modrinth 搜索 + 下载队列暴露。
|
||||
class DownloadProvider extends ChangeNotifier {
|
||||
final MirrorService mirror = MirrorService();
|
||||
late final ModrinthApi api = ModrinthApi(mirror);
|
||||
late final DownloadManager manager = DownloadManager(
|
||||
maxConcurrent: 3,
|
||||
onTaskCompleteUpload: _autoUpload,
|
||||
);
|
||||
|
||||
ServerConfig? uploadTarget; // 下载完成后自动上传到的服务器
|
||||
|
||||
Future<void> init() async {
|
||||
await mirror.load();
|
||||
}
|
||||
|
||||
/// 搜索 Modrinth。
|
||||
Future<List<ModrinthSearchResult>> search(
|
||||
String query, {String? mcVersion, String? loader, String projectType = 'mod', int limit = 20}) {
|
||||
return api.search(
|
||||
query: query,
|
||||
mcVersion: mcVersion,
|
||||
loader: loader,
|
||||
projectType: projectType,
|
||||
limit: limit,
|
||||
);
|
||||
}
|
||||
|
||||
/// 获取某项目的版本列表。
|
||||
Future<List<ModrinthVersion>> versions(String projectId) => api.versions(projectId);
|
||||
|
||||
/// 入队下载:保存到应用下载目录;若配置了 uploadTarget 且其有 SSH,
|
||||
/// 完成后自动上传到 mods/plugins 目录。
|
||||
Future<DownloadTask> download({
|
||||
required String url,
|
||||
required String fileName,
|
||||
required String projectType, // mod | plugin
|
||||
}) async {
|
||||
final base = await getApplicationDocumentsDirectory();
|
||||
final saveDir = '${base.path}/downloads';
|
||||
await Directory(saveDir).create(recursive: true);
|
||||
String? remoteDir;
|
||||
final target = uploadTarget;
|
||||
if (target != null && target.hasSsh) {
|
||||
final home = target.sshUser == 'root' ? '/root' : '/home/${target.sshUser}';
|
||||
remoteDir = '$home/${projectType == 'plugin' ? 'plugins' : 'mods'}';
|
||||
}
|
||||
return manager.enqueue(
|
||||
url: mirror.rewrite(url),
|
||||
fileName: fileName,
|
||||
saveDir: saveDir,
|
||||
sftpRemoteDir: remoteDir,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _autoUpload(DownloadTask task) async {
|
||||
final target = uploadTarget;
|
||||
if (target == null || !target.hasSsh || task.sftpRemoteDir == null) return;
|
||||
try {
|
||||
await uploadViaSftp(
|
||||
task,
|
||||
ServerLike(
|
||||
host: target.host,
|
||||
sshPort: target.sshPort,
|
||||
sshUser: target.sshUser,
|
||||
sshPassword: target.sshPassword,
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
// 上传失败不影响下载状态,用户可在下载记录里手动重试
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
manager.dispose();
|
||||
mirror.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -8,20 +8,37 @@ class ServerConfig {
|
||||
final int port;
|
||||
final String password;
|
||||
|
||||
/// SSH(SFTP / 终端)可选配置,纯 RCON 用户可留空。
|
||||
final bool sshEnabled;
|
||||
final int sshPort;
|
||||
final String sshUser;
|
||||
final String sshPassword;
|
||||
|
||||
ServerConfig({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.password,
|
||||
this.sshEnabled = false,
|
||||
this.sshPort = 22,
|
||||
this.sshUser = '',
|
||||
this.sshPassword = '',
|
||||
});
|
||||
|
||||
/// 是否具备模组/终端功能所需的 SSH 配置。
|
||||
bool get hasSsh => sshEnabled && sshUser.isNotEmpty;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'host': host,
|
||||
'port': port,
|
||||
'password': password,
|
||||
'sshEnabled': sshEnabled,
|
||||
'sshPort': sshPort,
|
||||
'sshUser': sshUser,
|
||||
'sshPassword': sshPassword,
|
||||
};
|
||||
|
||||
factory ServerConfig.fromJson(Map<String, dynamic> json) => ServerConfig(
|
||||
@@ -30,6 +47,10 @@ class ServerConfig {
|
||||
host: json['host'],
|
||||
port: json['port'],
|
||||
password: json['password'],
|
||||
sshEnabled: json['sshEnabled'] ?? false,
|
||||
sshPort: json['sshPort'] ?? 22,
|
||||
sshUser: json['sshUser'] ?? '',
|
||||
sshPassword: json['sshPassword'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,6 +82,15 @@ class ServerProvider extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
ServerConfig? byId(String? id) {
|
||||
if (id == null) return null;
|
||||
try {
|
||||
return _servers.firstWhere((s) => s.id == id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
await SecureStorageService.saveServers(_servers);
|
||||
}
|
||||
|
||||
+13
-6
@@ -1,27 +1,34 @@
|
||||
name: zv_manager
|
||||
description: Minecraft服务器管理工具
|
||||
version: 1.5.5+12
|
||||
version: 2.0.0+13
|
||||
|
||||
environment:
|
||||
sdk: ">=3.0.0 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
dartssh2: ^2.8.2
|
||||
xterm: ^4.0.0
|
||||
dio: ^5.4.0
|
||||
archive: ^3.6.0
|
||||
yaml: ^3.1.2
|
||||
sqflite: ^2.3.0
|
||||
path: ^1.9.0
|
||||
flutter:
|
||||
sdk: flutter
|
||||
flutter_localizations:
|
||||
sdk: flutter
|
||||
provider: ^6.1.2
|
||||
shared_preferences: ^2.5.5
|
||||
flutter_secure_storage: ^11.0.0
|
||||
package_info_plus: ^10.2.1
|
||||
shared_preferences: ^2.3.3
|
||||
flutter_secure_storage: ^9.2.4
|
||||
package_info_plus: ^8.0.0
|
||||
video_player: ^2.8.1
|
||||
image_picker: ^1.0.4
|
||||
file_picker: ^13.1.0
|
||||
file_picker: ^8.1.0
|
||||
path_provider: ^2.1.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^6.0.0
|
||||
flutter_lints: ^5.0.0
|
||||
flutter:
|
||||
uses-material-design: true
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'package:zv_manager/core/services/jar_metadata.dart';
|
||||
|
||||
void main() {
|
||||
test('JarMetadata 解析 plugin.yml 插件', () {
|
||||
final archive = Archive()
|
||||
..addFile(ArchiveFile('plugin.yml', 0, '''
|
||||
name: EssentialsX
|
||||
version: 2.20.1
|
||||
authors: [Essentialsteam, md_5]
|
||||
description: Essentials plugin
|
||||
depend: [Vault]
|
||||
softdepend: [PlaceholderAPI]
|
||||
'''.codeUnits));
|
||||
final meta = JarMetadata.parseArchive(archive);
|
||||
expect(meta.name, 'EssentialsX');
|
||||
expect(meta.version, '2.20.1');
|
||||
expect(meta.depends, contains('Vault'));
|
||||
expect(meta.softDepends, contains('PlaceholderAPI'));
|
||||
});
|
||||
|
||||
test('JarMetadata 解析 fabric.mod.json 模组', () {
|
||||
final archive = Archive()
|
||||
..addFile(ArchiveFile('fabric.mod.json', 0, '''
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "sodium",
|
||||
"version": "0.5.3",
|
||||
"name": "Sodium",
|
||||
"authors": ["jellysquid3"],
|
||||
"depends": {"fabricloader": ">=0.14.0", "sodium": "x"}
|
||||
}
|
||||
'''.codeUnits));
|
||||
final meta = JarMetadata.parseArchive(archive);
|
||||
expect(meta.name, 'Sodium');
|
||||
expect(meta.version, '0.5.3');
|
||||
expect(meta.depends, contains('sodium'));
|
||||
});
|
||||
|
||||
test('无效文件返回 empty', () {
|
||||
expect(JarMetadata.parse('/nonexistent/path.jar').name, isNull);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user