commit 90f6d120eb96c969083962ece3c176d51bfeb12f Author: driftinblock <3480428251@qq.com> Date: Thu Aug 27 15:41:11 2026 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..51f47ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# VSCode +.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +build/ +/coverage/ +pubspec.lock + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c374953 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 driftinblock && venti1112 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f7d3d7 --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +ZV Manager + +你的手机,就是服务器控制台 + +ZV Manager 是一款轻量、安全的 Minecraft 服务器远程管理工具。通过 RCON 协议,让你随时随地用手机管理你的服务器,无需打开电脑。 + +--- + +功能特性 + +| 模块 | 功能 | 状态 | +|------|------|------| +| 服务器管理 | 添加/编辑/删除服务器 | +| 服务器管理 | 多服务器切换 | +| 状态监控 | 实时在线人数 | +| 状态监控 | TPS 监控 +| 玩家管理 | 查看玩家列表 +| 玩家管理 | 授予/撤销 OP +| 玩家管理 | 踢出/封禁玩家 +| 玩家管理 | 批量操作玩家 +| 控制台 | RCON 模式 | +| 控制台 | 快速命令预设 +| 主题 | 浅色/深色/跟随系统 +| 壁纸 | 自定义壁纸 +| 数据 | 加密存储 + +技术栈 + +| 项目 | 说明 | +|------|------| +| **框架** | Flutter 3.x | +| **语言** | Dart 3.x | +| **目标平台** | Android 7.0+ / Web | +| **通信协议** | RCON (Minecraft 远程控制协议) | +| **本地存储** | Shared Preferences + Flutter Secure Storage | +| **状态管理** | Provider | +| **主题** | Material 3 | + +--- + +项目结构 + +``` + +lib/ +├── main.dart # 应用入口 +├── app.dart # MaterialApp 配置 +├── core/ +│ ├── theme/ +│ │ └── app_theme.dart # MD3 主题定义 +│ ├── utils/ +│ │ ├── rcon_client.dart # RCON 客户端 +│ │ └── update_service.dart # 更新检查 +│ └── widgets/ +│ └── background_widget.dart # 壁纸背景组件 +├── data/ +│ └── services/ +│ └── secure_storage_service.dart # 加密存储 +├── features/ +│ ├── server_list/ +│ │ ├── server_list_page.dart # 服务器列表 +│ │ └── server_form_dialog.dart # 添加/编辑弹窗 +│ ├── console/ +│ │ └── console_page.dart # 双模式控制台 +│ ├── player_management/ +│ │ └── player_list_page.dart # 玩家管理 +│ └── settings/ +│ ├── settings_page.dart # 设置页 +│ └── wallpaper_settings.dart # 壁纸设置 +└── providers/ +├── server_provider.dart # 服务器状态 +├── theme_provider.dart # 主题状态 +├── wallpaper_provider.dart # 壁纸状态 +└── rcon_provider.dart # RCON 状态 + +``` + +--- diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0abcf92 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,38 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..59d6f81 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,9 @@ +/.gradle +/.kotlin +/captures/ +/local.properties +GeneratedPluginRegistrant.java +.cxx/ +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..c881231 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,77 @@ +import java.util.Properties +import java.io.FileInputStream + +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + +android { + namespace = "com.mcserver_manager" + compileSdk { + version = release(37) { + minorApiLevel = 1 + } + } + buildToolsVersion = "37.0.0" + ndkVersion = "30.0.16138531" + + compileOptions { + isCoreLibraryDesugaringEnabled = true + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + applicationId = "com.mcserver_manager" + minSdk = 24 + targetSdk = 37 + versionCode = flutter.versionCode + versionName = flutter.versionName + + // 仅保留 ARMv8 (arm64-v8a):先清空默认集合再添加,排除 ARMv7 与 x86_64 + ndk { + abiFilters.clear() + abiFilters.add("arm64-v8a") + } + } + + signingConfigs { + create("release") { + keyAlias = keystoreProperties["keyAlias"] as? String ?: "" + keyPassword = keystoreProperties["keyPassword"] as? String ?: "" + storeFile = keystoreProperties["storeFile"]?.let { file(it as String) } + storePassword = keystoreProperties["storePassword"] as? String ?: "" + enableV1Signing = false + enableV2Signing = true + enableV3Signing = true + } + } + + buildTypes { + release { + signingConfig = signingConfigs.getByName("release") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") +} + +flutter { + source = "../.." +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ed0fa66 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/minecraft_manager/MainActivity.kt b/android/app/src/main/kotlin/com/minecraft_manager/MainActivity.kt new file mode 100644 index 0000000..6aecc6b --- /dev/null +++ b/android/app/src/main/kotlin/com/minecraft_manager/MainActivity.kt @@ -0,0 +1,145 @@ +package com.mcserver_manager + +import android.content.ActivityNotFoundException +import android.content.Intent +import androidx.core.content.FileProvider +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodChannel +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +class MainActivity : FlutterActivity() { + private companion object { + const val CHANNEL = "mc_server_manager/update" + const val PROGRESS_CHANNEL = "mc_server_manager/down_progress" + const val ARG_URL = "url" + const val ARG_FILENAME = "filename" + + /** 是否正在下载,防止并发下载到同一文件 */ + val downloading = AtomicBoolean(false) + + /** 下载进度推送事件流(由 Flutter 订阅) */ + val progressSink = AtomicReference(null) + } + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + MethodChannel( + flutterEngine.dartExecutor.binaryMessenger, + CHANNEL, + ).setMethodCallHandler { call, result -> + when (call.method) { + "downloadAndInstall" -> { + val url = call.argument(ARG_URL) + val filename = call.argument(ARG_FILENAME) + if (url.isNullOrBlank()) { + result.error("BAD_ARGS", "下载地址为空", null) + } else if (!downloading.compareAndSet(false, true)) { + // 已有下载正在进行,拒绝并发,避免文件写坏 + result.error("BUSY", "正在下载,请稍候", null) + } else { + downloadAndInstall(url, filename ?: "latest.apk", result) + } + } + else -> result.notImplemented() + } + } + + EventChannel( + flutterEngine.dartExecutor.binaryMessenger, + PROGRESS_CHANNEL, + ).setStreamHandler(object : EventChannel.StreamHandler { + override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { + progressSink.set(events) + } + + override fun onCancel(arguments: Any?) { + progressSink.set(null) + } + }) + } + + private fun sendProgress(downloaded: Long, total: Long) { + val sink = progressSink.get() ?: return + val percent = if (total > 0) downloaded.toDouble() / total else 0.0 + val payload = HashMap() + payload["downloaded"] = downloaded + payload["total"] = total + payload["percent"] = percent + android.os.Handler(android.os.Looper.getMainLooper()).post { + runCatching { sink.success(payload) } + } + } + + private fun downloadAndInstall( + url: String, + filename: String, + result: MethodChannel.Result, + ) { + Thread { + try { + val dir = File(cacheDir, "apk").apply { mkdirs() } + val file = File(dir, filename) + // 删除旧的半成品/残留文件,保证安装的是最新完整文件 + file.delete() + + val connection = java.net.URL(url).openConnection() + connection.setRequestProperty("User-Agent", "MCServerManager") + connection.connectTimeout = 15_000 + connection.readTimeout = 30_000 + val total = connection.contentLengthLong + + val buffer = ByteArray(8 * 1024) + var downloaded = 0L + var lastSent = 0L + connection.inputStream.use { input -> + file.outputStream().use { output -> + while (true) { + val read = input.read(buffer) + if (read < 0) break + output.write(buffer, 0, read) + downloaded += read + // 每约 256KB 推送一次进度,避免高频回调卡顿 + if (downloaded - lastSent >= 256 * 1024 || downloaded >= total) { + sendProgress(downloaded, total) + lastSent = downloaded + } + } + } + } + // 确保最终 100% 进度已推送 + if (lastSent < downloaded) { + sendProgress(downloaded, total) + } + + if (file.length() == 0L) { + file.delete() + runOnUiThread { result.error("DOWNLOAD_FAILED", "下载文件为空", null) } + return@Thread + } + + val uri = FileProvider.getUriForFile( + this, + "$packageName.fileprovider", + file, + ) + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + startActivity(intent) + runOnUiThread { result.success(null) } + } catch (e: ActivityNotFoundException) { + runOnUiThread { result.error("INSTALL_NOT_FOUND", "未找到可用的安装器", e.message) } + } catch (e: Exception) { + runOnUiThread { result.error("DOWNLOAD_FAILED", "下载失败:${e.message}", null) } + } finally { + downloading.set(false) + } + }.start() + } +} \ No newline at end of file diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..524b09a Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..343dacd Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..b3a9813 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..444887d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..9b1f663 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..e45a6d3 --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..362da11 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,65 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} + +gradle.beforeProject { + val flutterExt = extensions.findByName("flutter") + if (flutterExt != null) { + try { + var klass: Class<*>? = flutterExt.javaClass + var field: java.lang.reflect.Field? = null + while (klass != null && field == null) { + try { field = klass.getDeclaredField("ndkVersion") } + catch (e: NoSuchFieldException) { klass = klass.superclass } + } + if (field != null) { + field.isAccessible = true + field.set(flutterExt, "30.0.16138531") + } + } catch (e: Exception) { + logger.warn("无法反射修改 flutter.ndkVersion: ${e.message}") + } + } + + plugins.withId("com.android.application") { + extensions.findByType()?.apply { + buildToolsVersion = "37.0.0" + externalNativeBuild { cmake { version = "4.1.2" } } + } + } + plugins.withId("com.android.library") { + extensions.findByType()?.apply { + buildToolsVersion = "37.0.0" + externalNativeBuild { cmake { version = "4.1.2" } } + } + } + afterEvaluate { + val libExt = extensions.findByType() + if (libExt != null) { + libExt.compileSdk = 37 + libExt.compileSdkMinor = 1 + } + } +} + +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..8929bfe --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,8 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false +# 插件源码在 C: 盘( pub 缓存)而项目在 D: 盘,跨盘符路径使 Kotlin 增量编译缓存崩溃,此处禁用 +kotlin.incremental=false diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ffcd530 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-all.zip diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000..9d82f78 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..22e0aab --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.3.1" apply false + id("org.jetbrains.kotlin.android") version "2.4.10" apply false +} + +include(":app") diff --git a/lib/app.dart b/lib/app.dart new file mode 100644 index 0000000..9efd141 --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,92 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:provider/provider.dart'; +import 'core/theme/app_theme.dart'; +import 'core/utils/update_service.dart'; +import 'core/widgets/background_widget.dart'; +import 'features/server_list/server_list_page.dart'; +import 'providers/theme_provider.dart'; +import 'providers/server_provider.dart'; + +/// 全局导航 Key +final navigatorKey = GlobalKey(); + +class ZVManagerApp extends StatefulWidget { + const ZVManagerApp({super.key}); + + @override + State createState() => ZVManagerAppState(); +} + +class ZVManagerAppState extends State { + final GlobalKey _bgKey = GlobalKey(); + + @override + void initState() { + super.initState(); + _checkUpdateSilently(); + } + + Future _checkUpdateSilently() async { + await Future.delayed(const Duration(seconds: 1)); + if (!mounted) return; + try { + final packageInfo = await PackageInfo.fromPlatform(); + final updateInfo = await UpdateService.fetchInfo(userAgent: packageInfo.version); + if (!mounted || updateInfo == null) return; + final navContext = navigatorKey.currentContext; + if (navContext == null || !navContext.mounted) return; + UpdateService.showUpdateDialog( + navContext, + updateInfo, + packageInfo.version, + silentOnNoUpdate: true, + ); + } catch (_) {} + } + + void refreshBackground() { + _bgKey.currentState?.refreshBackground(); + } + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => ThemeProvider()), + ChangeNotifierProvider(create: (_) => ServerProvider()), + ], + child: Consumer( + builder: (context, themeProvider, child) { + return MaterialApp( + title: 'ZV Manager', + debugShowCheckedModeBanner: false, + navigatorKey: navigatorKey, + theme: AppTheme.lightTheme, + darkTheme: AppTheme.darkTheme, + themeMode: themeProvider.flutterThemeMode, + locale: const Locale('zh', 'CN'), + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + Locale('zh', 'CN'), + Locale('en', 'US'), + ], + home: const ServerListPage(), + builder: (context, child) { + return BackgroundWidget( + key: _bgKey, + child: child!, + ); + }, + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/lib/core/theme/app_theme.dart b/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..a878019 --- /dev/null +++ b/lib/core/theme/app_theme.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; + +enum AppThemeMode { light, dark, system } + +class AppTheme { + static const _primaryColor = Color(0xFF4CAF50); + + static ThemeData get lightTheme => ThemeData( + useMaterial3: true, + brightness: Brightness.light, + colorSchemeSeed: _primaryColor, + appBarTheme: const AppBarTheme(centerTitle: true), + inputDecorationTheme: InputDecorationTheme( + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + filled: true, + ), + ); + + static ThemeData get darkTheme => ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + colorSchemeSeed: _primaryColor, + appBarTheme: const AppBarTheme(centerTitle: true), + scaffoldBackgroundColor: const Color(0xFF121212), + inputDecorationTheme: InputDecorationTheme( + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + filled: true, + ), + ); + + static ThemeMode toFlutterThemeMode(AppThemeMode mode) { + switch (mode) { + case AppThemeMode.light: + return ThemeMode.light; + case AppThemeMode.dark: + return ThemeMode.dark; + case AppThemeMode.system: + return ThemeMode.system; + } + } +} diff --git a/lib/core/utils/background_service.dart b/lib/core/utils/background_service.dart new file mode 100644 index 0000000..6511914 --- /dev/null +++ b/lib/core/utils/background_service.dart @@ -0,0 +1,40 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +class BackgroundService { + static const String _keyType = 'background_type'; // 'image' 或 'video' + static const String _keyPath = 'background_path'; + static const String _keyVideoSound = 'background_video_sound'; + + // 保存背景(图片或视频) + static Future setBackground(String type, String path) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyType, type); + await prefs.setString(_keyPath, path); + } + + // 获取背景 + static Future> getBackground() async { + final prefs = await SharedPreferences.getInstance(); + final type = prefs.getString(_keyType); + final path = prefs.getString(_keyPath); + return {'type': type, 'path': path}; + } + + // 清除背景 + static Future clearBackground() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyType); + await prefs.remove(_keyPath); + } + + // 视频声音开关 + static Future getVideoSound() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getBool(_keyVideoSound) ?? false; + } + + static Future setVideoSound(bool enabled) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyVideoSound, enabled); + } +} \ No newline at end of file diff --git a/lib/core/utils/command_preset_service.dart b/lib/core/utils/command_preset_service.dart new file mode 100644 index 0000000..29a8f52 --- /dev/null +++ b/lib/core/utils/command_preset_service.dart @@ -0,0 +1,58 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// 快速命令预设。 +class QuickCommandPreset { + final String label; + final String command; + + const QuickCommandPreset({required this.label, required this.command}); + + Map toJson() => {'label': label, 'command': command}; + + factory QuickCommandPreset.fromJson(Map json) => + QuickCommandPreset( + label: json['label'] as String? ?? '', + command: json['command'] as String? ?? '', + ); +} + +/// 快速命令预设的持久化存储(基于 SharedPreferences)。 +class CommandPresetService { + static const _key = 'mc_quick_commands_v1'; + + /// 默认预设,首次使用或清空后恢复。 + static const defaultPresets = [ + QuickCommandPreset(label: '在线列表', command: 'list'), + QuickCommandPreset(label: '立即存档', command: 'save-all'), + QuickCommandPreset(label: '查看种子', command: 'seed'), + QuickCommandPreset(label: '晴天', command: 'weather clear'), + QuickCommandPreset(label: '设为白天', command: 'time set day'), + QuickCommandPreset(label: '设为黑夜', command: 'time set night'), + QuickCommandPreset(label: '和平难度', command: 'difficulty peaceful'), + QuickCommandPreset(label: '生存模式', command: 'gamemode survival'), + QuickCommandPreset(label: '白名单列表', command: 'whitelist list'), + QuickCommandPreset(label: '在线公告', command: 'say 服务器已在线,欢迎游玩!'), + ]; + + static Future> load() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_key); + if (raw == null) return List.of(defaultPresets); + try { + final List decoded = jsonDecode(raw) as List; + return decoded + .map((e) => QuickCommandPreset.fromJson(e as Map)) + .where((p) => p.label.isNotEmpty && p.command.isNotEmpty) + .toList(); + } catch (_) { + return List.of(defaultPresets); + } + } + + static Future save(List presets) async { + final prefs = await SharedPreferences.getInstance(); + final encoded = jsonEncode(presets.map((p) => p.toJson()).toList()); + await prefs.setString(_key, encoded); + } +} \ No newline at end of file diff --git a/lib/core/utils/rcon_client.dart b/lib/core/utils/rcon_client.dart new file mode 100644 index 0000000..8a8a85a --- /dev/null +++ b/lib/core/utils/rcon_client.dart @@ -0,0 +1,166 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'rcon_stream_parser.dart'; + +/// 去除 Minecraft 消息中的颜色/格式码(§ 后跟一个有效字符)。 +String stripMinecraftCodes(String input) { + return input.replaceAll(RegExp(r'\u00a7[0-9A-Fa-fK-ORk-or]'), ''); +} + +class RconClient { + Socket? _socket; + int _requestId = 0; + bool _isAuthenticated = false; + final Map> _pendingRequests = {}; + + Timer? _heartbeatTimer; + Timer? _reconnectTimer; + int _reconnectAttempts = 0; + static const _maxReconnectAttempts = 10; + static const _heartbeatInterval = Duration(seconds: 30); + + VoidCallback? onDisconnected; + VoidCallback? onReconnected; + + String? _host; + int? _port; + String? _password; + bool _autoReconnect = true; + + bool get isConnected => _isAuthenticated && _socket != null; + + Future connect( + String host, + int port, + String password, { + bool autoReconnect = true, + }) async { + _host = host; + _port = port; + _password = password; + _autoReconnect = autoReconnect; + + try { + _socket = await Socket.connect( + host, + port, + timeout: const Duration(seconds: 5), + ); + + _socket!.transform(RconStreamParser()).listen((parsed) { + final completer = _pendingRequests.remove(parsed.id); + completer?.complete(parsed); + }); + + final authResponse = await _sendPacket(3, password); + _isAuthenticated = authResponse != null && authResponse.id != -1; + + if (_isAuthenticated) { + _reconnectAttempts = 0; + _startHeartbeat(); + } + return _isAuthenticated; + } catch (e) { + disconnect(); + rethrow; + } + } + + Future executeCommand(String command) async { + if (!_isAuthenticated || _socket == null) { + throw Exception('RCON 未连接或未认证'); + } + final response = await _sendPacket(2, command); + return response?.payload; + } + + void disconnect() { + _heartbeatTimer?.cancel(); + _reconnectTimer?.cancel(); + _reconnectAttempts = 0; + _socket?.destroy(); + _socket = null; + _isAuthenticated = false; + } + + void _startHeartbeat() { + _heartbeatTimer?.cancel(); + _heartbeatTimer = Timer.periodic(_heartbeatInterval, (_) async { + try { + await executeCommand('list'); + } catch (_) { + _handleDisconnect(); + } + }); + } + + void _handleDisconnect() { + _heartbeatTimer?.cancel(); + onDisconnected?.call(); + + if (!_autoReconnect || _reconnectAttempts >= _maxReconnectAttempts) return; + + _reconnectAttempts++; + final delay = Duration( + seconds: min(60, pow(2, _reconnectAttempts - 1).toInt()), + ); + + _reconnectTimer = Timer(delay, () async { + try { + final success = await connect( + _host!, + _port!, + _password!, + autoReconnect: true, + ); + if (success) onReconnected?.call(); + } catch (_) {} + }); + } + + Future _sendPacket(int type, String payload) async { + final id = ++_requestId; + final packet = _buildPacket(id, type, payload); + final completer = Completer(); + + _pendingRequests[id] = completer; + _socket!.add(packet); + + return completer.future.timeout( + const Duration(seconds: 5), + onTimeout: () { + _pendingRequests.remove(id); + // 请求超时:连接已失效,销毁后由下次调用重新建立 + disconnect(); + return null; + }, + ); + } + + Uint8List _buildPacket(int id, int type, String payload) { + final payloadBytes = utf8.encode(payload); + final length = 4 + 4 + payloadBytes.length + 2; + final buffer = BytesBuilder(); + + final lengthData = ByteData(4); + lengthData.setInt32(0, length, Endian.little); + buffer.add(lengthData.buffer.asUint8List()); + + final idData = ByteData(4); + idData.setInt32(0, id, Endian.little); + buffer.add(idData.buffer.asUint8List()); + + final typeData = ByteData(4); + typeData.setInt32(0, type, Endian.little); + buffer.add(typeData.buffer.asUint8List()); + + buffer.add(payloadBytes); + buffer.add([0, 0]); + + return buffer.toBytes(); + } +} diff --git a/lib/core/utils/rcon_stream_parser.dart b/lib/core/utils/rcon_stream_parser.dart new file mode 100644 index 0000000..1351646 --- /dev/null +++ b/lib/core/utils/rcon_stream_parser.dart @@ -0,0 +1,57 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +class RconPacket { + final int length; + final int id; + final int type; + final String payload; + + RconPacket({ + required this.length, + required this.id, + required this.type, + required this.payload, + }); +} + +class RconStreamParser extends StreamTransformerBase { + @override + Stream bind(Stream stream) async* { + BytesBuilder buffer = BytesBuilder(); + + await for (final chunk in stream) { + buffer.add(chunk); + var bytes = buffer.toBytes(); + + while (bytes.length >= 4) { + final byteData = ByteData.sublistView(bytes); + final packetLength = byteData.getInt32(0, Endian.little); + final totalSize = 4 + packetLength; + + if (bytes.length < totalSize) break; + + final packetBytes = bytes.sublist(4, totalSize); + final packetData = ByteData.sublistView(packetBytes); + + if (packetBytes.length >= 10) { + yield RconPacket( + length: packetLength, + id: packetData.getInt32(0, Endian.little), + type: packetData.getInt32(4, Endian.little), + payload: utf8.decode( + packetBytes.sublist(8, packetBytes.length - 2), + allowMalformed: true, + ), + ); + } + + bytes = bytes.sublist(totalSize); + } + + buffer.clear(); + if (bytes.isNotEmpty) buffer.add(bytes); + } + } +} diff --git a/lib/core/utils/update_service.dart b/lib/core/utils/update_service.dart new file mode 100644 index 0000000..9ed8d7f --- /dev/null +++ b/lib/core/utils/update_service.dart @@ -0,0 +1,202 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// 软件更新信息,由 Gitee 发布接口的 tag_name 与 assets 解析而来 +class UpdateInfo { + final String latestVersion; + final String downloadUrl; + final String apkName; + const UpdateInfo({ + required this.latestVersion, + required this.downloadUrl, + required this.apkName, + }); +} + +/// 更新检查与安装服务:负责从 Gitee 拉取发布信息、下载并调起系统安装器。 +class UpdateService { + const UpdateService._(); + + /// Gitee 仓库最新发布信息地址 + static const _updateInfoUrl = + 'https://gitee.com/api/v5/repos/venti1112/mcserver_manager/releases/latest'; + + /// Android 原生下载安装通道 + static const _channel = MethodChannel('mc_server_manager/update'); + + /// 下载进度事件通道(原生推送) + static const _progressChannel = EventChannel('mc_server_manager/down_progress'); + + /// 是否正在下载,用于防止重复触发并发下载到同一文件。 + static bool _downloading = false; + + /// 从 Gitee 拉取最新发布信息;接口异常返回 null(调用方决定是否静默处理)。 + static Future fetchInfo({String userAgent = ''}) async { + final client = HttpClient(); + try { + final request = await client + .getUrl(Uri.parse(_updateInfoUrl)) + .timeout(const Duration(seconds: 8)); + request.headers.set( + HttpHeaders.userAgentHeader, + 'ZVManager${userAgent.isEmpty ? '' : '/$userAgent'}', + ); + final response = await request.close(); + if (response.statusCode != 200) return null; + final body = await response.transform(utf8.decoder).join(); + final json = jsonDecode(body) as Map; + // Gitee 发布接口的 tag_name 形如 "v1.3.0",去掉开头的 "v" 用于版本号对比 + final tag = json['tag_name'] as String? ?? ''; + final latestVersion = + tag.startsWith('v') ? tag.substring(1) : tag; + + // 从 assets 中筛选 APK 安装包,取其直链与文件名 + String downloadUrl = ''; + String apkName = ''; + final assets = json['assets'] as List? ?? []; + for (final item in assets) { + final name = (item as Map)['name'] as String? ?? ''; + if (name.endsWith('.apk')) { + downloadUrl = + (item['browser_download_url'] as String? ?? + item['download_url'] as String? ?? + ''); + apkName = name; + break; + } + } + + return UpdateInfo( + latestVersion: latestVersion, + downloadUrl: downloadUrl, + apkName: apkName, + ); + } finally { + client.close(); + } + } + + /// 展示版本对比结果弹窗;`hasUpdate` 为 false 时若无更新且 `silentOnNoUpdate` 为 true 则直接静默返回。 + static void showUpdateDialog( + BuildContext context, + UpdateInfo info, + String currentVersion, { + bool silentOnNoUpdate = false, + }) { + final hasUpdate = info.latestVersion != currentVersion; + if (!hasUpdate && silentOnNoUpdate) return; + + showDialog( + context: context, + builder: (_) => AlertDialog( + title: Text(hasUpdate ? '发现新版本' : '已是最新'), + content: Text(hasUpdate + ? '最新版本: ${info.latestVersion}\n当前版本: $currentVersion' + : '当前版本 $currentVersion 已是最新'), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('关闭')), + if (hasUpdate) + FilledButton( + onPressed: () { + Navigator.pop(context); + downloadAndInstall(context, info); + }, + child: const Text('立即更新'), + ), + ], + ), + ); + } + + /// 调用 Android 原生下载 APK 并调起系统安装器;下载期间展示不可关闭的进度弹窗,失败提示错误。 + static Future downloadAndInstall(BuildContext context, UpdateInfo info) async { + if (_downloading) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('正在下载,请稍候…')), + ); + return; + } + if (info.downloadUrl.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('未找到可下载的安装包')), + ); + return; + } + if (!context.mounted) return; + + _downloading = true; + // 进度值,范围为 0~1;原生推送前为 null,显示不确定进度条转圈。 + final progress = ValueNotifier(null); + StreamSubscription? progressSub; + + try { + progressSub = _progressChannel.receiveBroadcastStream().listen((event) { + if (event is Map) { + final percent = event['percent']; + if (percent is num) { + progress.value = percent.clamp(0.0, 1.0).toDouble(); + } + } + }); + + final navigator = Navigator.of(context, rootNavigator: true); + // 展示不可关闭的进度弹窗(不阻塞,下载完成后关闭) + // ignore: unawaited_futures + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => PopScope( + canPop: false, + child: AlertDialog( + title: const Text('正在下载更新'), + content: ValueListenableBuilder( + valueListenable: progress, + builder: (context, value, _) { + final percent = value == null ? null : (value * 100).round(); + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(value: value), + const SizedBox(height: 16), + Text( + percent == null + ? '正在下载安装包…' + : '下载中:$percent%', + style: Theme.of(context).textTheme.bodyMedium, + ), + ], + ); + }, + ), + ), + ), + ); + + try { + await _channel.invokeMethod( + 'downloadAndInstall', + {'url': info.downloadUrl, 'filename': info.apkName}, + ); + } on PlatformException catch (e) { + final message = e.message?.toString() ?? e.code; + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('更新失败:$message')), + ); + } + } finally { + // 下载/触发安装器结束后关闭进度弹窗 + if (context.mounted) { + navigator.pop(); + } + } + } finally { + await progressSub?.cancel(); + progress.dispose(); + _downloading = false; + } + } +} \ No newline at end of file diff --git a/lib/core/widgets/background_widget.dart b/lib/core/widgets/background_widget.dart new file mode 100644 index 0000000..23fe2ea --- /dev/null +++ b/lib/core/widgets/background_widget.dart @@ -0,0 +1,130 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; +import '../utils/background_service.dart'; + +class BackgroundWidget extends StatefulWidget { + final Widget child; + + const BackgroundWidget({super.key, required this.child}); + + @override + State createState() => BackgroundWidgetState(); +} + +// 导出 State 供外部调用 +class BackgroundWidgetState extends State { + VideoPlayerController? _controller; + String? _currentType; + String? _currentPath; + bool _isLoading = true; + + @override + void initState() { + super.initState(); + _loadBackground(); + } + + Future _loadBackground() async { + final data = await BackgroundService.getBackground(); + final type = data['type']; + final path = data['path']; + + // 如果没变化就不重新加载 + if (_currentType == type && _currentPath == path && _controller != null) { + setState(() => _isLoading = false); + return; + } + + // 释放旧视频 + if (_controller != null) { + await _controller!.dispose(); + _controller = null; + } + + _currentType = type; + _currentPath = path; + + if (type == 'video' && path != null) { + try { + final videoSound = await BackgroundService.getVideoSound(); + final controller = VideoPlayerController.file(File(path)); + await controller.initialize(); + controller.setLooping(true); + controller.setVolume(videoSound ? 1.0 : 0.0); + controller.play(); + setState(() { + _controller = controller; + _isLoading = false; + }); + return; + } catch (e) { + print('视频加载失败: $e'); + } + } + + setState(() => _isLoading = false); + } + + // 供外部调用的刷新方法 + void refreshBackground() { + _loadBackground(); + } + + @override + void dispose() { + _controller?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (_isLoading) { + return widget.child; + } + + // 有视频背景 + if (_controller != null && _controller!.value.isInitialized) { + return Stack( + fit: StackFit.expand, + children: [ + SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: _controller!.value.size.width, + height: _controller!.value.size.height, + child: VideoPlayer(_controller!), + ), + ), + ), + Container(color: Colors.black.withOpacity(0.3)), + _wrapWithTransparentTheme(widget.child), + ], + ); + } + + // 有图片背景 + if (_currentType == 'image' && _currentPath != null) { + return Stack( + fit: StackFit.expand, + children: [ + Image.file(File(_currentPath!), fit: BoxFit.cover), + _wrapWithTransparentTheme(widget.child), + ], + ); + } + + // 无背景 + return widget.child; + } + + Widget _wrapWithTransparentTheme(Widget child) { + return Theme( + data: Theme.of(context).copyWith( + scaffoldBackgroundColor: Colors.transparent, + ), + child: child, + ); + } +} \ No newline at end of file diff --git a/lib/data/services/secure_storage_service.dart b/lib/data/services/secure_storage_service.dart new file mode 100644 index 0000000..e883230 --- /dev/null +++ b/lib/data/services/secure_storage_service.dart @@ -0,0 +1,41 @@ +import 'dart:convert'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../../providers/server_provider.dart'; + +class SecureStorageService { + static const _key = 'mc_servers_encrypted'; + static const _legacyKey = 'mc_servers'; + + static const _storage = FlutterSecureStorage( + aOptions: AndroidOptions(), + iOptions: IOSOptions( + accessibility: KeychainAccessibility.first_unlock_this_device, + ), + ); + + static Future> loadServers() async { + final encrypted = await _storage.read(key: _key); + if (encrypted != null) { + final List decoded = jsonDecode(encrypted); + return decoded.map((e) => ServerConfig.fromJson(e)).toList(); + } + + final prefs = await SharedPreferences.getInstance(); + final legacy = prefs.getString(_legacyKey); + if (legacy != null) { + final List decoded = jsonDecode(legacy); + final servers = decoded.map((e) => ServerConfig.fromJson(e)).toList(); + await saveServers(servers); + await prefs.remove(_legacyKey); + return servers; + } + + return []; + } + + static Future saveServers(List servers) async { + final encoded = jsonEncode(servers.map((s) => s.toJson()).toList()); + await _storage.write(key: _key, value: encoded); + } +} diff --git a/lib/features/console/console_page.dart b/lib/features/console/console_page.dart new file mode 100644 index 0000000..1210156 --- /dev/null +++ b/lib/features/console/console_page.dart @@ -0,0 +1,473 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../core/utils/command_preset_service.dart'; +import '../../core/utils/rcon_client.dart'; +import '../player_management/player_list_page.dart'; + +class ConsolePage extends StatefulWidget { + final RconClient rconClient; + const ConsolePage({super.key, required this.rconClient}); + + @override + State createState() => _ConsolePageState(); +} + +class _ConsolePageState extends State { + final _controller = TextEditingController(); + final _scrollController = ScrollController(); + final _history = []; + int _historyIndex = -1; + final _outputLines = <_LogLine>[]; + List _presets = []; + + static const _commands = [ + 'help', 'list', 'stop', 'say', 'op', 'deop', 'kick', 'ban', 'pardon', + 'gamemode', 'tp', 'give', 'time set', 'weather', 'difficulty', + ]; + + @override + void initState() { + super.initState(); + widget.rconClient.onDisconnected = () { + if (mounted) { + setState(() => _outputLines.add(_LogLine(text: '[警告] 连接断开,正在重连...', isError: true))); + } + }; + widget.rconClient.onReconnected = () { + if (mounted) { + setState(() => _outputLines.add(_LogLine(text: '[信息] 重连成功', isCommand: false))); + } + }; + _loadPresets(); + } + + Future _loadPresets() async { + final presets = await CommandPresetService.load(); + if (mounted) setState(() => _presets = presets); + } + + @override + void dispose() { + _controller.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + void _scrollToBottom() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 200), + curve: Curves.easeOut, + ); + } + }); + } + + Future _executeCommand() async { + final cmd = _controller.text.trim(); + if (cmd.isEmpty) return; + _controller.clear(); + await _sendCommand(cmd); + } + + Future _sendCommand(String cmd) async { + if (_history.isEmpty || _history.last != cmd) _history.add(cmd); + _historyIndex = _history.length; + + setState(() { + _outputLines.add(_LogLine(text: '> $cmd', isCommand: true)); + }); + _scrollToBottom(); + + try { + final response = await widget.rconClient.executeCommand(cmd); + setState(() { + _outputLines.add(_LogLine( + text: stripMinecraftCodes(response ?? '(无响应)'), + isCommand: false, + )); + }); + } catch (e) { + setState(() { + _outputLines.add(_LogLine(text: '[错误] $e', isCommand: false, isError: true)); + }); + } + _scrollToBottom(); + } + + void _onTabPressed() { + final input = _controller.text.trim(); + if (input.isEmpty) return; + + final matches = _commands.where((c) => c.startsWith(input)).toList(); + if (matches.length == 1) { + _controller.text = matches.first; + _controller.selection = TextSelection.fromPosition(TextPosition(offset: matches.first.length)); + } else if (matches.length > 1) { + setState(() { + _outputLines.add(_LogLine(text: '建议:${matches.join(", ")}', isCommand: false)); + }); + _scrollToBottom(); + } + } + + void _onHistoryNavigate(bool up) { + if (_history.isEmpty) return; + setState(() { + if (up) { + _historyIndex = (_historyIndex - 1).clamp(0, _history.length - 1); + } else { + _historyIndex = (_historyIndex + 1).clamp(0, _history.length); + } + _controller.text = _historyIndex < _history.length ? _history[_historyIndex] : ''; + _controller.selection = TextSelection.fromPosition(TextPosition(offset: _controller.text.length)); + }); + } + + Future _managePresets() async { + final result = await showModalBottomSheet>( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (_) => _PresetManageSheet( + presets: _presets, + onSend: _sendCommand, + ), + ); + if (result != null && mounted) { + await CommandPresetService.save(result); + if (mounted) setState(() => _presets = result); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar( + title: const Text('服务器控制台'), + actions: [ + IconButton( + icon: const Icon(Icons.people_outline), + tooltip: '玩家管理', + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => PlayerListPage(rconClient: widget.rconClient)), + ), + ), + ], + ), + body: Column( + children: [ + Expanded( + child: Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3), + child: ListView.builder( + controller: _scrollController, + itemCount: _outputLines.length, + itemBuilder: (_, i) { + final line = _outputLines[i]; + return SelectableText( + line.text, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 13, + color: line.isError + ? theme.colorScheme.error + : line.isCommand + ? theme.colorScheme.primary + : theme.colorScheme.onSurface, + ), + ); + }, + ), + ), + ), + _PresetBar( + presets: _presets, + onSend: _sendCommand, + onManage: _managePresets, + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + children: [ + Expanded( + child: KeyboardListener( + focusNode: FocusNode(), + onKeyEvent: (event) { + if (event is KeyDownEvent) { + if (event.logicalKey == LogicalKeyboardKey.arrowUp) _onHistoryNavigate(true); + if (event.logicalKey == LogicalKeyboardKey.arrowDown) _onHistoryNavigate(false); + if (event.logicalKey == LogicalKeyboardKey.tab) _onTabPressed(); + } + }, + child: TextField( + controller: _controller, + decoration: InputDecoration( + hintText: '输入命令...', + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + ), + style: const TextStyle(fontFamily: 'monospace', fontSize: 14), + onSubmitted: (_) => _executeCommand(), + ), + ), + ), + const SizedBox(width: 8), + FilledButton.icon( + onPressed: _executeCommand, + icon: const Icon(Icons.send_rounded, size: 18), + label: const Text('发送'), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class _LogLine { + final String text; + final bool isCommand; + final bool isError; + _LogLine({required this.text, this.isCommand = false, this.isError = false}); +} + +/// 快速命令预设栏:横向滚动的预设按钮 + 管理入口。 +class _PresetBar extends StatelessWidget { + final List presets; + final ValueChanged onSend; + final VoidCallback onManage; + + const _PresetBar({ + required this.presets, + required this.onSend, + required this.onManage, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return SizedBox( + height: 40, + child: Row( + children: [ + Expanded( + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12), + itemCount: presets.length, + separatorBuilder: (_, __) => const SizedBox(width: 8), + itemBuilder: (context, i) { + final preset = presets[i]; + return ActionChip( + label: Text(preset.label), + labelStyle: TextStyle(fontSize: 13, color: theme.colorScheme.onSecondaryContainer), + visualDensity: VisualDensity.compact, + backgroundColor: theme.colorScheme.secondaryContainer.withValues(alpha: 0.5), + onPressed: () => onSend(preset.command), + ); + }, + ), + ), + IconButton( + icon: const Icon(Icons.tune_rounded, size: 20), + tooltip: '管理快速命令', + onPressed: onManage, + ), + const SizedBox(width: 4), + ], + ), + ); + } +} + +/// 快速命令管理底部弹窗:可新增、编辑、删除、一键发送,点完成保存。 +class _PresetManageSheet extends StatefulWidget { + final List presets; + final ValueChanged onSend; + + const _PresetManageSheet({required this.presets, required this.onSend}); + + @override + State<_PresetManageSheet> createState() => _PresetManageSheetState(); +} + +class _PresetManageSheetState extends State<_PresetManageSheet> { + late final List _presets = List.of(widget.presets); + + Future _editPreset({QuickCommandPreset? preset}) async { + final result = await showDialog<_PresetEditResult>( + context: context, + builder: (_) => _PresetEditDialog(preset: preset), + ); + if (result == null || !mounted) return; + setState(() { + if (preset == null) { + _presets.add(QuickCommandPreset(label: result.label, command: result.command)); + } else { + final index = _presets.indexOf(preset); + _presets[index] = QuickCommandPreset(label: result.label, command: result.command); + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: SizedBox( + height: MediaQuery.of(context).size.height * 0.6, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Text('快速命令', style: theme.textTheme.titleMedium), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 16), + child: Text('点击标签一键发送,点击右侧按钮编辑'), + ), + Expanded( + child: _presets.isEmpty + ? const Center(child: Text('暂无预设,点击下方按钮添加')) + : ListView.builder( + itemCount: _presets.length, + itemBuilder: (context, i) { + final preset = _presets[i]; + return ListTile( + leading: const Icon(Icons.bolt_outlined), + title: Text(preset.label), + subtitle: Text( + preset.command, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontFamily: 'monospace', fontSize: 12), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.send_rounded, size: 20), + tooltip: '发送', + onPressed: () => widget.onSend(preset.command), + ), + IconButton( + icon: const Icon(Icons.edit_outlined, size: 20), + tooltip: '编辑', + onPressed: () => _editPreset(preset: preset), + ), + IconButton( + icon: const Icon(Icons.delete_outline, size: 20), + tooltip: '删除', + onPressed: () => setState(() => _presets.removeAt(i)), + ), + ], + ), + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + OutlinedButton.icon( + onPressed: () => _editPreset(), + icon: const Icon(Icons.add, size: 18), + label: const Text('新增'), + ), + const Spacer(), + FilledButton( + onPressed: () => Navigator.pop(context, _presets), + child: const Text('完成'), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _PresetEditResult { + final String label; + final String command; + _PresetEditResult({required this.label, required this.command}); +} + +class _PresetEditDialog extends StatefulWidget { + final QuickCommandPreset? preset; + const _PresetEditDialog({this.preset}); + + @override + State<_PresetEditDialog> createState() => _PresetEditDialogState(); +} + +class _PresetEditDialogState extends State<_PresetEditDialog> { + late final _labelController = TextEditingController(text: widget.preset?.label ?? ''); + late final _commandController = TextEditingController(text: widget.preset?.command ?? ''); + + @override + void dispose() { + _labelController.dispose(); + _commandController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(widget.preset == null ? '新增预设' : '编辑预设'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: _labelController, + decoration: const InputDecoration(labelText: '标签', hintText: '例如:立即存档'), + autofocus: true, + ), + const SizedBox(height: 12), + TextField( + controller: _commandController, + decoration: const InputDecoration(labelText: '命令', hintText: '例如:save-all'), + style: const TextStyle(fontFamily: 'monospace'), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + final label = _labelController.text.trim(); + final command = _commandController.text.trim(); + if (label.isEmpty || command.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('标签和命令都不能为空')), + ); + return; + } + Navigator.pop(context, _PresetEditResult(label: label, command: command)); + }, + child: const Text('保存'), + ), + ], + ); + } +} \ No newline at end of file diff --git a/lib/features/player_management/player_list_page.dart b/lib/features/player_management/player_list_page.dart new file mode 100644 index 0000000..b76bd22 --- /dev/null +++ b/lib/features/player_management/player_list_page.dart @@ -0,0 +1,339 @@ +import 'package:flutter/material.dart'; +import '../../core/utils/rcon_client.dart'; +import 'player_service.dart'; + +/// 玩家管理页:展示当前在线玩家的完整列表(含 UUID)。 +class PlayerListPage extends StatefulWidget { + final RconClient rconClient; + const PlayerListPage({super.key, required this.rconClient}); + + @override + State createState() => _PlayerListPageState(); +} + +class _PlayerListPageState extends State { + late final PlayerService _service; + List? _players; + bool _loading = true; + String? _error; + bool _selecting = false; + final Set _selected = {}; + + @override + void initState() { + super.initState(); + _service = PlayerService(widget.rconClient); + _load(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final players = await _service.getOnlinePlayers(); + if (!mounted) return; + setState(() { + _players = players; + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = '$e'; + _loading = false; + }); + } + } + + Future _performAction(String actionName, Future Function() action) async { + try { + final result = await action(); + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('$actionName:${stripMinecraftCodes(result ?? '无响应')}'), duration: const Duration(seconds: 2))); + await _load(); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('$actionName失败:$e'), backgroundColor: Colors.red)); + } + } + + Future _handleAction(PlayerInfo p, String action) async { + switch (action) { + case 'op': + await _performAction('给予 OP', () => _service.opPlayer(p.name)); + case 'deop': + await _performAction('取消 OP', () => _service.deopPlayer(p.name)); + case 'kick': + final kickReason = await _showReasonDialog('踢出', p.name); + if (kickReason == null) break; + await _performAction('踢出', () => _service.kickPlayer(p.name, reason: kickReason)); + case 'ban': + final banReason = await _showReasonDialog('封禁', p.name); + if (banReason == null) break; + await _performAction('封禁', () => _service.banPlayer(p.name, reason: banReason)); + } + } + + /// 进入批量选择模式。 + void _enterSelection() { + setState(() { + _selecting = true; + _selected.clear(); + }); + } + + /// 退出批量选择模式。 + void _exitSelection() { + setState(() { + _selecting = false; + _selected.clear(); + }); + } + + /// 在批量选择模式下勾选/取消某个玩家。 + void _toggleSelect(String name) { + setState(() { + if (!_selected.add(name)) _selected.remove(name); + }); + } + + static const _actionLabels = { + 'op': '给予OP', + 'deop': '取消OP', + 'kick': '踢出', + 'ban': '封禁', + }; + + /// 对选中的所有玩家执行批量操作。 + Future _handleBatch(String action) async { + final names = (_players ?? []) + .where((p) => _selected.contains(p.name)) + .map((p) => p.name) + .toList(); + if (names.isEmpty) return; + + String? reason; + if (action == 'kick' || action == 'ban') { + reason = await _showReasonDialog(_actionLabels[action]!, '${names.length}名玩家'); + if (reason == null) return; // 用户取消 + } + + var success = 0; + var fail = 0; + for (final name in names) { + try { + switch (action) { + case 'op': + await _service.opPlayer(name); + case 'deop': + await _service.deopPlayer(name); + case 'kick': + await _service.kickPlayer(name, reason: reason ?? ''); + case 'ban': + await _service.banPlayer(name, reason: reason ?? ''); + } + success++; + } catch (_) { + fail++; + } + } + if (!mounted) return; + final label = _actionLabels[action]!; + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('$label完成:成功 $success 人${fail > 0 ? ',失败 $fail 人' : ''}'), + duration: const Duration(seconds: 2), + )); + await _load(); + if (mounted) setState(() => _selected.clear()); + } + + /// 展示操作确认框并允许填写原因,返回原因字符串;取消则返回 null。 + Future _showReasonDialog(String actionLabel, String player) async { + final controller = TextEditingController(); + try { + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(actionLabel), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('将对「$player」执行该操作'), + const SizedBox(height: 12), + TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: '原因(可选)'), + ), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('确认', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + final reason = controller.text.trim(); + return confirmed == true ? reason : null; + } finally { + controller.dispose(); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Scaffold( + appBar: AppBar( + leading: _selecting + ? IconButton( + icon: const Icon(Icons.close), + tooltip: '退出选择', + onPressed: _exitSelection, + ) + : null, + title: Text(_selecting ? '已选 ${_selected.length} 人' : '玩家管理'), + actions: [ + if (_selecting) ...[ + IconButton( + icon: const Icon(Icons.select_all), + tooltip: '全选', + onPressed: () { + setState(() => _selected + ..clear() + ..addAll((_players ?? []).map((p) => p.name))); + }, + ), + ] else + IconButton( + icon: const Icon(Icons.checklist_outlined), + tooltip: '批量操作', + onPressed: _loading ? null : _enterSelection, + ), + IconButton( + icon: const Icon(Icons.refresh), + tooltip: '刷新', + onPressed: _loading ? null : _load, + ), + ], + ), + body: _buildBody(theme), + bottomNavigationBar: _selecting ? _buildBatchBar(theme) : null, + ); + } + + /// 批量操作底部工具栏。 + Widget _buildBatchBar(ThemeData theme) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _buildBatchButton('op', Icons.admin_panel_settings_outlined, '给予OP', Colors.green), + _buildBatchButton('deop', Icons.remove_moderator_outlined, '取消OP', Colors.orange), + _buildBatchButton('kick', Icons.logout, '踢出', Colors.blue), + _buildBatchButton('ban', Icons.block, '封禁', Colors.red), + ], + ), + ), + ); + } + + Widget _buildBatchButton(String action, IconData icon, String label, Color color) { + final disabled = _selected.isEmpty; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: Icon(icon), + color: disabled ? null : color, + tooltip: label, + onPressed: disabled ? null : () => _handleBatch(action), + ), + Text( + label, + style: TextStyle(fontSize: 11, color: disabled ? null : color), + ), + ], + ); + } + + Widget _buildBody(ThemeData theme) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + if (_error != null) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('加载失败:$_error', textAlign: TextAlign.center), + const SizedBox(height: 12), + FilledButton(onPressed: _load, child: const Text('重试')), + ], + ), + ); + } + final players = _players ?? []; + if (players.isEmpty) { + return Center(child: Text('暂无在线玩家', style: theme.textTheme.bodyLarge)); + } + return RefreshIndicator( + onRefresh: _load, + child: ListView.separated( + padding: const EdgeInsets.all(12), + itemCount: players.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (_, i) { + final p = players[i]; + final selected = _selected.contains(p.name); + return ListTile( + leading: _selecting + ? Checkbox( + value: selected, + onChanged: (_) => _toggleSelect(p.name), + ) + : CircleAvatar( + child: Text(p.name.isNotEmpty ? p.name[0].toUpperCase() : '?'), + ), + title: Text(p.name, style: theme.textTheme.titleMedium), + subtitle: p.uuid.isEmpty ? null : Text(p.uuid, style: theme.textTheme.bodySmall), + selected: selected, + onTap: _selecting ? () => _toggleSelect(p.name) : null, + trailing: _selecting + ? const SizedBox.shrink() + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (p.isOp) + Chip( + label: const Text('OP'), + visualDensity: VisualDensity.compact, + ), + PopupMenuButton( + tooltip: '操作', + onSelected: (action) => _handleAction(p, action), + itemBuilder: (_) => [ + const PopupMenuItem(value: 'op', child: Text('给予 OP')), + const PopupMenuItem(value: 'deop', child: Text('取消 OP')), + const PopupMenuItem(value: 'kick', child: Text('踢出')), + const PopupMenuItem(value: 'ban', child: Text('封禁')), + ], + ), + ], + ), + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/player_management/player_service.dart b/lib/features/player_management/player_service.dart new file mode 100644 index 0000000..03e69e3 --- /dev/null +++ b/lib/features/player_management/player_service.dart @@ -0,0 +1,55 @@ +import '../../core/utils/rcon_client.dart'; + +class PlayerInfo { + final String name; + final String uuid; + final bool isOp; + + PlayerInfo({required this.name, required this.uuid, this.isOp = false}); +} + +class PlayerService { + final RconClient _rcon; + PlayerService(this._rcon); + + Future> getOnlinePlayers() async { + final response = await _rcon.executeCommand('list uuids'); + if (response == null) return []; + final cleaned = stripMinecraftCodes(response); + + // 玩家段位于最后一个冒号(ASCII 或全角)之后,使用已清除颜色码的内容 + if (!cleaned.contains(RegExp(r'[::]'))) return []; + final playerSection = cleaned.split(RegExp(r'[::]')).last.trim(); + if (playerSection.isEmpty) return []; + + return playerSection.split(', ').map((entry) { + final entryTrimmed = entry.trim(); + if (entryTrimmed.isEmpty) return null; + // 兼容全角( )与半角(())括号 + final match = RegExp(r'(.+?)[((]([^()()]+)[))]').firstMatch(entryTrimmed); + if (match == null) return null; + return PlayerInfo( + name: match.group(1)!.trim(), + uuid: match.group(2)!.trim(), + ); + }).whereType().toList(); + } + + Future opPlayer(String name) async { + return _rcon.executeCommand('op $name'); + } + + Future deopPlayer(String name) async { + return _rcon.executeCommand('deop $name'); + } + + Future kickPlayer(String name, {String reason = ''}) async { + final cmd = reason.isEmpty ? 'kick $name' : 'kick $name $reason'; + return _rcon.executeCommand(cmd); + } + + Future banPlayer(String name, {String reason = ''}) async { + final cmd = reason.isEmpty ? 'ban $name' : 'ban $name $reason'; + return _rcon.executeCommand(cmd); + } +} diff --git a/lib/features/server_list/server_form_dialog.dart b/lib/features/server_list/server_form_dialog.dart new file mode 100644 index 0000000..4e32c34 --- /dev/null +++ b/lib/features/server_list/server_form_dialog.dart @@ -0,0 +1,124 @@ +import 'package:flutter/material.dart'; +import '../../providers/server_provider.dart'; + +class ServerFormDialog extends StatefulWidget { + final ServerConfig? existingServer; + + const ServerFormDialog({super.key, this.existingServer}); + + @override + State createState() => _ServerFormDialogState(); +} + +class _ServerFormDialogState extends State { + final _formKey = GlobalKey(); + late TextEditingController _nameCtrl; + late TextEditingController _hostCtrl; + late TextEditingController _portCtrl; + late TextEditingController _passCtrl; + bool _obscurePassword = true; + + bool get isEditing => widget.existingServer != null; + + @override + void initState() { + super.initState(); + final s = widget.existingServer; + _nameCtrl = TextEditingController(text: s?.name ?? ''); + _hostCtrl = TextEditingController(text: s?.host ?? ''); + _portCtrl = TextEditingController(text: s?.port.toString() ?? '25575'); + _passCtrl = TextEditingController(text: s?.password ?? ''); + } + + @override + void dispose() { + _nameCtrl.dispose(); + _hostCtrl.dispose(); + _portCtrl.dispose(); + _passCtrl.dispose(); + super.dispose(); + } + + String? _validateRequired(String? value, String field) { + if (value == null || value.trim().isEmpty) return '$field不能为空'; + return null; + } + + String? _validatePort(String? value) { + if (value == null || value.trim().isEmpty) return '端口不能为空'; + final port = int.tryParse(value.trim()); + if (port == null || port < 1 || port > 65535) return '端口范围 1-65535'; + return null; + } + + void _submit() { + if (!_formKey.currentState!.validate()) return; + + final server = ServerConfig( + id: isEditing ? widget.existingServer!.id : DateTime.now().millisecondsSinceEpoch.toString(), + name: _nameCtrl.text.trim(), + host: _hostCtrl.text.trim(), + port: int.parse(_portCtrl.text.trim()), + password: _passCtrl.text, + ); + + Navigator.pop(context, server); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(isEditing ? '编辑服务器' : '添加服务器'), + content: SingleChildScrollView( + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextFormField( + controller: _nameCtrl, + decoration: const InputDecoration(labelText: '服务器名称', hintText: '例如: 我的生存服'), + validator: (v) => _validateRequired(v, '服务器名称'), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 12), + TextFormField( + controller: _hostCtrl, + decoration: const InputDecoration(labelText: '主机地址', hintText: 'IP 或域名'), + validator: (v) => _validateRequired(v, '主机地址'), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 12), + TextFormField( + controller: _portCtrl, + decoration: const InputDecoration(labelText: 'RCON 端口', hintText: '默认 25575'), + keyboardType: TextInputType.number, + validator: _validatePort, + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 12), + TextFormField( + controller: _passCtrl, + obscureText: _obscurePassword, + decoration: InputDecoration( + labelText: 'RCON 密码', + suffixIcon: IconButton( + icon: Icon(_obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined), + onPressed: () => setState(() => _obscurePassword = !_obscurePassword), + ), + ), + validator: (v) => _validateRequired(v, 'RCON 密码'), + textInputAction: TextInputAction.done, + onFieldSubmitted: (_) => _submit(), + ), + ], + ), + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + FilledButton(onPressed: _submit, child: Text(isEditing ? '保存' : '添加')), + ], + ); + } +} diff --git a/lib/features/server_list/server_list_page.dart b/lib/features/server_list/server_list_page.dart new file mode 100644 index 0000000..3f42ec1 --- /dev/null +++ b/lib/features/server_list/server_list_page.dart @@ -0,0 +1,303 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../core/utils/rcon_client.dart'; +import '../../providers/rcon_provider.dart'; +import '../../providers/server_provider.dart'; +import '../../providers/wallpaper_provider.dart'; +import '../console/console_page.dart'; +import '../settings/settings_page.dart'; +import 'server_form_dialog.dart'; + +class ServerListPage extends StatefulWidget { + const ServerListPage({super.key}); + + @override + State createState() => _ServerListPageState(); +} + +class _ServerListPageState extends State { + Timer? _pollTimer; + final Map _statusCache = {}; + + @override + void initState() { + super.initState(); + _pollTimer = Timer.periodic(const Duration(seconds: 5), (_) => _refreshAll()); + _refreshAll(); + } + + @override + void dispose() { + _pollTimer?.cancel(); + super.dispose(); + } + + Future _refreshAll() async { + final servers = context.read().servers; + for (final server in servers) { + if (!mounted) return; + unawaited(_checkStatus(server)); + } + if (mounted) setState(() {}); + } + + Future _checkStatus(ServerConfig server) async { + final status = await context.read().checkStatus(server); + if (!mounted) return; + setState(() => _statusCache[server.id] = status); + } + + /// 打开控制台:已连接直接进入;否则展示「正在连接」,失败则提示连接失败。 + Future _openConsole(ServerConfig server) async { + final rconProvider = context.read(); + + // 已连接:直接进入 + final existing = rconProvider.clientFor(server.id); + if (existing != null && existing.isConnected) { + if (!mounted) return; + Navigator.push( + context, + MaterialPageRoute(builder: (_) => ConsolePage(rconClient: existing)), + ); + return; + } + + // 未连接:展示「正在连接」进度框 + if (!mounted) return; + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center( + child: Card( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text('正在连接...'), + ], + ), + ), + ), + ), + ); + + RconClient? client; + String? error; + try { + client = await rconProvider.getClient(server); + } catch (e) { + error = '$e'; + } + + if (!mounted) return; + Navigator.pop(context); // 关闭进度框 + + final enteredClient = client; + if (enteredClient != null) { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => ConsolePage(rconClient: enteredClient)), + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('连接失败:$error')), + ); + } + } + + @override + Widget build(BuildContext context) { + final servers = context.watch().servers; + final theme = Theme.of(context); + final hasWallpaper = context.watch().hasWallpaper; + + return Scaffold( + appBar: AppBar( + title: const Text('MCServer Manager'), + backgroundColor: hasWallpaper ? Colors.transparent : null, + elevation: hasWallpaper ? 0 : null, + actions: [ + IconButton( + icon: const Icon(Icons.settings_outlined), + tooltip: '设置', + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const SettingsPage()), + ), + ), + ], + ), + body: servers.isEmpty + ? Center(child: Text('暂无服务器,点击 + 添加', style: theme.textTheme.bodyLarge)) + : RefreshIndicator( + onRefresh: _refreshAll, + child: ListView.separated( + padding: const EdgeInsets.all(12), + itemCount: servers.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (_, i) => _ServerCard( + server: servers[i], + status: _statusCache[servers[i].id], + onTap: () => _openConsole(servers[i]), + onEdit: () async { + final updated = await showDialog( + context: context, + builder: (_) => ServerFormDialog(existingServer: servers[i]), + ); + if (updated != null && context.mounted) { + await context.read().updateServer(updated); + } + }, + onDelete: () async { + final confirmed = await showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('确认删除'), + content: Text('确定要删除服务器「${servers[i].name}」吗?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('取消'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('删除', style: TextStyle(color: Colors.red)), + ), + ], + ), + ); + if (confirmed == true && context.mounted) { + final id = servers[i].id; + final rconProvider = context.read(); + await context.read().removeServer(id); + rconProvider.disposeServer(id); + } + }, + ), + ), + ), + floatingActionButton: FloatingActionButton( + onPressed: () async { + final server = await showDialog( + context: context, + builder: (_) => const ServerFormDialog(), + ); + if (server != null && context.mounted) { + await context.read().addServer(server); + } + }, + child: const Icon(Icons.add), + ), + ); + } +} + +// --- 以下内部类保持不变 --- + +class _ServerCard extends StatelessWidget { + final ServerConfig server; + final ServerStatus? status; + final VoidCallback onTap; + final VoidCallback onEdit; + final VoidCallback onDelete; + + const _ServerCard({ + required this.server, + required this.status, + required this.onTap, + required this.onEdit, + required this.onDelete, + }); + + /// 根据 TPS 值返回状态颜色:≥16 流畅(绿),≥10 略低(橙),否则卡顿(红)。 + static Color _tpsColor(double tps) { + if (tps >= 16) return Colors.green; + if (tps >= 10) return Colors.orange; + return Colors.red; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isOnline = status?.online ?? false; + + return Card( + elevation: isOnline ? 2 : 0.5, + color: isOnline ? null : theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Container( + width: 12, + height: 12, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isOnline ? Colors.greenAccent : Colors.redAccent, + boxShadow: isOnline + ? [BoxShadow(color: Colors.greenAccent.withValues(alpha: 0.4), blurRadius: 6)] + : null, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(server.name, style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold)), + const SizedBox(height: 4), + Text('${server.host}:${server.port}', style: theme.textTheme.bodySmall), + if (isOnline && status != null) ...[ + const SizedBox(height: 2), + Row( + children: [ + Text('${status!.latencyMs}ms', + style: theme.textTheme.labelSmall?.copyWith(color: Colors.green)), + if (status!.tps != null) ...[ + const SizedBox(width: 8), + Text('TPS ${status!.tps!.toStringAsFixed(1)}', + style: theme.textTheme.labelSmall?.copyWith(color: _tpsColor(status!.tps!))), + ], + ], + ), + ], + ], + ), + ), + if (isOnline) + Chip( + label: Text('在线${status?.playerCount ?? 0}人'), + visualDensity: VisualDensity.compact, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ) + else + Chip( + label: const Text('离线'), + backgroundColor: theme.colorScheme.errorContainer, + visualDensity: VisualDensity.compact, + ), + const SizedBox(width: 4), + IconButton( + icon: Icon(Icons.edit_outlined, color: theme.colorScheme.primary), + tooltip: '编辑服务器', + onPressed: onEdit, + ), + IconButton( + icon: Icon(Icons.delete_outline, color: theme.colorScheme.error), + tooltip: '删除服务器', + onPressed: onDelete, + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/settings/settings_page.dart b/lib/features/settings/settings_page.dart new file mode 100644 index 0000000..e8753b6 --- /dev/null +++ b/lib/features/settings/settings_page.dart @@ -0,0 +1,280 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:file_picker/file_picker.dart'; +import 'dart:io'; +import 'package:path_provider/path_provider.dart'; +import '../../core/theme/app_theme.dart'; +import '../../core/utils/update_service.dart'; +import '../../core/utils/background_service.dart'; +import '../../providers/theme_provider.dart'; +import '../../app.dart'; + +class SettingsPage extends StatefulWidget { + const SettingsPage({super.key}); + @override + State createState() => _SettingsPageState(); +} + +class _SettingsPageState extends State { + String _currentVersion = ''; + bool _checkingUpdate = false; + String? _currentBgType; + String? _currentBgPath; + bool _videoSoundEnabled = false; + + @override + void initState() { + super.initState(); + _loadVersion(); + _loadCurrentBg(); + _loadVideoSound(); + } + + Future _loadVersion() async { + final info = await PackageInfo.fromPlatform(); + if (mounted) setState(() => _currentVersion = info.version); + } + + Future _loadCurrentBg() async { + final data = await BackgroundService.getBackground(); + if (mounted) { + setState(() { + _currentBgType = data['type']; + _currentBgPath = data['path']; + }); + } + } + + Future _loadVideoSound() async { + final enabled = await BackgroundService.getVideoSound(); + if (mounted) setState(() => _videoSoundEnabled = enabled); + } + + Future _checkUpdate() async { + setState(() => _checkingUpdate = true); + try { + final updateInfo = await UpdateService.fetchInfo(userAgent: _currentVersion); + if (!mounted) return; + setState(() => _checkingUpdate = false); + + if (updateInfo == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('获取更新信息失败')), + ); + return; + } + + UpdateService.showUpdateDialog(context, updateInfo, _currentVersion); + } catch (e) { + if (!mounted) return; + setState(() => _checkingUpdate = false); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('检查更新失败:$e')), + ); + } + } + + // ==================== 背景相关方法 ==================== + + void _showBackgroundPicker() { + showModalBottomSheet( + context: context, + builder: (ctx) => SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(Icons.photo, color: Colors.blue), + title: const Text('选择图片'), + onTap: () { + Navigator.pop(ctx); + _pickImage(); + }, + ), + ListTile( + leading: const Icon(Icons.videocam, color: Colors.green), + title: const Text('选择视频'), + onTap: () { + Navigator.pop(ctx); + _pickVideo(); + }, + ), + if (_currentBgPath != null) ...[ + const Divider(), + ListTile( + leading: const Icon(Icons.delete, color: Colors.red), + title: const Text('清除背景', style: TextStyle(color: Colors.red)), + onTap: () { + Navigator.pop(ctx); + _clearBackground(); + }, + ), + ], + ], + ), + ), + ); + } + + Future _pickImage() async { + final picker = ImagePicker(); + final result = await picker.pickImage(source: ImageSource.gallery); + if (result == null) return; + + final path = await _saveFileToAssets(result.path, 'image'); + if (path == null) return; + + await BackgroundService.setBackground('image', path); + _refreshUI(); + } + + Future _pickVideo() async { + final result = await FilePicker.pickFiles( + type: FileType.video, + allowMultiple: false, + ); + if (result.isEmpty) return; + + final filePath = result.single.path; + if (filePath == null) return; + + final path = await _saveFileToAssets(filePath, 'video'); + if (path == null) return; + + await BackgroundService.setBackground('video', path); + _refreshUI(); + } + + Future _saveFileToAssets(String sourcePath, String type) async { + try { + final dir = await getApplicationDocumentsDirectory(); + final ext = sourcePath.split('.').last; + final fileName = 'background_${type}_${DateTime.now().millisecondsSinceEpoch}.$ext'; + final destPath = '${dir.path}/$fileName'; + + final file = File(sourcePath); + await file.copy(destPath); + + return destPath; + } catch (e) { + print('保存失败: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('保存失败,请重试')), + ); + } + return null; + } + } + + Future _clearBackground() async { + await BackgroundService.clearBackground(); + _refreshUI(); + } + + void _refreshUI() { + _loadCurrentBg(); + _refreshBackground(); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(_currentBgPath == null ? '已清除背景' : '背景已更新 ✅'), + duration: const Duration(seconds: 1), + ), + ); + } + } + + void _refreshBackground() { + final appState = context.findAncestorStateOfType(); + appState?.refreshBackground(); + } + + // ==================== build ==================== + + @override + Widget build(BuildContext context) { + final themeProvider = context.watch(); + + return Scaffold( + appBar: AppBar(title: const Text('设置')), + body: ListView( + children: [ + // ---------- 外观主题 ---------- + ListTile( + leading: const Icon(Icons.palette_outlined), + title: const Text('外观主题'), + trailing: SegmentedButton( + segments: const [ + ButtonSegment(value: AppThemeMode.light, icon: Icon(Icons.light_mode, size: 18)), + ButtonSegment(value: AppThemeMode.dark, icon: Icon(Icons.dark_mode, size: 18)), + ButtonSegment(value: AppThemeMode.system, icon: Icon(Icons.brightness_auto, size: 18)), + ], + selected: {themeProvider.themeMode}, + onSelectionChanged: (v) => themeProvider.setThemeMode(v.first), + style: SegmentedButton.styleFrom(visualDensity: VisualDensity.compact), + ), + ), + const Divider(), + + // ---------- 应用背景(新增) ---------- + ListTile( + leading: const Icon(Icons.wallpaper), + title: const Text('应用背景'), + subtitle: Text( + _currentBgPath == null + ? '未设置' + : '已设置 ${_currentBgType == 'video' ? ' 视频' : ' 图片'}', + ), + trailing: const Icon(Icons.arrow_forward_ios, size: 16), + onTap: _showBackgroundPicker, + ), + // ---------- 视频声音开关 ---------- + if (_currentBgType == 'video') ...[ + SwitchListTile( + secondary: const Icon(Icons.volume_up), + title: const Text('视频声音'), + subtitle: const Text('开启后背景视频将播放声音'), + value: _videoSoundEnabled, + onChanged: (value) async { + await BackgroundService.setVideoSound(value); + setState(() => _videoSoundEnabled = value); + _refreshBackground(); + }, + ), + ], + const Divider(), + + // ---------- 检查更新 ---------- + ListTile( + leading: const Icon(Icons.system_update_outlined), + title: const Text('检查更新'), + subtitle: Text('当前版本: $_currentVersion'), + trailing: _checkingUpdate + ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.chevron_right), + onTap: _checkingUpdate ? null : _checkUpdate, + ), + const Divider(), + + // ---------- 关于 ---------- + const ListTile( + leading: Icon(Icons.info_outline), + title: Text('关于'), + subtitle: Text('开发者:Z有3笔,协作者:venti1112'), + ), + const Divider(), + + // ---------- 开源许可 ---------- + ListTile( + leading: const Icon(Icons.fact_check_outlined), + title: const Text('开源许可'), + onTap: () => showLicensePage(context: context), + ), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/features/settings/wallpaper_settings.dart b/lib/features/settings/wallpaper_settings.dart new file mode 100644 index 0000000..55ed487 --- /dev/null +++ b/lib/features/settings/wallpaper_settings.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path_provider/path_provider.dart'; +import 'dart:io'; +import '../../providers/wallpaper_provider.dart'; +import '../../app.dart'; + +class WallpaperSettings extends StatelessWidget { + const WallpaperSettings({super.key}); + + @override + Widget build(BuildContext context) { + final provider = context.watch(); + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar( + title: const Text('壁纸设置'), + backgroundColor: theme.colorScheme.primary, + foregroundColor: Colors.white, + ), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + // 预览区域 + Container( + height: 200, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + color: Colors.grey[200], + image: provider.wallpaperPath != null + ? DecorationImage( + image: FileImage(File(provider.wallpaperPath!)), + fit: BoxFit.cover, + ) + : null, + ), + child: provider.wallpaperPath == null + ? const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.wallpaper, size: 48, color: Colors.grey), + SizedBox(height: 8), + Text('当前为默认壁纸', style: TextStyle(color: Colors.grey)), + Text('点击下方「选择图片」自定义', style: TextStyle(color: Colors.grey, fontSize: 12)), + ], + ), + ) + : const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.check_circle, size: 48, color: Colors.white), + SizedBox(height: 8), + Text('自定义壁纸已应用', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)), + ], + ), + ), + ), + const SizedBox(height: 24), + + // 选择图片 + const Text('选择壁纸', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + const Text('从相册选择图片作为应用背景', style: TextStyle(fontSize: 12, color: Colors.grey)), + const SizedBox(height: 12), + FilledButton.icon( + onPressed: () async { + final picker = ImagePicker(); + final image = await picker.pickImage(source: ImageSource.gallery); + if (image != null && context.mounted) { + final savedPath = await _saveFileToAssets(context, image.path); + if (savedPath != null && context.mounted) { + await provider.setCustomWallpaper(savedPath); + if (context.mounted) { + _refreshBackground(context); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('壁纸已更新'), backgroundColor: Colors.green), + ); + } + } + } + }, + icon: const Icon(Icons.photo_library), + label: const Text('选择图片'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + ), + const SizedBox(height: 24), + + // 重置 + const Text('重置壁纸', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + const SizedBox(height: 4), + const Text('恢复默认壁纸', style: TextStyle(fontSize: 12, color: Colors.grey)), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: () { + _showResetDialog(context, provider); + }, + icon: const Icon(Icons.restore), + label: const Text('恢复默认'), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24), + side: const BorderSide(color: Colors.red), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + ), + ], + ), + ); + } + + Future _saveFileToAssets(BuildContext context, String sourcePath) async { + try { + final dir = await getApplicationDocumentsDirectory(); + final ext = sourcePath.split('.').last; + final fileName = 'background_image_${DateTime.now().millisecondsSinceEpoch}.$ext'; + final destPath = '${dir.path}/$fileName'; + + final file = File(sourcePath); + await file.copy(destPath); + + return destPath; + } catch (e) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('保存失败,请重试')), + ); + } + return null; + } + } + + void _refreshBackground(BuildContext context) { + final appState = context.findAncestorStateOfType(); + appState?.refreshBackground(); + } + + void _showResetDialog(BuildContext context, WallpaperProvider provider) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('确认重置'), + content: const Text('确定要恢复默认壁纸吗?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消'), + ), + FilledButton( + onPressed: () async { + await provider.resetWallpaper(); + if (context.mounted) { + _refreshBackground(context); + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('已恢复默认壁纸'), backgroundColor: Colors.green), + ); + } + }, + style: FilledButton.styleFrom(backgroundColor: Colors.red), + child: const Text('重置'), + ), + ], + ), + ); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..54c1142 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'app.dart'; +import 'providers/rcon_provider.dart'; +import 'providers/server_provider.dart'; +import 'providers/theme_provider.dart'; +import 'providers/wallpaper_provider.dart'; // 新增 + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + final serverProvider = ServerProvider(); + await serverProvider.loadServers(); + + final themeProvider = ThemeProvider(); + await themeProvider.loadThemeMode(); + + // 预加载壁纸设置 + final wallpaperProvider = WallpaperProvider(); // 新增 + await wallpaperProvider.loadWallpaper(); // 新增 + + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: serverProvider), + ChangeNotifierProvider.value(value: themeProvider), + ChangeNotifierProvider(create: (_) => RconProvider()), + ChangeNotifierProvider.value(value: wallpaperProvider), // 新增 + ], + child: const ZVManagerApp(), // 改成 ZVManagerApp + ), + ); +} diff --git a/lib/providers/rcon_provider.dart b/lib/providers/rcon_provider.dart new file mode 100644 index 0000000..023d827 --- /dev/null +++ b/lib/providers/rcon_provider.dart @@ -0,0 +1,106 @@ +import 'package:flutter/foundation.dart'; +import '../core/utils/rcon_client.dart'; +import 'server_provider.dart'; + +/// 全局 RCON 连接管理器:为每个服务器维护一个复用的 RconClient, +/// 持续连接复用,避免轮询时反复建立/断开连接。 +class RconProvider extends ChangeNotifier { + final Map _clients = {}; + + /// 获取某服务器的 RconClient,复用已有连接;未连接则连接。 + /// 连接失败时抛出异常,由调用方决定如何提示。 + Future getClient(ServerConfig server) async { + var client = _clients[server.id]; + if (client == null) { + client = RconClient(); + _clients[server.id] = client; + } + if (!client.isConnected) { + await client.connect(server.host, server.port, server.password); + } + return client; + } + + /// 返回某服务器的客户端对象;不存在时返回 null。 + RconClient? clientFor(String id) => _clients[id]; + + /// 某服务器是否已建立连接。 + bool isConnected(String id) => _clients[id]?.isConnected ?? false; + + /// 复用连接查询服务器状态。 + Future checkStatus(ServerConfig server) async { + final stopwatch = Stopwatch()..start(); + try { + final client = await getClient(server); + // 并行查询在线列表与 TPS(RCON 通过 requestId 区分响应) + final results = await Future.wait([ + client.executeCommand('list'), + client.executeCommand('tps').catchError((_) => null), + ]); + stopwatch.stop(); + final playerInfo = results[0]; + // 执行超时返回 null,视为服务器不可达 + if (playerInfo == null) { + return ServerStatus(online: false, latencyMs: stopwatch.elapsedMilliseconds); + } + return ServerStatus( + online: true, + latencyMs: stopwatch.elapsedMilliseconds, + playerInfo: playerInfo, + tps: _parseTps(results[1]), + ); + } catch (_) { + stopwatch.stop(); + return ServerStatus(online: false, latencyMs: stopwatch.elapsedMilliseconds); + } + } + + /// 断开并移除某服务器的连接。 + void disposeServer(String id) { + _clients.remove(id)?.disconnect(); + } + + @override + void dispose() { + for (final client in _clients.values) { + client.disconnect(); + } + _clients.clear(); + super.dispose(); + } +} + +/// 服务器状态快照。 +class ServerStatus { + final bool online; + final int latencyMs; + final String? playerInfo; + final double? tps; + ServerStatus({required this.online, this.latencyMs = 0, this.playerInfo, this.tps}); + + /// 从 `list` 返回中解析在线玩家数量。 + /// 如「当前共有0名玩家在线(最大玩家数为20):」或「There are 0 of a max of 20 players online:」, + /// 在线人数即提示词中的第一个数字。 + int get playerCount => _parseOnlineCount(playerInfo); +} + +int _parseOnlineCount(String? info) { + if (info == null) return 0; + final match = RegExp(r'\d+').firstMatch(info); + return int.tryParse(match?.group(0) ?? '') ?? 0; +} + +/// 从 `tps` 命令返回中解析 TPS 数值。 +/// 常见输出如「TPS from last 1m, 5m, 15m: 20.0, 20.0, 20.0」, +/// 取第一个数字(1 分钟均值);无法解析返回 null。 +double? _parseTps(String? info) { + if (info == null) return null; + final cleaned = stripMinecraftCodes(info); + // 匹配浮点数;排除紧跟字母的数字(如 "1m" 中的 1) + final match = RegExp(r'\d+(?:\.\d+)?(?![\d.a-zA-Z])').firstMatch(cleaned); + if (match == null) return null; + final tps = double.tryParse(match.group(0)!); + if (tps == null) return null; + // TPS 理论范围 0~20,超出视为解析异常 + return tps.clamp(0, 20); +} \ No newline at end of file diff --git a/lib/providers/server_provider.dart b/lib/providers/server_provider.dart new file mode 100644 index 0000000..1326de0 --- /dev/null +++ b/lib/providers/server_provider.dart @@ -0,0 +1,67 @@ +import 'package:flutter/foundation.dart'; +import '../data/services/secure_storage_service.dart'; + +class ServerConfig { + final String id; + final String name; + final String host; + final int port; + final String password; + + ServerConfig({ + required this.id, + required this.name, + required this.host, + required this.port, + required this.password, + }); + + Map toJson() => { + 'id': id, + 'name': name, + 'host': host, + 'port': port, + 'password': password, + }; + + factory ServerConfig.fromJson(Map json) => ServerConfig( + id: json['id'], + name: json['name'], + host: json['host'], + port: json['port'], + password: json['password'], + ); +} + +class ServerProvider extends ChangeNotifier { + List _servers = []; + List get servers => List.unmodifiable(_servers); + + Future loadServers() async { + _servers = await SecureStorageService.loadServers(); + notifyListeners(); + } + + Future addServer(ServerConfig server) async { + _servers.add(server); + await _save(); + notifyListeners(); + } + + Future updateServer(ServerConfig server) async { + final index = _servers.indexWhere((s) => s.id == server.id); + if (index != -1) _servers[index] = server; + await _save(); + notifyListeners(); + } + + Future removeServer(String id) async { + _servers.removeWhere((s) => s.id == id); + await _save(); + notifyListeners(); + } + + Future _save() async { + await SecureStorageService.saveServers(_servers); + } +} diff --git a/lib/providers/theme_provider.dart b/lib/providers/theme_provider.dart new file mode 100644 index 0000000..698dd3f --- /dev/null +++ b/lib/providers/theme_provider.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../core/theme/app_theme.dart'; + +class ThemeProvider extends ChangeNotifier { + static const _key = 'app_theme_mode'; + + AppThemeMode _themeMode = AppThemeMode.system; + AppThemeMode get themeMode => _themeMode; + + ThemeMode get flutterThemeMode => AppTheme.toFlutterThemeMode(_themeMode); + + Future loadThemeMode() async { + final prefs = await SharedPreferences.getInstance(); + final value = prefs.getString(_key); + if (value != null) { + _themeMode = AppThemeMode.values.firstWhere( + (m) => m.name == value, + orElse: () => AppThemeMode.system, + ); + notifyListeners(); + } + } + + Future setThemeMode(AppThemeMode mode) async { + if (_themeMode != mode) { + _themeMode = mode; + notifyListeners(); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_key, mode.name); + } + } +} diff --git a/lib/providers/wallpaper_provider.dart b/lib/providers/wallpaper_provider.dart new file mode 100644 index 0000000..e7d48e9 --- /dev/null +++ b/lib/providers/wallpaper_provider.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; +import '../core/utils/background_service.dart'; + +class WallpaperProvider extends ChangeNotifier { + String? _wallpaperPath; + String? _wallpaperType; + + String? get wallpaperPath => _wallpaperPath; + String? get wallpaperType => _wallpaperType; + + WallpaperProvider(); + + Future loadWallpaper() async { + final data = await BackgroundService.getBackground(); + _wallpaperType = data['type']; + _wallpaperPath = data['path']; + notifyListeners(); + } + + Future setCustomWallpaper(String path, {String type = 'image'}) async { + await BackgroundService.setBackground(type, path); + _wallpaperType = type; + _wallpaperPath = path; + notifyListeners(); + } + + Future resetWallpaper() async { + await BackgroundService.clearBackground(); + _wallpaperType = null; + _wallpaperPath = null; + notifyListeners(); + } + + bool get hasWallpaper => _wallpaperPath != null; +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..72d15c2 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,27 @@ +name: zv_manager +description: Minecraft服务器管理工具 +version: 1.5.1+9 + +environment: + sdk: ">=3.0.0 <4.0.0" + +dependencies: + 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 + video_player: ^2.8.1 + image_picker: ^1.0.4 + file_picker: ^12.0.0 + path_provider: ^2.1.1 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 +flutter: + uses-material-design: true