feat: 初始化项目结构,大致开发方向

This commit is contained in:
叁玖领域 2025-08-15 09:10:22 +08:00
commit b4c1269dbb
55 changed files with 2069 additions and 0 deletions

43
.gitignore vendored Normal file
View File

@ -0,0 +1,43 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
/logs/

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1,10 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme>
</component>

View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

16
.idea/gradle.xml Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="$PROJECT_DIR$/../../projEnv/gradle/gradle-8.7" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
.idea/kotlinc.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.23" />
</component>
</project>

14
.idea/misc.xml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ASMIdeaPluginConfiguration">
<asm skipDebug="false" skipFrames="false" skipCode="false" expandFrames="false" />
<groovy codeStyle="LEGACY" />
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

9
LINCESE Normal file
View File

@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 3944Realms
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.

65
build.gradle.kts Normal file
View File

@ -0,0 +1,65 @@
plugins {
kotlin("jvm") version "1.9.23"
kotlin("plugin.serialization") version "1.9.23" // 添加序列化插件
application
}
group = "top.r3944realms.ltdmanager"
version = "1.0-SNAPSHOT"
repositories {
repositories {
mavenLocal()
maven {
url = uri("https://maven.aliyun.com/repository/public/")
}
mavenCentral()
maven {
url = uri("https://maven.aliyun.com/repository/gradle-plugin")
}
}
//TODO: 0872d1c0-829c-e1d7-6782-89e45c8a6b76
dependencies {
// 添加序列化库
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")
// Ktor WebSocket客户端
implementation("io.ktor:ktor-client-websockets:2.3.3")
implementation("io.ktor:ktor-client-cio:2.3.3")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.3") // 推荐使用kotlinx.serialization替代Gson
// 数据库相关
implementation("org.jetbrains.exposed:exposed-core:0.41.1")
implementation("org.jetbrains.exposed:exposed-jdbc:0.41.1")
implementation("com.mysql:mysql-connector-j:8.0.33") // 使用MySQL 8.x驱动
implementation("com.zaxxer:HikariCP:5.0.1") // 连接池
// 日志系统
implementation("org.slf4j:slf4j-api:2.0.7")
implementation("org.apache.logging.log4j:log4j-slf4j2-impl:2.20.0")
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
// 配置管理
implementation("org.yaml:snakeyaml:2.2")
implementation("com.typesafe:config:1.4.2") // 类型安全的配置库
// 协程
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
// 测试
testImplementation(kotlin("test"))
testImplementation("io.ktor:ktor-client-mock:2.3.3")
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(17)
}
application {
mainClass.set("top.r3944realms.ltdmanager.main") // 设置主类
}
}

19
doc/README.MD Normal file
View File

@ -0,0 +1,19 @@
# NapCat
将回应抽象为event模型
将请求抽象为request模型
优先级发送流程
sequenceDiagram
participant Client
participant PriorityQueue
participant PendingResponses
participant Server
Client->>PriorityQueue: sendRequest(高优先级)
Client->>PriorityQueue: sendRequest(低优先级)
PriorityQueue->>Server: 先发送高优先级请求
Server->>PendingResponses: 返回响应1
PendingResponses->>Client: 解除高优先级请求的await
PriorityQueue->>Server: 发送低优先级请求
Server->>PendingResponses: 返回响应2
PendingResponses->>Client: 解除低优先级请求的await

4
gradle.properties Normal file
View File

@ -0,0 +1,4 @@
kotlin.code.style=official
org.gradle.downloadSources=false
org.gradle.parallel=true
org.gradle.degree_of_parallelism=16

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.7-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
gradlew vendored Normal file
View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
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" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

91
gradlew.bat vendored Normal file
View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@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
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
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 execute
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
: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 %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 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!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

5
settings.gradle.kts Normal file
View File

@ -0,0 +1,5 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "LTD-ManagerBot"

View File

@ -0,0 +1,9 @@
package top.r3944realms.ltdmanager.core.config
data class CryptoConfig(
var secretKey: String? = null
) {
override fun toString(): String {
return "CryptoConfig(secretkeu=$secretKey)"
}
}

View File

@ -0,0 +1,66 @@
package top.r3944realms.ltdmanager.core.config
import top.r3944realms.ltdmanager.utils.CryptoUtil
import top.r3944realms.ltdmanager.utils.YamlUpdater
import java.util.*
data class DatabaseConfig(
var url: String? = null,
var user: String? = null,
var encryptedPassword: String? = null
) {
/**
* 获取解密后的密码如果未加密返回原值
*/
val decryptedPassword: String?
get() {
if (encryptedPassword == null) {
return null
}
if (!isEncrypted()) {
return encryptedPassword
}
try {
val cipherText = encryptedPassword!!.substring(4, encryptedPassword!!.length - 1)
return CryptoUtil.decrypt(cipherText)
} catch (e: Exception) {
throw IllegalStateException("密码解密失败", e)
}
}
/**
* 加密密码如果未加密并返回是否成功加密
*/
fun encryptPassword() {
if (encryptedPassword == null || isEncrypted()) {
return
}
try {
encryptedPassword = "ENC(${CryptoUtil.encrypt(encryptedPassword!!)})"
YamlUpdater.updateYamlValue(
Objects.requireNonNull(
YamlConfigLoader::class.java
.classLoader
.getResource("application.yaml")
).path,
"database.encrypted-password",
this.encryptedPassword!!
)
} catch (e: Exception) {
throw IllegalStateException("密码加密失败", e)
}
}
/**
* 检查密码是否已加密
*/
fun isEncrypted(): Boolean {
return encryptedPassword != null &&
encryptedPassword!!.startsWith("ENC(") &&
encryptedPassword!!.endsWith(")")
}
override fun toString(): String {
return "DatabaseConfig(url=$url, user=$user, encryptedPassword=***)"
}
}

View File

@ -0,0 +1,10 @@
package top.r3944realms.ltdmanager.core.config
data class WebsocketConfig(
var url: String? = null,
var token: String? = null
) {
override fun toString(): String {
return "WebsocketConfig(Url=$url, token=$token)"
}
}

View File

@ -0,0 +1,49 @@
package top.r3944realms.ltdmanager.core.config
import org.yaml.snakeyaml.LoaderOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.Constructor
import org.yaml.snakeyaml.introspector.Property
import org.yaml.snakeyaml.introspector.PropertyUtils
import top.r3944realms.ltdmanager.utils.NamingConventionUtil
object YamlConfigLoader {
private val config: ConfigWrapper = loadConfig().also {
ensureConfigEncrypted(it) // 初始化后立即加密
}
private fun ensureConfigEncrypted(config: ConfigWrapper?) {
config?.database?.encryptPassword()
}
private fun loadConfig(): ConfigWrapper {
YamlConfigLoader::class.java.classLoader.getResourceAsStream("application.yaml").use { inputStream ->
if (inputStream == null) {
throw RuntimeException("配置文件 application.yaml 未找到!")
}
return Yaml(getConstructor()).load(inputStream)
}
}
private fun getConstructor(): Constructor {
val propertyUtils = object : PropertyUtils() {
override fun getProperty(type: Class<*>, name: String): Property {
val processedName = if (name.contains("-")) {
NamingConventionUtil.hyphenToCamel(name) // 连字符转驼峰
} else {
name
}
return super.getProperty(type, processedName)
}
}
return Constructor(ConfigWrapper::class.java, LoaderOptions()).apply {
setPropertyUtils(propertyUtils)
}
}
fun loadDatabaseConfig(): DatabaseConfig = config.database
fun loadCryptoConfig(): CryptoConfig = config.crypto
fun loadWebsocketConfig(): WebsocketConfig = config.websocket
data class ConfigWrapper(
var database :DatabaseConfig,
var crypto :CryptoConfig,
var websocket :WebsocketConfig
)
}

View File

@ -0,0 +1,41 @@
package top.r3944realms.ltdmanager.core.mysql
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import top.r3944realms.ltdmanager.core.config.YamlConfigLoader
import java.sql.Connection
import java.sql.SQLException
class MysqlHikariConnectPool : AutoCloseable {
private val dataSource: HikariDataSource
constructor() {
val config = HikariConfig().apply {
jdbcUrl = YamlConfigLoader.loadDatabaseConfig().url
username = YamlConfigLoader.loadDatabaseConfig().user
password = YamlConfigLoader.loadDatabaseConfig().decryptedPassword
// 8.0+ 推荐配置
addDataSourceProperty("cachePrepStmts", "true")
addDataSourceProperty("prepStmtCacheSize", "250")
addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
}
dataSource = HikariDataSource(config)
}
constructor(hikariConfig: HikariConfig) {
dataSource = HikariDataSource(hikariConfig)
}
/**
* 获取数据库连接
* @return 连接
* @throws SQLException SQL异常
*/
@Throws(SQLException::class)
fun getConnection(): Connection {
return dataSource.connection
}
override fun close() {
if (!dataSource.isClosed) {
dataSource.close()
}
}
}

View File

@ -0,0 +1,193 @@
package top.r3944realms.ltdmanager.core.mysql.utils
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.sql.Connection
import java.sql.SQLException
class SqlFileExecutor private constructor() {
companion object {
private val log = LoggerFactory.getLogger(SqlFileExecutor::class.java)
/**
* 执行SQL语句
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``module`模块下的`resources/`目录下的`sql/init.sql`
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFile(conn: Connection, filePath: String, module: Module) {
readAndExecuteSql(conn, filePath, -1, module)
}
/**
* 执行SQL语句
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``resources/`目录下的`sql/init.sql`
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFile(conn: Connection, filePath: String) {
readAndExecuteSql(conn, filePath, -1)
}
/**
* 执行SQL语句带批处理
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``resources/`目录下的`sql/init.sql`
* @param batchSize 批处理语句数
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFile(conn: Connection, filePath: String, batchSize: Int) {
readAndExecuteSql(conn, filePath, batchSize)
}
/**
* 执行SQL语句带批处理
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``module`模块下的`resources/`目录下的`sql/init.sql`
* @param batchSize 批处理语句数
* @param module 资源所属模块
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFile(conn: Connection, filePath: String, batchSize: Int, module: Module) {
readAndExecuteSql(conn, filePath, batchSize, module)
}
/**
* 执行SQL语句带批处理和事务
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``resources/`目录下的`sql/init.sql`
* @param batchSize 批处理语句数
* @param module 资源所属模块
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFileWithTransactional(conn: Connection, filePath: String, batchSize: Int, module: Module) {
val originalAutoCommit = conn.autoCommit
try {
conn.autoCommit = false
readAndExecuteSql(conn, filePath, batchSize, module)
conn.commit()
} catch (e: Exception) {
conn.rollback()
throw e
} finally {
conn.autoCommit = originalAutoCommit
}
}
/**
* 执行SQL语句带事务
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``module`模块下的`resources/`目录下的`sql/init.sql`
* @param module 资源所属模块
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFileWithTransactional(conn: Connection, filePath: String, module: Module) {
executeSqlFileWithTransactional(conn, filePath, -1, module)
}
/**
* 执行SQL语句带批处理和事务
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``resources/`目录下的`sql/init.sql`
* @param batchSize 批处理语句数
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFileWithTransactional(conn: Connection, filePath: String, batchSize: Int) {
executeSqlFileWithTransactional(conn, filePath, batchSize, SqlFileExecutor::class.java.module)
}
/**
* 执行SQL语句带事务
* @param conn 数据库连接
* @param filePath 文件路径 `/sql/init.sql``resources/`目录下的`sql/init.sql`
* @throws SQLException SQL语句执行出问题
* @throws IOException 对应文件缺失或不可读
*/
@Throws(IOException::class, SQLException::class)
fun executeSqlFileWithTransactional(conn: Connection, filePath: String) {
executeSqlFileWithTransactional(conn, filePath, -1, SqlFileExecutor::class.java.module)
}
private fun readAndExecuteSql(conn: Connection, filePath: String, batchSize: Int) {
readAndExecuteSql(conn, filePath, batchSize, SqlFileExecutor::class.java.module)
}
private fun readAndExecuteSql(
conn: Connection,
filePath: String,
batchSize: Int,
module: Module
) {
val inputStream = module.getResourceAsStream(filePath) ?: throw IOException("SQL file not found: $filePath")
BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)).use { reader ->
conn.createStatement().use { stmt ->
val useBatch = batchSize > 0
var count = 0
val sqlBuilder = StringBuilder()
reader.lineSequence()
.map { it.trim() }
.filter { it.isNotEmpty() && !it.startsWith("--") }
.forEach { line ->
sqlBuilder.append(line).append(" ")
if (line.endsWith(";")) {
val sql = sqlBuilder.substring(0, sqlBuilder.length - 1).trim()
try {
if (useBatch) {
stmt.addBatch(sql)
sqlBuilder.clear()
count++
if (count % batchSize == 0) stmt.executeBatch()
} else {
stmt.execute(sql)
}
} catch (e: Exception) {
log.error("执行SQL失败: {}", sql, e)
throw e
}
sqlBuilder.clear()
}
}
// Handle remaining SQL without semicolon
if (sqlBuilder.isNotEmpty()) {
val sql = sqlBuilder.toString().trim()
try {
if (useBatch) {
stmt.addBatch(sql)
stmt.executeBatch()
} else {
stmt.execute(sql)
}
} catch (e: SQLException) {
log.error("执行最后一条SQL失败: {}", sql, e)
throw e
}
}
// Execute remaining batch
if (useBatch && count % batchSize != 0) {
stmt.executeBatch()
}
}
}
}
}
}

View File

@ -0,0 +1,61 @@
package top.r3944realms.ltdmanager
import org.slf4j.LoggerFactory
import top.r3944realms.ltdmanager.napcat.data.Sex
import top.r3944realms.ltdmanager.napcat.events.NapCatEvent
import top.r3944realms.ltdmanager.napcat.events.account.SetQQProfileEvent
import top.r3944realms.ltdmanager.napcat.requests.account.SetQQProfileRequest
fun main() {
val logger = LoggerFactory.getLogger("log")
logger.info("Start")
// 创建请求
val request = SetQQProfileRequest(
nickname = "123",
personalNote = "232",
sex = Sex.FEMALE
)
// 序列化会自动添加type字段
val jsonStr = request.toJSON()
logger.info("Serialized: {}", jsonStr)
// 输出示例: {"type":"account/setQQProfile","nickname":"123","personal_note":"232","sex":"2"}
val decodeJson =
"""
{
"status": "ok",
"retcode": 0,
"data": {
"result": 0,
"errMsg": "string"
},
"message": "string",
"wording": "string",
"echo": "string"
}
""".trimIndent();
try {
when (val decoded = NapCatEvent.decodeEvent(decodeJson, request.type())) {
is SetQQProfileEvent -> {
println("""
反序列化成功:
{
"status": ${decoded.status},
"retcode": ${decoded.retcode},
"data": {
"result": ${decoded.data.result},
"errMsg": ${decoded.data.errorMsg}
},
"message": ${decoded.message},
"wording": ${decoded.wording},
"echo": ${decoded.echo}
}
""".trimIndent())
}
else -> println("未知请求类型")
}
} catch (e: Exception) {
println("反序列化失败: ${e.message}")
}
}

View File

@ -0,0 +1,4 @@
package top.r3944realms.ltdmanager.napcat
@Target(AnnotationTarget.CLASS)
annotation class Developing()

View File

@ -0,0 +1,134 @@
package top.r3944realms.ltdmanager.napcat
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.websocket.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import top.r3944realms.ltdmanager.napcat.events.NapCatEvent
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
import top.r3944realms.ltdmanager.napcat.requests.PrioritizedRequest
import top.r3944realms.ltdmanager.napcat.requests.PriorityMessageQueue
import kotlin.coroutines.coroutineContext
class NapCatClient(private val wsUrl: String, private val token: String) {
private val client = HttpClient(CIO) { install(WebSockets) }
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val logger = LoggerFactory.getLogger(NapCatClient::class.java)
// 请求-响应匹配队列FIFO
private val pendingResponses = Channel<CompletableDeferred<NapCatEvent>>(capacity = Channel.UNLIMITED)
private val mutex = Mutex()
// 事件通道(用于非请求响应的消息)
// 优先级队列(按优先级发送请求)
private val priorityQueue = PriorityMessageQueue()
private val eventChannel = Channel<NapCatEvent>(capacity = Channel.UNLIMITED)
private val _connectionState = MutableStateFlow(false)
val connectionState = _connectionState.asStateFlow()
// 子协程引用
private var receiverJob: Job? = null
private var senderJob: Job? = null
suspend fun start() {
receiverJob = scope.launch { launchReceiver() }
senderJob = scope.launch { launchSender() }
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun launchReceiver() {
try {
client.wss(
host = wsUrl.removePrefix("ws://").substringBefore(':'),
port = wsUrl.substringAfterLast(':').toInt(),
path = "/"
) {
send(Frame.Text("""{"token":"$token"}"""))
_connectionState.value = true
while (true) {
when (val frame = incoming.receive()) {
is Frame.Text -> {
val event = Json.decodeFromString<NapCatEvent>(frame.readText())
// 尝试匹配最近的请求
if (!pendingResponses.isEmpty) {
pendingResponses.tryReceive().getOrNull()?.complete(event)
} else {
eventChannel.send(event) // 非请求响应的消息
}
}
is Frame.Close -> break
else -> {}
}
}
}
} finally {
_connectionState.value = false
pendingResponses.close()
eventChannel.close()
priorityQueue.close()
}
}
private suspend fun launchSender() {
while (coroutineContext.isActive) {
try {
// 从优先级队列取出请求(自动按优先级排序)
val prioritized = priorityQueue.dequeue()
val request = prioritized.request
// 发送前注册响应监听器
val deferred = CompletableDeferred<NapCatEvent>()
mutex.withLock {
pendingResponses.send(deferred)
}
// 发送请求
client.webSocketSession(wsUrl).send(Frame.Text(Json.encodeToString(request)))
// 等待响应(超时由外层 sendRequest 控制)
deferred.await()
} catch (e: Exception) {
logger.error("发送请求失败", e)
delay(1000) // 错误时暂停1秒
}
}
}
/**
* 发送带优先级的请求
* @param priority 优先级HIGH_PRIORITY/DEFAULT_PRIORITY/LOW_PRIORITY
* @param timeout 超时时间毫秒
*/
suspend fun sendRequest(
request: NapCatRequest,
priority: Int = PrioritizedRequest.DEFAULT_PRIORITY,
timeout: Long = 5000
): NapCatEvent = withTimeout(timeout) {
val deferred = CompletableDeferred<NapCatEvent>()
// 将请求加入优先级队列
priorityQueue.enqueue(PrioritizedRequest(request, priority))
deferred.await() // 等待响应(由 launchSender 和 launchReceiver 协作完成)
}
val incomingEvents: ReceiveChannel<NapCatEvent> = eventChannel
private fun cleanup() {
_connectionState.value = false
pendingResponses.close()
eventChannel.close()
priorityQueue.close()
}
fun close() {
scope.cancel("NapCatClient closed")
cleanup()
}
}

View File

@ -0,0 +1,9 @@
package top.r3944realms.ltdmanager.napcat.data
import kotlinx.serialization.Serializable
@Serializable
sealed class ID {
class DoubleValue(val value: Double) : ID()
class StringValue(val value: String) : ID()
}

View File

@ -0,0 +1,14 @@
package top.r3944realms.ltdmanager.napcat.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* 性别
*/
@Serializable
enum class Sex(val value: String) {
@SerialName("0") UNKNOWN("0"),
@SerialName("1") MALE("1"),
@SerialName("2") FEMALE("2");
}

View File

@ -0,0 +1,78 @@
package top.r3944realms.ltdmanager.napcat.events
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.events.account.AbstractAccountEvent
/**
* 基础NapCat事件类
* @property httpStatusCode HTTP状态码
* @property createTime 创建时间戳
*/
@Serializable
abstract class NapCatEvent(
@Transient
open val httpStatusCode: HttpStatus = HttpStatus.OK,
@Transient
open val createTime: Long = System.currentTimeMillis()
) {
abstract fun type() :String
abstract fun subtype(): String
companion object {
private val eventTypeMap by lazy {
mutableMapOf<String, KSerializer<out NapCatEvent>>().apply {
putAll(AbstractAccountEvent.eventTypeMap)
}
}
fun decodeEvent(jsonString: String, type: String): NapCatEvent {
return eventTypeMap[type]?.let { serializer ->
// 如果是Account相关事件使用AccountEvent的json配置
if (type.startsWith("account/")) {
AbstractAccountEvent.json.decodeFromString(serializer, jsonString)
} else {
// 其他类型的事件可以使用默认的Json配置
val json = Json {
ignoreUnknownKeys = true
}
json.decodeFromString(serializer, jsonString)
}
} ?: throw SerializationException("Unknown request type: $type")
}
}
@Serializable
enum class Status(val value: String) {
@SerialName("ok") Ok("ok");
}
enum class HttpStatus(
val code: Int,
val message: String
) {
// 1xx Informational
CONTINUE(100, "Continue"),
SWITCHING_PROTOCOLS(101, "Switching Protocols"),
// 2xx Success
OK(200, "OK"),
CREATED(201, "Created"),
// 3xx Redirection
MOVED_PERMANENTLY(301, "Moved Permanently"),
// 4xx Client Error
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
// 5xx Server Error
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
SERVICE_UNAVAILABLE(503, "Service Unavailable");
companion object {
private val values = entries.associateBy { it.code }
fun fromCode(code: Int) = values[code] ?: throw IllegalArgumentException("无效的HTTP状态码: $code")
}
}
}

View File

@ -0,0 +1,75 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
import top.r3944realms.ltdmanager.napcat.events.NapCatEvent
/**
* QQ 账户相关响应抽象
* @property status 状态字符串
* @property retcode 返回代码
* @property message 消息
* @property wording 文字描述
* @property echo 回显字段 (可空)
*/
@Serializable
abstract class AbstractAccountEvent(
/**
* 状态字符串
*/
open val status: Status,
/**
* 返回代码
*/
open val retcode: Double,
/**
* 消息
*/
open val message: String,
/**
* 文字描述
*/
open val wording: String,
/**
* 回显字段
*/
open val echo: String? = null
) : NapCatEvent() {
override fun type(): String {
return "account/" + subtype()
}
companion object {
val eventTypeMap by lazy {
mutableMapOf<String, KSerializer<out NapCatEvent>>().apply {
put("account/set_qq_profile", SetQQProfileEvent.serializer())
put("account/ArkSharePeer", GetArkSharePeerEvent.serializer())
put("account/get_doubt_friends_add_request", GetDoubtFriendsAddRequestEvent.serializer())
put("account/set_doubt_friends_add_request", SetDoubtFriendsAddRequestEvent.serializer())
put("account/get_online_clients", GetOnlineClientsEvent.serializer())
put("account/mark_msg_as_read", MarkMsgAsReadEvent.serializer())
put("account/set_online_status", SetOnlineStatusEvent.serializer())
put("account/ArkShareGroup", MarkMsgAsReadEvent.serializer())
}
}
internal val json: Json by lazy {
Json {
ignoreUnknownKeys = true
serializersModule = SerializersModule {
polymorphic(NapCatEvent::class) {
subclass(GetArkSharePeerEvent::class)
subclass(SetQQProfileEvent::class)
subclass(GetDoubtFriendsAddRequestEvent::class)
subclass(SetDoubtFriendsAddRequestEvent::class)
subclass(GetOnlineClientsEvent::class)
subclass(MarkMsgAsReadEvent::class)
}
}
}
}
}
}

View File

@ -0,0 +1,29 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* 获取推荐群聊卡片
*/
@Serializable
data class ArkShareGroupEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
/**
* 卡片json
*/
val data: String
) : AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
override fun subtype(): String {
return "ArkShareGroup"
}
}

View File

@ -0,0 +1,40 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* 获取推荐好友/群聊卡片事件
* @property data 响应数据
*/
@Serializable
data class GetArkSharePeerEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
val data: Data
): AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
@Serializable
data class Data(
val errCode: Int,
val errMsg: String,
/**
* 卡片json
*/
@SerialName("arkJson")
val arkJSON: String,
)
override fun subtype(): String {
return "ArkSharePeer"
}
}

View File

@ -0,0 +1,43 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* 获取被过滤好友请求响应
* @property data 响应数据
*/
@Serializable
data class GetDoubtFriendsAddRequestEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
val data: List<Datum>,
): AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
@Serializable
data class Datum (
val flag: String,
@SerialName("group_code")
val groupCode: String,
val msg: String,
val nick: String,
val reason: String,
val source: String,
val time: String,
val type: String,
val uin: String
)
override fun subtype(): String {
return "get_doubt_friends_add_request"
}
}

View File

@ -0,0 +1,29 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import top.r3944realms.ltdmanager.napcat.Developing
/**
* 获取当前账号在线客户端列表
*/
@Developing
@Serializable
data class GetOnlineClientsEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
val data: List<String>,
): AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
override fun subtype(): String {
return "get_online_clients"
}
}

View File

@ -0,0 +1,25 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* 设置消息已读
*/
@Serializable
data class MarkMsgAsReadEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
): AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
override fun subtype(): String {
return "mark_msg_as_read"
}
}

View File

@ -0,0 +1,28 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.JsonObject
/**
* 处理被过滤好友请求响应
*/
@Serializable
data class SetDoubtFriendsAddRequestEvent (
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
val data: JsonObject,
) : AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
override fun subtype(): String {
return "set_doubt_friends_add_request"
}
}

View File

@ -0,0 +1,24 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.JsonElement
@Serializable
data class SetOnlineStatusEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
val data: JsonElement? = null,
) : AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
override fun subtype(): String = "/set_online_status"
}

View File

@ -0,0 +1,54 @@
package top.r3944realms.ltdmanager.napcat.events.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* QQ设置个人资料事件响应
* @property data 响应数据
*/
@Serializable
data class SetQQProfileEvent(
@Transient
val status0: Status = Status.Ok,
@Transient
val retcode0: Double = 0.0,
@Transient
val message0: String = "",
@Transient
val wording0: String = "",
@Transient
val echo0: String? = null,
/**
* 响应数据
*/
val data: Data,
): AbstractAccountEvent(status0, retcode0, message0, wording0, echo0) {
/**
* 响应数据
* @property result 相关数字
* @property errorMsg 错误信息(成功时为null)
*/
@Serializable
data class Data(
/**
* 相关数字
*/
@SerialName("result")
val result: Double,
/**
* 错误信息
*/
@SerialName("errMsg")
val errorMsg: String? = null
)
val isSuccess: Boolean get() = status == Status.Ok && retcode == 0.0
override fun subtype(): String {
return "set_qq_profile"
}
}

View File

@ -0,0 +1,21 @@
package top.r3944realms.ltdmanager.napcat.requests
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* 请求内容
* @property createTime 创建时间(用于相同优先级时排序)
*/
@Serializable
abstract class NapCatRequest(
@Transient
open val createTime: Long = System.currentTimeMillis()
) {
abstract fun toJSON(): String
fun type(): String {
return header() + path()
}
abstract fun path(): String
abstract fun header(): String
}

View File

@ -0,0 +1,22 @@
package top.r3944realms.ltdmanager.napcat.requests
/**
* 带优先级的消息封装
* @property request 原始请求
* @property priority 优先级数值(越大优先级越高)
*/
data class PrioritizedRequest(
val request: NapCatRequest,
val priority: Int = DEFAULT_PRIORITY,
) :Comparable<PrioritizedRequest> {
companion object {
const val HIGH_PRIORITY = 1000
const val DEFAULT_PRIORITY = 500
const val LOW_PRIORITY = 100
}
override fun compareTo(other: PrioritizedRequest): Int {
return compareValuesBy(other, this,
{ it.priority },
{ it.request.createTime }) // 优先级相同则先创建的优先
}
}

View File

@ -0,0 +1,33 @@
package top.r3944realms.ltdmanager.napcat.requests
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.withContext
import java.util.concurrent.PriorityBlockingQueue
/**
* 线程安全的优先级消息队列
*/
class PriorityMessageQueue {
private val queue = PriorityBlockingQueue<PrioritizedRequest>()
private val pendingSignal = Channel<Unit>(Channel.UNLIMITED)
suspend fun enqueue(request: PrioritizedRequest) {
queue.put(request)
pendingSignal.send(Unit) // 通知有新消息
}
suspend fun dequeue(): PrioritizedRequest {
// 队列为空时挂起等待
if (queue.isEmpty()) {
pendingSignal.receive()
}
return withContext(Dispatchers.IO) {
queue.take()
}
}
fun size(): Int = queue.size
fun close() {
pendingSignal.close()
}
}

View File

@ -0,0 +1,12 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.Serializable
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
@Serializable
abstract class AbstractAccountRequest
: NapCatRequest() {
override fun header(): String {
return "account"
}
}

View File

@ -0,0 +1,16 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class ArkShareGroupRequest(
@SerialName("group_id")
val groupId: String
): AbstractAccountRequest() {
override fun toJSON(): String = Json.encodeToString(this)
override fun path(): String = "/ArkShareGroup"
}

View File

@ -0,0 +1,41 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.data.ID
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* 获取推荐好友/群聊卡片
*/
@Serializable
data class ArkSharePeerRequest(
/**
* 和user_id二选一
*/
@SerialName("group_id")
val groupID: ID? = null,
/**
* 对方手机号
*/
val phoneNumber: String? = null,
/**
* 和group_id二选一
*/
@SerialName("user_id")
val userID: ID? = null
) : AbstractAccountRequest() {
override fun toJSON(): String {
return Json.encodeToString(this)
}
override fun path(): String {
return "/ArkSharePeer"
}
}

View File

@ -0,0 +1,23 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* 获取被过滤好友请求
*/
@Serializable
data class GetDoubtFriendsAddRequestRequest(
val count: Int = 50
) : AbstractAccountRequest() {
override fun toJSON(): String {
return Json.encodeToString(this)
}
override fun path(): String {
return "/get_doubt_friends_add_request"
}
}

View File

@ -0,0 +1,21 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.Serializable
import top.r3944realms.ltdmanager.napcat.Developing
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* 设置消息已读
*/
@Developing
@Serializable
class GetOnlineClientRequest
: AbstractAccountRequest(){
override fun toJSON(): String {
return "{}"
}
override fun path(): String {
return "/get_online_clients"
}
}

View File

@ -0,0 +1,36 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.data.ID
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* 设置消息已读
*/
@Serializable
data class MarkMsgAsReadRequest (
/**
* 与user_id二选一
*/
@SerialName("group_id")
val groupID: ID? = null,
/**
* 与group_id二选一
*/
@SerialName("user_id")
val userID: ID? = null
) : AbstractAccountRequest() {
override fun toJSON(): String {
return Json.encodeToString(this)
}
override fun path(): String {
return "/mark_msg_as_read"
}
}

View File

@ -0,0 +1,27 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* 处理被过滤好友请求
*/
@Serializable
data class SetDoubtFriendsAddRequestRequest(
/**
* 4.7.43 版本中该值无效
*/
val approve: Boolean,
val flag: String
) : AbstractAccountRequest() {
override fun toJSON(): String {
return Json.encodeToString(this)
}
override fun path(): String {
return "/set_doubt_friends_add_request"
}
}

View File

@ -0,0 +1,28 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class SetOnlineStatusRequest(
/**
* 电量
*/
val batteryStatus: Double,
/**
* 详情看顶部
*/
val extStatus: Double,
/**
* 详情看顶部
*/
val status: Double
) : AbstractAccountRequest() {
override fun toJSON(): String = Json.encodeToString(this)
override fun path(): String = "/set_online_status"
}

View File

@ -0,0 +1,43 @@
package top.r3944realms.ltdmanager.napcat.requests.account
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import top.r3944realms.ltdmanager.napcat.data.Sex
import top.r3944realms.ltdmanager.napcat.requests.NapCatRequest
/**
* QQ设置个人资料事件请求
* @property nickname 昵称
* @property personalNote 个性签名(可空)
* @property sex 性别(可空)
*/
@Serializable
data class SetQQProfileRequest(
/**
* 昵称
*/
val nickname: String,
/**
* 个性签名
*/
@SerialName("personal_note")
val personalNote: String? = null,
/**
* 性别
*/
val sex: Sex? = null
) : AbstractAccountRequest() {
override fun toJSON(): String {
return Json.encodeToString(this)
}
override fun path(): String {
return "/set_qq_profile"
}
}

View File

@ -0,0 +1,55 @@
package top.r3944realms.ltdmanager.utils
import top.r3944realms.ltdmanager.core.config.YamlConfigLoader
import java.nio.charset.StandardCharsets
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
object CryptoUtil {
private const val SECRET_KEY = "ltd25r3944realms"
private const val ALGORITHM = "AES"
private val secretKey: String
get() {
return YamlConfigLoader.loadCryptoConfig().secretKey ?: SECRET_KEY
}
// 解密
fun decrypt(encryptedText: String): String {
return decrypt(encryptedText, secretKey)
}
// 加密
fun encrypt(plainText: String): String {
return encrypt(plainText, secretKey)
}
fun decrypt(encryptedText: String, secretKey: String): String {
try {
val key = SecretKeySpec(secretKey.toByteArray(), ALGORITHM)
val cipher = Cipher.getInstance(ALGORITHM)
cipher.init(Cipher.DECRYPT_MODE, key)
val decodedBytes = Base64.getDecoder().decode(encryptedText)
val decryptedBytes = cipher.doFinal(decodedBytes)
return String(decryptedBytes, StandardCharsets.UTF_8)
} catch (e: Exception) {
throw RuntimeException("解密失败", e)
}
}
fun encrypt(plainText: String, secretKey: String): String {
try {
val key = SecretKeySpec(secretKey.toByteArray(), ALGORITHM)
val cipher = Cipher.getInstance(ALGORITHM)
cipher.init(Cipher.ENCRYPT_MODE, key)
val encryptedBytes = cipher.doFinal(plainText.toByteArray(StandardCharsets.UTF_8))
return Base64.getEncoder().encodeToString(encryptedBytes)
} catch (e: Exception) {
throw RuntimeException("加密失败", e)
}
}
}

View File

@ -0,0 +1,24 @@
package top.r3944realms.ltdmanager.utils
object NamingConventionUtil {
fun camelToHyphen(str: String): String {
return str.replace(Regex("([a-z0-9])([A-Z])"), "$1-$2").lowercase()
}
fun hyphenToCamel(name: String): String {
val result = StringBuilder()
var nextUpper = false
for (c in name) {
when {
c == '-' -> nextUpper = true
nextUpper -> {
result.append(c.uppercaseChar())
nextUpper = false
}
else -> result.append(c)
}
}
return result.toString()
}
}

View File

@ -0,0 +1,56 @@
package top.r3944realms.ltdmanager.utils
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import java.io.FileInputStream
import java.io.FileWriter
import java.io.IOException
object YamlUpdater {
/**
* 更新 YAML 文件字段值保留原始格式
* @param filePath YAML 文件路径
* @param keyPath 层级字段路径 "database.url"
* @param newValue 新值
*/
@Throws(IOException::class)
fun updateYamlValue(filePath: String, keyPath: String, newValue: String) {
// 1. 读取原始 YAML 文件
// 标准化路径
val normalizedPath = filePath.replaceFirst("^/(.:/)".toRegex(), "$1") // 修复Windows路径
val yaml = Yaml()
val yamlData: Map<String, Any>
FileInputStream(normalizedPath).use { inputStream ->
yamlData = yaml.load(inputStream)
}
// 2. 更新嵌套 Map 中的值
updateNestedValue(yamlData, keyPath.split("\\.".toRegex()).toTypedArray(), 0, newValue)
// 3. 配置 YAML 输出格式(保留原始风格)
val options = DumperOptions().apply {
defaultFlowStyle = DumperOptions.FlowStyle.FLOW // 使用 {} 风格
indent = 2 // 缩进2空格
isPrettyFlow = true // 保持可读性
}
// 4. 写回文件
FileWriter(normalizedPath).use { writer ->
Yaml(options).dump(yamlData, writer)
}
}
private fun updateNestedValue(map: Map<String, Any>, keys: Array<String>, index: Int, newValue: Any) {
if (index == keys.size - 1) {
(map as MutableMap<String, Any>)[keys[index]] = newValue // 更新最终字段
} else {
val nested = map[keys[index]]
if (nested is Map<*, *>) {
@Suppress("UNCHECKED_CAST")
val nestedMap = nested as Map<String, Any>
updateNestedValue(nestedMap, keys, index + 1, newValue)
} else {
throw IllegalArgumentException("Invalid YAML path: ${keys.joinToString(".")}")
}
}
}
}

View File

@ -0,0 +1,14 @@
# 重载后注释将会消失
database:
# 数据库地址
url: "jdbc:mysql://localhost:3306/quizdb?useSSL=false&serverTimezone=UTC"
# 数据库用户名
user: "root"
# 格式为 ENC(XXX),若不是则会在加载完成配置后自动加密
encrypted-password: "123123aa"
crypto:
# 示例AES加密密钥 密钥字段必需是16字节的正整数倍
secret-key: "ltd25r3944realms"
websocket:
url:
token:

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<!-- 定义日志格式 -->
<Properties>
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n</Property>
<Property name="LOG_FILE">logs/app.log</Property>
</Properties>
<!-- 定义 Appenders -->
<Appenders>
<!-- 控制台输出 -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}" />
</Console>
<!-- 文件输出 -->
<File name="File" fileName="${LOG_FILE}">
<PatternLayout pattern="${LOG_PATTERN}" />
</File>
</Appenders>
<!-- 定义日志记录规则 -->
<Loggers>
<!-- 应用程序日志 -->
<Logger name="com.example" level="debug" additivity="false">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Logger>
<!-- Root 日志 -->
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>