mirror of
https://github.com/LamGC/ScalaBot.git
synced 2025-07-01 12:57:24 +00:00
Compare commits
56 Commits
Author | SHA1 | Date | |
---|---|---|---|
ac0a398afc
|
|||
145e5a2141
|
|||
b5c85e213b
|
|||
746221a085
|
|||
24f34aa27f
|
|||
31366575a9
|
|||
37c3275bb6
|
|||
72e26bd677
|
|||
9aab3c2a24
|
|||
cac055bb08
|
|||
efbb57f1f7
|
|||
5e18149640
|
|||
0a5313e94a
|
|||
a0afde52ac
|
|||
ef37f3b2d7
|
|||
6e59a9a5ac
|
|||
a44732a7f6
|
|||
95ad251826
|
|||
8174f2a3a2
|
|||
478480014a
|
|||
830f05c90a
|
|||
8be0978783 | |||
ce613787f6
|
|||
2389d082f4
|
|||
27f54c3c36
|
|||
7b985ce325
|
|||
77b7a7cd08
|
|||
e8b746b3f8
|
|||
d24572a4f3
|
|||
f11290c73d
|
|||
1f2ab0f9b1
|
|||
d14ef9de36
|
|||
3e51327ed7
|
|||
93cf5c4e2f
|
|||
e12f858690
|
|||
3e99d7d033
|
|||
8131f41313
|
|||
270e744bcf
|
|||
d84465ebd9
|
|||
18bc3a8d48
|
|||
2b88134207
|
|||
142eddfa28
|
|||
64849adfab
|
|||
29bd12a8dd
|
|||
9cdf10ccc2
|
|||
4210efef3b
|
|||
bc0f3be32c
|
|||
c5f28e395e
|
|||
1172caa8d7
|
|||
eb95436404
|
|||
804d0e3012
|
|||
1281dbcabe
|
|||
1cd26b3b25
|
|||
19162dcaef
|
|||
0748afaff5
|
|||
b20b25bc7b
|
@ -7,5 +7,5 @@ allprojects {
|
|||||||
|
|
||||||
}
|
}
|
||||||
group = "net.lamgc"
|
group = "net.lamgc"
|
||||||
version = "0.1.0"
|
version = "0.3.1"
|
||||||
}
|
}
|
@ -11,7 +11,7 @@ dependencies {
|
|||||||
|
|
||||||
implementation("org.slf4j:slf4j-api:1.7.36")
|
implementation("org.slf4j:slf4j-api:1.7.36")
|
||||||
implementation("io.github.microutils:kotlin-logging:2.1.21")
|
implementation("io.github.microutils:kotlin-logging:2.1.21")
|
||||||
implementation("ch.qos.logback:logback-classic:1.2.10")
|
implementation("ch.qos.logback:logback-classic:1.2.11")
|
||||||
|
|
||||||
val aetherVersion = "1.1.0"
|
val aetherVersion = "1.1.0"
|
||||||
implementation("org.eclipse.aether:aether-api:$aetherVersion")
|
implementation("org.eclipse.aether:aether-api:$aetherVersion")
|
||||||
@ -22,18 +22,21 @@ dependencies {
|
|||||||
implementation("org.eclipse.aether:aether-connector-basic:$aetherVersion")
|
implementation("org.eclipse.aether:aether-connector-basic:$aetherVersion")
|
||||||
implementation("org.apache.maven:maven-aether-provider:3.3.9")
|
implementation("org.apache.maven:maven-aether-provider:3.3.9")
|
||||||
|
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0")
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1")
|
||||||
|
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.20")
|
||||||
implementation("com.google.code.gson:gson:2.9.0")
|
implementation("com.google.code.gson:gson:2.9.0")
|
||||||
|
|
||||||
implementation("org.jdom:jdom2:2.0.6.1")
|
implementation("org.jdom:jdom2:2.0.6.1")
|
||||||
|
|
||||||
implementation("org.telegram:telegrambots-abilities:5.6.0")
|
implementation("org.telegram:telegrambots-abilities:6.0.1")
|
||||||
implementation("org.telegram:telegrambots:5.6.0")
|
implementation("org.telegram:telegrambots:6.0.1")
|
||||||
|
|
||||||
implementation("io.prometheus:simpleclient:0.15.0")
|
implementation("io.prometheus:simpleclient:0.15.0")
|
||||||
implementation("io.prometheus:simpleclient_httpserver:0.15.0")
|
implementation("io.prometheus:simpleclient_httpserver:0.15.0")
|
||||||
|
|
||||||
testImplementation(kotlin("test"))
|
testImplementation(kotlin("test"))
|
||||||
|
testImplementation("io.mockk:mockk:1.12.3")
|
||||||
|
testImplementation("com.github.stefanbirkner:system-lambda:1.2.1")
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.test {
|
tasks.test {
|
||||||
|
@ -1,17 +0,0 @@
|
|||||||
package net.lamgc.scalabot.util;
|
|
||||||
|
|
||||||
final class ByteUtils {
|
|
||||||
|
|
||||||
private ByteUtils() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String bytesToHexString(byte[] bytes) {
|
|
||||||
StringBuilder builder = new StringBuilder();
|
|
||||||
for (byte aByte : bytes) {
|
|
||||||
String hexBit = Integer.toHexString(aByte & 0xFF);
|
|
||||||
builder.append(hexBit.length() == 1 ? "0" + hexBit : hexBit);
|
|
||||||
}
|
|
||||||
return builder.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -13,12 +13,15 @@ import org.eclipse.aether.artifact.Artifact
|
|||||||
import org.eclipse.aether.repository.Authentication
|
import org.eclipse.aether.repository.Authentication
|
||||||
import org.eclipse.aether.repository.Proxy
|
import org.eclipse.aether.repository.Proxy
|
||||||
import org.eclipse.aether.repository.RemoteRepository
|
import org.eclipse.aether.repository.RemoteRepository
|
||||||
|
import org.eclipse.aether.repository.RepositoryPolicy
|
||||||
import org.telegram.telegrambots.bots.DefaultBotOptions
|
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||||
import org.telegram.telegrambots.meta.ApiConstants
|
import org.telegram.telegrambots.meta.ApiConstants
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
private val log = KotlinLogging.logger { }
|
private val log = KotlinLogging.logger { }
|
||||||
|
|
||||||
@ -32,7 +35,14 @@ internal data class BotAccount(
|
|||||||
val name: String,
|
val name: String,
|
||||||
val token: String,
|
val token: String,
|
||||||
val creatorId: Long = -1
|
val creatorId: Long = -1
|
||||||
)
|
) {
|
||||||
|
|
||||||
|
val id
|
||||||
|
// 不要想着每次获取都要从 token 里取出有性能损耗.
|
||||||
|
// 由于 Gson 解析方式, 如果不这么做, 会出现 token 设置前 id 初始化完成, 就只有"0"了,
|
||||||
|
// 虽然能过单元测试, 但实际使用过程是不能正常用的.
|
||||||
|
get() = token.substringBefore(":").toLong()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 机器人配置.
|
* 机器人配置.
|
||||||
@ -92,20 +102,40 @@ internal data class MetricsConfig(
|
|||||||
* @property layout 仓库布局版本, Maven 2 及以上使用 `default`, Maven 1 使用 `legacy`.
|
* @property layout 仓库布局版本, Maven 2 及以上使用 `default`, Maven 1 使用 `legacy`.
|
||||||
*/
|
*/
|
||||||
internal data class MavenRepositoryConfig(
|
internal data class MavenRepositoryConfig(
|
||||||
|
val id: String? = null,
|
||||||
val url: URL,
|
val url: URL,
|
||||||
val proxy: Proxy? = Proxy("http", "127.0.0.1", 1080),
|
val proxy: Proxy? = null,
|
||||||
val layout: String = "default",
|
val layout: String = "default",
|
||||||
|
val enableReleases: Boolean = true,
|
||||||
|
val enableSnapshots: Boolean = true,
|
||||||
// 可能要设计个 type 来判断解析成什么类型的 Authentication.
|
// 可能要设计个 type 来判断解析成什么类型的 Authentication.
|
||||||
val authentication: Authentication? = null
|
val authentication: Authentication? = null
|
||||||
) {
|
) {
|
||||||
|
|
||||||
fun toRemoteRepository(): RemoteRepository {
|
fun toRemoteRepository(proxyConfig: ProxyConfig): RemoteRepository {
|
||||||
val builder = RemoteRepository.Builder(null, checkRepositoryLayout(layout), url.toString())
|
val builder =
|
||||||
|
RemoteRepository.Builder(id ?: createDefaultRepositoryId(), checkRepositoryLayout(layout), url.toString())
|
||||||
if (proxy != null) {
|
if (proxy != null) {
|
||||||
builder.setProxy(proxy)
|
builder.setProxy(proxy)
|
||||||
} else if (Const.config.proxy.type == DefaultBotOptions.ProxyType.HTTP) {
|
} else if (proxyConfig.type == DefaultBotOptions.ProxyType.HTTP) {
|
||||||
builder.setProxy(Const.config.proxy.toAetherProxy())
|
builder.setProxy(proxyConfig.toAetherProxy())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
builder.setReleasePolicy(
|
||||||
|
RepositoryPolicy(
|
||||||
|
enableReleases,
|
||||||
|
RepositoryPolicy.UPDATE_POLICY_NEVER,
|
||||||
|
RepositoryPolicy.CHECKSUM_POLICY_FAIL
|
||||||
|
)
|
||||||
|
)
|
||||||
|
builder.setSnapshotPolicy(
|
||||||
|
RepositoryPolicy(
|
||||||
|
enableSnapshots,
|
||||||
|
RepositoryPolicy.UPDATE_POLICY_ALWAYS,
|
||||||
|
RepositoryPolicy.CHECKSUM_POLICY_WARN
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return builder.build()
|
return builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,6 +147,13 @@ internal data class MavenRepositoryConfig(
|
|||||||
}
|
}
|
||||||
return type
|
return type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val repoNumber = AtomicInteger(1)
|
||||||
|
|
||||||
|
fun createDefaultRepositoryId(): String {
|
||||||
|
return "Repository-${repoNumber.getAndIncrement()}"
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,11 +164,13 @@ internal data class MavenRepositoryConfig(
|
|||||||
* @property proxy Telegram API 代理配置.
|
* @property proxy Telegram API 代理配置.
|
||||||
* @property metrics 运行指标数据配置. 可通过时序数据库记录运行数据.
|
* @property metrics 运行指标数据配置. 可通过时序数据库记录运行数据.
|
||||||
* @property mavenRepositories Maven 远端仓库配置.
|
* @property mavenRepositories Maven 远端仓库配置.
|
||||||
|
* @property mavenLocalRepository Maven 本地仓库路径. 相对于运行目录 (而不是 DATA_ROOT 目录)
|
||||||
*/
|
*/
|
||||||
internal data class AppConfig(
|
internal data class AppConfig(
|
||||||
val proxy: ProxyConfig = ProxyConfig(),
|
val proxy: ProxyConfig = ProxyConfig(),
|
||||||
val metrics: MetricsConfig = MetricsConfig(),
|
val metrics: MetricsConfig = MetricsConfig(),
|
||||||
val mavenRepositories: List<MavenRepositoryConfig> = emptyList()
|
val mavenRepositories: List<MavenRepositoryConfig> = emptyList(),
|
||||||
|
val mavenLocalRepository: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -152,7 +191,10 @@ internal enum class AppPaths(
|
|||||||
* 提示: 结尾不带 `/`.
|
* 提示: 结尾不带 `/`.
|
||||||
*/
|
*/
|
||||||
DATA_ROOT(fileSupplier = {
|
DATA_ROOT(fileSupplier = {
|
||||||
File(System.getProperty(PathConst.PROP_DATA_PATH) ?: System.getenv(PathConst.ENV_DATA_PATH) ?: ".")
|
File(
|
||||||
|
System.getProperty(PathConst.PROP_DATA_PATH) ?: System.getenv(PathConst.ENV_DATA_PATH)
|
||||||
|
?: System.getProperty("user.dir") ?: "."
|
||||||
|
)
|
||||||
}, initializer = {
|
}, initializer = {
|
||||||
val f = file
|
val f = file
|
||||||
if (!f.exists()) {
|
if (!f.exists()) {
|
||||||
@ -167,7 +209,8 @@ internal enum class AppPaths(
|
|||||||
AppConfig(
|
AppConfig(
|
||||||
mavenRepositories = listOf(
|
mavenRepositories = listOf(
|
||||||
MavenRepositoryConfig(
|
MavenRepositoryConfig(
|
||||||
URL(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL)
|
id = "central",
|
||||||
|
url = URL(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
), it
|
), it
|
||||||
@ -220,9 +263,9 @@ internal enum class AppPaths(
|
|||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object PathConst {
|
private object PathConst {
|
||||||
private const val PROP_DATA_PATH = "bot.path.data"
|
const val PROP_DATA_PATH = "bot.path.data"
|
||||||
private const val ENV_DATA_PATH = "BOT_DATA_PATH"
|
const val ENV_DATA_PATH = "BOT_DATA_PATH"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -256,9 +299,17 @@ private fun AppPaths.defaultInitializer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun initialFiles() {
|
internal fun initialFiles() {
|
||||||
|
val configFilesNotInitialized = !AppPaths.DEFAULT_CONFIG_APPLICATION.file.exists()
|
||||||
|
&& !AppPaths.DEFAULT_CONFIG_BOT.file.exists()
|
||||||
|
|
||||||
for (path in AppPaths.values()) {
|
for (path in AppPaths.values()) {
|
||||||
path.initial()
|
path.initial()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (configFilesNotInitialized) {
|
||||||
|
log.warn { "配置文件已初始化, 请根据需要修改配置文件后重新启动本程序." }
|
||||||
|
exitProcess(1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private object GsonConst {
|
private object GsonConst {
|
||||||
|
@ -4,25 +4,32 @@ import io.prometheus.client.exporter.HTTPServer
|
|||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
import mu.KotlinLogging
|
import mu.KotlinLogging
|
||||||
import net.lamgc.scalabot.util.registerShutdownHook
|
import net.lamgc.scalabot.util.registerShutdownHook
|
||||||
|
import org.eclipse.aether.repository.LocalRepository
|
||||||
import org.telegram.telegrambots.bots.DefaultBotOptions
|
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||||
import org.telegram.telegrambots.meta.TelegramBotsApi
|
import org.telegram.telegrambots.meta.TelegramBotsApi
|
||||||
import org.telegram.telegrambots.meta.generics.BotSession
|
import org.telegram.telegrambots.meta.generics.BotSession
|
||||||
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
|
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.nio.file.attribute.PosixFilePermission
|
||||||
|
import java.nio.file.attribute.PosixFilePermissions
|
||||||
|
import kotlin.io.path.createDirectories
|
||||||
|
import kotlin.io.path.exists
|
||||||
|
import kotlin.io.path.isReadable
|
||||||
|
import kotlin.io.path.isWritable
|
||||||
import kotlin.system.exitProcess
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
private val log = KotlinLogging.logger { }
|
private val log = KotlinLogging.logger { }
|
||||||
|
|
||||||
private val launcher = Launcher()
|
|
||||||
.registerShutdownHook()
|
|
||||||
|
|
||||||
fun main(args: Array<String>): Unit = runBlocking {
|
fun main(args: Array<String>): Unit = runBlocking {
|
||||||
log.info { "ScalaBot 正在启动中..." }
|
log.info { "ScalaBot 正在启动中..." }
|
||||||
log.info { "数据目录: ${AppPaths.DATA_ROOT}" }
|
log.info { "数据目录: ${AppPaths.DATA_ROOT}" }
|
||||||
log.debug { "启动参数: ${args.joinToString(prefix = "[", postfix = "]")}" }
|
log.debug { "启动参数: ${args.joinToString(prefix = "[", postfix = "]")}" }
|
||||||
initialFiles()
|
initialFiles()
|
||||||
if (Const.config.metrics.enable) {
|
|
||||||
startMetricsServer()
|
val launcher = Launcher()
|
||||||
}
|
.registerShutdownHook()
|
||||||
|
startMetricsServer()
|
||||||
if (!launcher.launch()) {
|
if (!launcher.launch()) {
|
||||||
exitProcess(1)
|
exitProcess(1)
|
||||||
}
|
}
|
||||||
@ -32,11 +39,16 @@ fun main(args: Array<String>): Unit = runBlocking {
|
|||||||
* 启动运行指标服务器.
|
* 启动运行指标服务器.
|
||||||
* 使用 Prometheus 指标格式.
|
* 使用 Prometheus 指标格式.
|
||||||
*/
|
*/
|
||||||
fun startMetricsServer() {
|
internal fun startMetricsServer(config: MetricsConfig = Const.config.metrics) {
|
||||||
|
if (!config.enable) {
|
||||||
|
log.debug { "运行指标服务器已禁用." }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
val builder = HTTPServer.Builder()
|
val builder = HTTPServer.Builder()
|
||||||
.withDaemonThreads(true)
|
.withDaemonThreads(true)
|
||||||
.withPort(Const.config.metrics.port)
|
.withPort(config.port)
|
||||||
.withHostname(Const.config.metrics.bindAddress)
|
.withHostname(config.bindAddress)
|
||||||
|
|
||||||
val httpServer = builder
|
val httpServer = builder
|
||||||
.build()
|
.build()
|
||||||
@ -44,7 +56,7 @@ fun startMetricsServer() {
|
|||||||
log.info { "运行指标服务器已启动. (Port: ${httpServer.port})" }
|
log.info { "运行指标服务器已启动. (Port: ${httpServer.port})" }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class Launcher : AutoCloseable {
|
internal class Launcher(private val config: AppConfig = Const.config) : AutoCloseable {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
@ -53,6 +65,46 @@ internal class Launcher : AutoCloseable {
|
|||||||
|
|
||||||
private val botApi = TelegramBotsApi(DefaultBotSession::class.java)
|
private val botApi = TelegramBotsApi(DefaultBotSession::class.java)
|
||||||
private val botSessionMap = mutableMapOf<ScalaBot, BotSession>()
|
private val botSessionMap = mutableMapOf<ScalaBot, BotSession>()
|
||||||
|
private val mavenLocalRepository = getMavenLocalRepository()
|
||||||
|
|
||||||
|
private fun getMavenLocalRepository(): LocalRepository {
|
||||||
|
val localPath =
|
||||||
|
if (config.mavenLocalRepository != null && config.mavenLocalRepository.isNotEmpty()) {
|
||||||
|
val repoPath = AppPaths.DATA_ROOT.file.toPath()
|
||||||
|
.resolve(config.mavenLocalRepository)
|
||||||
|
.apply {
|
||||||
|
if (!exists()) {
|
||||||
|
if (!parent.isWritable() || !parent.isReadable()) {
|
||||||
|
throw IOException("Unable to read and write the directory where Maven repository is located.")
|
||||||
|
}
|
||||||
|
if (System.getProperty("os.name").lowercase().startsWith("windows")) {
|
||||||
|
createDirectories()
|
||||||
|
} else {
|
||||||
|
createDirectories(
|
||||||
|
PosixFilePermissions.asFileAttribute(
|
||||||
|
setOf(
|
||||||
|
PosixFilePermission.OWNER_READ,
|
||||||
|
PosixFilePermission.OWNER_WRITE,
|
||||||
|
PosixFilePermission.GROUP_READ,
|
||||||
|
PosixFilePermission.GROUP_WRITE,
|
||||||
|
PosixFilePermission.OTHERS_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.toRealPath()
|
||||||
|
.toFile()
|
||||||
|
repoPath
|
||||||
|
} else {
|
||||||
|
File("${System.getProperty("user.home")}/.m2/repository")
|
||||||
|
}
|
||||||
|
if (!localPath.exists()) {
|
||||||
|
localPath.mkdirs()
|
||||||
|
}
|
||||||
|
return LocalRepository(localPath)
|
||||||
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun launch(): Boolean {
|
fun launch(): Boolean {
|
||||||
@ -60,6 +112,9 @@ internal class Launcher : AutoCloseable {
|
|||||||
if (botConfigs.isEmpty()) {
|
if (botConfigs.isEmpty()) {
|
||||||
log.warn { "尚未配置任何机器人, 请先配置机器人后再启动本程序." }
|
log.warn { "尚未配置任何机器人, 请先配置机器人后再启动本程序." }
|
||||||
return false
|
return false
|
||||||
|
} else if (botConfigs.none { it.enabled }) {
|
||||||
|
log.warn { "配置文件中没有已启用的机器人, 请至少启用一个机器人." }
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
for (botConfig in botConfigs) {
|
for (botConfig in botConfigs) {
|
||||||
try {
|
try {
|
||||||
@ -81,15 +136,15 @@ internal class Launcher : AutoCloseable {
|
|||||||
val proxyConfig =
|
val proxyConfig =
|
||||||
if (botConfig.proxy != null && botConfig.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
|
if (botConfig.proxy != null && botConfig.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
|
||||||
botConfig.proxy
|
botConfig.proxy
|
||||||
} else if (Const.config.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
|
} else if (config.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
|
||||||
Const.config.proxy
|
config.proxy
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
if (proxyConfig != null) {
|
if (proxyConfig != null) {
|
||||||
proxyType = proxyConfig.type
|
proxyType = proxyConfig.type
|
||||||
proxyHost = Const.config.proxy.host
|
proxyHost = config.proxy.host
|
||||||
proxyPort = Const.config.proxy.port
|
proxyPort = config.proxy.port
|
||||||
log.debug { "机器人 `${botConfig.account.name}` 已启用代理配置: $proxyConfig" }
|
log.debug { "机器人 `${botConfig.account.name}` 已启用代理配置: $proxyConfig" }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,20 +154,26 @@ internal class Launcher : AutoCloseable {
|
|||||||
}
|
}
|
||||||
val account = botConfig.account
|
val account = botConfig.account
|
||||||
|
|
||||||
val remoteRepositories = Const.config.mavenRepositories
|
val remoteRepositories = config.mavenRepositories
|
||||||
.map(MavenRepositoryConfig::toRemoteRepository)
|
.map { it.toRemoteRepository(config.proxy) }
|
||||||
.toMutableList().apply {
|
.toMutableList().apply {
|
||||||
add(MavenRepositoryExtensionFinder.getMavenCentralRepository(proxy = Const.config.proxy.toAetherProxy()))
|
if (this.none {
|
||||||
|
it.url == MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL
|
||||||
|
|| it.url == MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL.trimEnd('/')
|
||||||
|
}) {
|
||||||
|
add(MavenRepositoryExtensionFinder.getMavenCentralRepository(proxy = config.proxy.toAetherProxy()))
|
||||||
|
}
|
||||||
}.toList()
|
}.toList()
|
||||||
val extensionPackageFinders = setOf(
|
val extensionPackageFinders = setOf(
|
||||||
MavenRepositoryExtensionFinder(
|
MavenRepositoryExtensionFinder(
|
||||||
|
localRepository = mavenLocalRepository,
|
||||||
remoteRepositories = remoteRepositories,
|
remoteRepositories = remoteRepositories,
|
||||||
proxy = Const.config.proxy.toAetherProxy()
|
proxy = config.proxy.toAetherProxy()
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
val bot = ScalaBot(
|
val bot = ScalaBot(
|
||||||
BotDBMaker.getBotMaker(account),
|
BotDBMaker.getBotDbInstance(account),
|
||||||
botOption,
|
botOption,
|
||||||
extensionPackageFinders,
|
extensionPackageFinders,
|
||||||
botConfig
|
botConfig
|
||||||
@ -138,9 +199,16 @@ internal class Launcher : AutoCloseable {
|
|||||||
@Synchronized
|
@Synchronized
|
||||||
override fun close() {
|
override fun close() {
|
||||||
botSessionMap.forEach {
|
botSessionMap.forEach {
|
||||||
log.info { "正在关闭机器人 `${it.key.botUsername}` ..." }
|
try {
|
||||||
it.value.stop()
|
if (!it.value.isRunning) {
|
||||||
log.info { "已关闭机器人 `${it.key.botUsername}`." }
|
return@forEach
|
||||||
|
}
|
||||||
|
log.info { "正在关闭机器人 `${it.key.botUsername}` ..." }
|
||||||
|
it.value.stop()
|
||||||
|
log.info { "已关闭机器人 `${it.key.botUsername}`." }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.error(e) { "机器人 `${it.key.botUsername}` 关闭时发生异常." }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,23 +1,190 @@
|
|||||||
package net.lamgc.scalabot
|
package net.lamgc.scalabot
|
||||||
|
|
||||||
import net.lamgc.scalabot.util.toHaxString
|
import com.google.common.io.Files
|
||||||
|
import mu.KotlinLogging
|
||||||
|
import net.lamgc.scalabot.util.toHexString
|
||||||
|
import org.mapdb.DB
|
||||||
|
import org.mapdb.DBException
|
||||||
import org.mapdb.DBMaker
|
import org.mapdb.DBMaker
|
||||||
import org.telegram.abilitybots.api.db.DBContext
|
import org.telegram.abilitybots.api.db.DBContext
|
||||||
import org.telegram.abilitybots.api.db.MapDBContext
|
import org.telegram.abilitybots.api.db.MapDBContext
|
||||||
|
import java.io.File
|
||||||
import java.nio.charset.StandardCharsets
|
import java.nio.charset.StandardCharsets
|
||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据库适配器.
|
||||||
|
*
|
||||||
|
* 应按照新到旧的顺序放置, 新的适配器应该在上面.
|
||||||
|
*/
|
||||||
|
private val adapters = arrayListOf<DbAdapter>(
|
||||||
|
BotAccountIdDbAdapter, // since [v0.2.0 ~ latest)
|
||||||
|
BotTokenDbAdapter // since [v0.0.1 ~ v0.2.0)
|
||||||
|
)
|
||||||
|
private const val FIELD_DB_VERSION = "::DB_VERSION"
|
||||||
|
|
||||||
internal object BotDBMaker {
|
internal object BotDBMaker {
|
||||||
fun getBotMaker(botAccount: BotAccount): DBContext {
|
private val logger = KotlinLogging.logger { }
|
||||||
val digest: MessageDigest = MessageDigest.getInstance("SHA-256")
|
|
||||||
val digestBytes = digest.digest(botAccount.token.toByteArray(StandardCharsets.UTF_8))
|
fun getBotDbInstance(botAccount: BotAccount): DBContext {
|
||||||
val dbPath = AppPaths.DATA_DB.path + "${digestBytes.toHaxString()}.db"
|
for (adapter in adapters) {
|
||||||
val db = DBMaker.fileDB(dbPath)
|
val botDb = try {
|
||||||
|
adapter.getBotDb(botAccount, create = false) ?: continue
|
||||||
|
} catch (e: Exception) {
|
||||||
|
logger.error(e) { "适配器 ${adapter::class.java} 打开数据库时发生异常." }
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!adapter.dbVersionMatches(botDb)) {
|
||||||
|
logger.warn {
|
||||||
|
"数据库版本号与适配器不符. " +
|
||||||
|
"(Adapter: ${adapter::class.java};(${adapter.dbVersion})," +
|
||||||
|
" DatabaseVer: ${adapter.getDbVersion(botDb)})"
|
||||||
|
}
|
||||||
|
botDb.close()
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
if (adapter != adapters[0]) {
|
||||||
|
logger.debug {
|
||||||
|
"数据库适配器不是最新的, 正在升级数据库... " +
|
||||||
|
"(Old: ${adapter::class.java}; New: ${adapters[0]::class.java})"
|
||||||
|
}
|
||||||
|
val db = try {
|
||||||
|
botDb.close()
|
||||||
|
val newDb = adapters[0].migrateDb(botAccount, adapter)
|
||||||
|
logger.debug { "数据库版本升级完成." }
|
||||||
|
newDb
|
||||||
|
} catch (e: Exception) {
|
||||||
|
logger.warn(e) { "Bot 数据库版本升级失败, 将继续使用旧版数据库." }
|
||||||
|
adapter.getBotDb(botAccount, create = false) ?: continue
|
||||||
|
}
|
||||||
|
return MapDBContext(db)
|
||||||
|
}
|
||||||
|
return MapDBContext(botDb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug { "没有适配器成功打开数据库, 使用最新的适配器创建数据库. (Adapter: ${adapters[0]::class.java})" }
|
||||||
|
val newDb = adapters[0].getBotDb(botAccount, create = true)
|
||||||
|
?: throw IllegalStateException("No adapter is available to get the database.")
|
||||||
|
adapters[0].setDbVersion(newDb, adapters[0].dbVersion)
|
||||||
|
return MapDBContext(newDb)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据库适配器.
|
||||||
|
*
|
||||||
|
* 用于解决数据库格式更新带来的问题, 通过迁移机制, 将数据库从旧版本迁移到新版本, 或者只通过旧版本适配器访问而不迁移.
|
||||||
|
* @param dbVersion 数据库格式版本. 格式为: `{格式标识}_{最后使用的版本号}`, 如果为最新版适配器, 则不需要填写最后使用的版本号.
|
||||||
|
*/
|
||||||
|
private abstract class DbAdapter(val dbVersion: String) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 Bot 专有的 [DBContext].
|
||||||
|
* @param botAccount Bot 账号信息.
|
||||||
|
*/
|
||||||
|
abstract fun getBotDb(botAccount: BotAccount, create: Boolean = false): DB?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 Bot 账号信息获取数据库文件.
|
||||||
|
*/
|
||||||
|
abstract fun getBotDbFile(botAccount: BotAccount): File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将旧版数据库迁移到当前版本.
|
||||||
|
*
|
||||||
|
* 实现时请注意不要直接修改原数据库, 以防升级过程出错导致无法回退到旧版本.
|
||||||
|
*/
|
||||||
|
abstract fun migrateDb(botAccount: BotAccount, oldDbAdapter: DbAdapter): DB
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据库版本是否匹配.
|
||||||
|
*/
|
||||||
|
open fun dbVersionMatches(db: DB): Boolean {
|
||||||
|
return getDbVersion(db) == dbVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getDbVersion(db: DB): String? {
|
||||||
|
if (!db.exists(FIELD_DB_VERSION)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val dbVersionField = try {
|
||||||
|
db.atomicString(FIELD_DB_VERSION).open()
|
||||||
|
} catch (e: DBException.WrongConfiguration) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return dbVersionField.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDbVersion(db: DB, version: String) {
|
||||||
|
db.atomicString(FIELD_DB_VERSION).createOrOpen().set(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 抽象文件数据库适配器.
|
||||||
|
*
|
||||||
|
* 只有文件有变化的适配器.
|
||||||
|
*/
|
||||||
|
private abstract class FileDbAdapter(
|
||||||
|
dbVersion: String,
|
||||||
|
private val fileProvider: (BotAccount) -> File
|
||||||
|
) : DbAdapter(dbVersion) {
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
constructor(dbVersion: String) : this(dbVersion,
|
||||||
|
{ throw NotImplementedError("When using this constructor, the \"getBotDbFile\" method must be implemented") })
|
||||||
|
|
||||||
|
override fun getBotDb(botAccount: BotAccount, create: Boolean): DB? {
|
||||||
|
val dbFile = getBotDbFile(botAccount)
|
||||||
|
if (!dbFile.exists() && !create) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return DBMaker.fileDB(dbFile)
|
||||||
.closeOnJvmShutdownWeakReference()
|
.closeOnJvmShutdownWeakReference()
|
||||||
.checksumStoreEnable()
|
.checksumStoreEnable()
|
||||||
.fileChannelEnable()
|
.fileChannelEnable()
|
||||||
.make()
|
.make()
|
||||||
return MapDBContext(db)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
override fun getBotDbFile(botAccount: BotAccount): File = fileProvider(botAccount)
|
||||||
|
|
||||||
|
override fun migrateDb(botAccount: BotAccount, oldDbAdapter: DbAdapter): DB {
|
||||||
|
val oldFile = oldDbAdapter.getBotDbFile(botAccount)
|
||||||
|
val newFile = getBotDbFile(botAccount)
|
||||||
|
try {
|
||||||
|
@Suppress("UnstableApiUsage")
|
||||||
|
Files.copy(oldFile, newFile)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (newFile.exists()) {
|
||||||
|
// 删除新文件以防止异常退出后直接读取新文件.
|
||||||
|
newFile.delete()
|
||||||
|
}
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
oldFile.delete()
|
||||||
|
return getBotDb(botAccount)!!.apply {
|
||||||
|
setDbVersion(this, this@FileDbAdapter.dbVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用 Bot Token 中的 Account Id 命名数据库文件名.
|
||||||
|
*/
|
||||||
|
private object BotAccountIdDbAdapter : FileDbAdapter("BotAccountId", { botAccount ->
|
||||||
|
File(AppPaths.DATA_DB.file, "${botAccount.id}.db")
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用 Bot Token, 经过 Sha256 加密后得到文件名.
|
||||||
|
*
|
||||||
|
* **已弃用**: 由于 Token 可以重新生成, 当 Token 改变后数据库文件名也会改变, 故弃用该方法.
|
||||||
|
*/
|
||||||
|
private object BotTokenDbAdapter : FileDbAdapter("BotToken_v0.1.0", { botAccount ->
|
||||||
|
val digest: MessageDigest = MessageDigest.getInstance("SHA-256")
|
||||||
|
val digestBytes = digest.digest(botAccount.token.toByteArray(StandardCharsets.UTF_8))
|
||||||
|
File(AppPaths.DATA_DB.file, "${digestBytes.toHexString()}.db")
|
||||||
|
})
|
@ -90,6 +90,10 @@ internal class ExtensionLoader(
|
|||||||
try {
|
try {
|
||||||
val extension =
|
val extension =
|
||||||
factory.createExtensionInstance(bot, getExtensionDataFolder(extensionArtifact))
|
factory.createExtensionInstance(bot, getExtensionDataFolder(extensionArtifact))
|
||||||
|
if (extension == null) {
|
||||||
|
log.debug { "Factory ${factory::class.java} 创建插件时返回了 null, 已跳过. (BotName: ${bot.botUsername})" }
|
||||||
|
continue
|
||||||
|
}
|
||||||
factories.add(LoadedExtensionEntry(extensionArtifact, factory::class.java, extension))
|
factories.add(LoadedExtensionEntry(extensionArtifact, factory::class.java, extension))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
log.error(e) { "创建扩展时发生异常. (ExtArtifact: `$extensionArtifact`, Factory: ${factory::class.java.name})" }
|
log.error(e) { "创建扩展时发生异常. (ExtArtifact: `$extensionArtifact`, Factory: ${factory::class.java.name})" }
|
||||||
@ -128,7 +132,7 @@ internal class ExtensionLoader(
|
|||||||
result[finder] = artifacts
|
result[finder] = artifacts
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
log.error { "搜索器 ${finder::class.java.name} 在搜索扩展 `$extensionArtifact` 时发生错误:" }
|
log.error(e) { "搜索器 ${finder::class.java.name} 在搜索扩展 `$extensionArtifact` 时发生错误." }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
@ -257,9 +257,21 @@ internal class MavenRepositoryExtensionFinder(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<FoundExtensionPackage> {
|
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<FoundExtensionPackage> {
|
||||||
|
log.debug {
|
||||||
|
StringBuilder().apply {
|
||||||
|
append("构件 $extensionArtifact 将在以下仓库拉取: \n")
|
||||||
|
remoteRepositories.forEach {
|
||||||
|
append("\t- ${it}\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
val extensionArtifactResult = repositorySystem.resolveArtifact(
|
val extensionArtifactResult = repositorySystem.resolveArtifact(
|
||||||
repoSystemSession,
|
repoSystemSession,
|
||||||
ArtifactRequest(extensionArtifact, remoteRepositories, null)
|
ArtifactRequest(
|
||||||
|
extensionArtifact,
|
||||||
|
repositorySystem.newResolutionRepositories(repoSystemSession, remoteRepositories),
|
||||||
|
null
|
||||||
|
)
|
||||||
)
|
)
|
||||||
val extResolvedArtifact = extensionArtifactResult.artifact
|
val extResolvedArtifact = extensionArtifactResult.artifact
|
||||||
if (!extensionArtifactResult.isResolved) {
|
if (!extensionArtifactResult.isResolved) {
|
||||||
|
@ -30,6 +30,7 @@ internal class ScalaBot(
|
|||||||
extensionFinders: Set<ExtensionPackageFinder>,
|
extensionFinders: Set<ExtensionPackageFinder>,
|
||||||
botConfig: BotConfig,
|
botConfig: BotConfig,
|
||||||
private val creatorId: Long = botConfig.account.creatorId,
|
private val creatorId: Long = botConfig.account.creatorId,
|
||||||
|
val accountId: Long = botConfig.account.id,
|
||||||
val extensions: Set<Artifact> = botConfig.extensions
|
val extensions: Set<Artifact> = botConfig.extensions
|
||||||
) :
|
) :
|
||||||
AbilityBot(
|
AbilityBot(
|
||||||
@ -102,6 +103,12 @@ internal class ScalaBot(
|
|||||||
}
|
}
|
||||||
BotCommand(it.name(), abilityInfo)
|
BotCommand(it.name(), abilityInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (botCommands.isEmpty()) {
|
||||||
|
log.info { "Bot 没有任何命令, 命令列表更新已跳过." }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
val setMyCommands = SetMyCommands()
|
val setMyCommands = SetMyCommands()
|
||||||
setMyCommands.commands = botCommands
|
setMyCommands.commands = botCommands
|
||||||
return execute(DeleteMyCommands()) && execute(setMyCommands)
|
return execute(DeleteMyCommands()) && execute(setMyCommands)
|
||||||
@ -113,7 +120,6 @@ internal class ScalaBot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onClosing() {
|
override fun onClosing() {
|
||||||
super.onClosing()
|
|
||||||
onlineBotGauge.dec()
|
onlineBotGauge.dec()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,7 +156,7 @@ internal class ScalaBot(
|
|||||||
private val updateProcessTime = Summary.build()
|
private val updateProcessTime = Summary.build()
|
||||||
.name("update_process_duration_seconds")
|
.name("update_process_duration_seconds")
|
||||||
.help(
|
.help(
|
||||||
"Time to process update. (This indicator includes the pre-processing of update by TelegrammBots, " +
|
"Time to process update. (This indicator includes the pre-processing of update by TelegramBots, " +
|
||||||
"so it may be different from the actual execution time of ability. " +
|
"so it may be different from the actual execution time of ability. " +
|
||||||
"It is not recommended to use it as the accurate execution time of ability)"
|
"It is not recommended to use it as the accurate execution time of ability)"
|
||||||
)
|
)
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package net.lamgc.scalabot.util
|
package net.lamgc.scalabot.util
|
||||||
|
|
||||||
import com.google.gson.*
|
import com.google.gson.*
|
||||||
import mu.KotlinLogging
|
|
||||||
import net.lamgc.scalabot.MavenRepositoryConfig
|
import net.lamgc.scalabot.MavenRepositoryConfig
|
||||||
import org.eclipse.aether.artifact.Artifact
|
import org.eclipse.aether.artifact.Artifact
|
||||||
import org.eclipse.aether.artifact.DefaultArtifact
|
import org.eclipse.aether.artifact.DefaultArtifact
|
||||||
@ -20,6 +19,9 @@ internal object ProxyTypeSerializer : JsonDeserializer<DefaultBotOptions.ProxyTy
|
|||||||
typeOfT: Type?,
|
typeOfT: Type?,
|
||||||
context: JsonDeserializationContext?
|
context: JsonDeserializationContext?
|
||||||
): DefaultBotOptions.ProxyType {
|
): DefaultBotOptions.ProxyType {
|
||||||
|
if (json.isJsonNull) {
|
||||||
|
return DefaultBotOptions.ProxyType.NO_PROXY
|
||||||
|
}
|
||||||
if (!json.isJsonPrimitive) {
|
if (!json.isJsonPrimitive) {
|
||||||
throw JsonParseException("Wrong configuration value type.")
|
throw JsonParseException("Wrong configuration value type.")
|
||||||
}
|
}
|
||||||
@ -52,8 +54,8 @@ internal object ArtifactSerializer : JsonSerializer<Artifact>, JsonDeserializer<
|
|||||||
return JsonPrimitive(gavBuilder.append(':').append(src.version).toString())
|
return JsonPrimitive(gavBuilder.append(':').append(src.version).toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Artifact {
|
override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext?): Artifact {
|
||||||
if (!json!!.isJsonPrimitive) {
|
if (!json.isJsonPrimitive) {
|
||||||
throw JsonParseException("Wrong configuration value type.")
|
throw JsonParseException("Wrong configuration value type.")
|
||||||
}
|
}
|
||||||
return DefaultArtifact(json.asString.trim())
|
return DefaultArtifact(json.asString.trim())
|
||||||
@ -63,72 +65,29 @@ internal object ArtifactSerializer : JsonSerializer<Artifact>, JsonDeserializer<
|
|||||||
|
|
||||||
internal object AuthenticationSerializer : JsonDeserializer<Authentication> {
|
internal object AuthenticationSerializer : JsonDeserializer<Authentication> {
|
||||||
|
|
||||||
private val log = KotlinLogging.logger { }
|
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Authentication {
|
||||||
|
if (json !is JsonObject) {
|
||||||
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Authentication? {
|
throw JsonParseException("Unsupported JSON type.")
|
||||||
val builder = AuthenticationBuilder()
|
|
||||||
when (json) {
|
|
||||||
is JsonArray -> {
|
|
||||||
for (element in json) {
|
|
||||||
if (element is JsonArray) {
|
|
||||||
builder.addCustom(jsonArrayToAuthentication(element))
|
|
||||||
} else if (element is JsonObject) {
|
|
||||||
jsonToAuthentication(element, builder)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
is JsonObject -> {
|
|
||||||
jsonToAuthentication(json, builder)
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
throw JsonParseException("Unsupported JSON data type: ${json::class.java}")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
val username = SerializerUtils.checkJsonKey(json, "username")
|
||||||
|
val password = SerializerUtils.checkJsonKey(json, "password")
|
||||||
|
val builder = AuthenticationBuilder()
|
||||||
|
builder.addUsername(username)
|
||||||
|
builder.addPassword(password)
|
||||||
return builder.build()
|
return builder.build()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun jsonArrayToAuthentication(jsonArray: JsonArray): Authentication {
|
|
||||||
val builder = AuthenticationBuilder()
|
|
||||||
for (element in jsonArray) {
|
|
||||||
when (element) {
|
|
||||||
is JsonObject -> jsonToAuthentication(element, builder)
|
|
||||||
is JsonArray -> builder.addCustom(jsonArrayToAuthentication(element))
|
|
||||||
else -> log.warn { "不支持的 Json 类型: ${element::class.java}" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return builder.build()
|
|
||||||
}
|
|
||||||
|
|
||||||
private const val KEY_TYPE = "type"
|
|
||||||
|
|
||||||
private fun jsonToAuthentication(json: JsonObject, builder: AuthenticationBuilder) {
|
|
||||||
if (!json.has(KEY_TYPE)) {
|
|
||||||
log.warn { "缺少 type 字段, 无法判断 Maven 认证信息类型." }
|
|
||||||
return
|
|
||||||
} else if (!json.get(KEY_TYPE).isJsonPrimitive) {
|
|
||||||
log.warn { "type 字段类型错误(应为 Primitive 类型), 无法判断 Maven 认证信息类型.(实际类型: `${json::class.java}`)" }
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
when (json.get(KEY_TYPE).asString.trim().lowercase()) {
|
|
||||||
"string" -> {
|
|
||||||
builder.addString(checkJsonKey(json, "key"), checkJsonKey(json, "value"))
|
|
||||||
}
|
|
||||||
"secret" -> {
|
|
||||||
builder.addSecret(checkJsonKey(json, "key"), checkJsonKey(json, "value"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun checkJsonKey(json: JsonObject, key: String): String {
|
private object SerializerUtils {
|
||||||
if (!json.has(key)) {
|
fun checkJsonKey(json: JsonObject, key: String): String {
|
||||||
throw JsonParseException("Required field does not exist: $key")
|
if (!json.has(key)) {
|
||||||
} else if (!json.get(key).isJsonPrimitive) {
|
throw JsonParseException("Required field does not exist: $key")
|
||||||
throw JsonParseException("Wrong field `$key` type: ${json.get(key)::class.java}")
|
} else if (!json.get(key).isJsonPrimitive) {
|
||||||
|
throw JsonParseException("Wrong field `$key` type: ${json.get(key)::class.java}")
|
||||||
|
}
|
||||||
|
return json.get(key).asString
|
||||||
}
|
}
|
||||||
return json.get(key).asString
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object MavenRepositoryConfigSerializer
|
internal object MavenRepositoryConfigSerializer
|
||||||
@ -142,12 +101,15 @@ internal object MavenRepositoryConfigSerializer
|
|||||||
return when (json) {
|
return when (json) {
|
||||||
is JsonObject -> {
|
is JsonObject -> {
|
||||||
MavenRepositoryConfig(
|
MavenRepositoryConfig(
|
||||||
url = URL(checkJsonKey(json, "url")),
|
id = json.get("id")?.asString,
|
||||||
|
url = URL(SerializerUtils.checkJsonKey(json, "url")),
|
||||||
proxy = if (json.has("proxy") && json.get("proxy").isJsonObject)
|
proxy = if (json.has("proxy") && json.get("proxy").isJsonObject)
|
||||||
context.deserialize<Proxy>(
|
context.deserialize<Proxy>(
|
||||||
json.getAsJsonObject("proxy"), Proxy::class.java
|
json.getAsJsonObject("proxy"), Proxy::class.java
|
||||||
) else null,
|
) else null,
|
||||||
layout = json.get("layout").asString ?: "default",
|
layout = json.get("layout")?.asString ?: "default",
|
||||||
|
enableReleases = json.get("enableReleases")?.asBoolean ?: true,
|
||||||
|
enableSnapshots = json.get("enableSnapshots")?.asBoolean ?: true,
|
||||||
authentication = if (json.has("authentication") && json.get("authentication").isJsonObject)
|
authentication = if (json.has("authentication") && json.get("authentication").isJsonObject)
|
||||||
context.deserialize<Authentication>(
|
context.deserialize<Authentication>(
|
||||||
json.getAsJsonObject("authentication"), Authentication::class.java
|
json.getAsJsonObject("authentication"), Authentication::class.java
|
||||||
@ -155,7 +117,7 @@ internal object MavenRepositoryConfigSerializer
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
is JsonPrimitive -> {
|
is JsonPrimitive -> {
|
||||||
MavenRepositoryConfig(URL(json.asString))
|
MavenRepositoryConfig(url = URL(json.asString))
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
throw JsonParseException("Unsupported Maven warehouse configuration type.")
|
throw JsonParseException("Unsupported Maven warehouse configuration type.")
|
||||||
|
@ -7,9 +7,8 @@ import org.eclipse.aether.artifact.Artifact
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileFilter
|
import java.io.FileFilter
|
||||||
import java.io.FilenameFilter
|
import java.io.FilenameFilter
|
||||||
import java.net.URL
|
|
||||||
|
|
||||||
internal fun ByteArray.toHaxString(): String = ByteUtils.bytesToHexString(this)
|
internal fun ByteArray.toHexString(): String = joinToString("") { it.toString(16) }
|
||||||
|
|
||||||
internal fun Artifact.equalsArtifact(that: Artifact): Boolean =
|
internal fun Artifact.equalsArtifact(that: Artifact): Boolean =
|
||||||
this.groupId.equals(that.groupId) &&
|
this.groupId.equals(that.groupId) &&
|
||||||
@ -34,11 +33,7 @@ internal fun File.deepListFiles(
|
|||||||
this.listFiles(filenameFilter)
|
this.listFiles(filenameFilter)
|
||||||
} else {
|
} else {
|
||||||
this.listFiles()
|
this.listFiles()
|
||||||
}
|
} ?: return null
|
||||||
|
|
||||||
if (files == null) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
val result = if (addSelf) mutableSetOf(this) else mutableSetOf()
|
val result = if (addSelf) mutableSetOf(this) else mutableSetOf()
|
||||||
for (file in files) {
|
for (file in files) {
|
||||||
@ -48,10 +43,8 @@ internal fun File.deepListFiles(
|
|||||||
if (!onlyFile) {
|
if (!onlyFile) {
|
||||||
result.add(file)
|
result.add(file)
|
||||||
}
|
}
|
||||||
val subFiles = file.deepListFiles(false, onlyFile, fileFilter, filenameFilter)
|
val subFiles = file.deepListFiles(false, onlyFile, fileFilter, filenameFilter) ?: continue
|
||||||
if (subFiles != null) {
|
result.addAll(subFiles)
|
||||||
result.addAll(subFiles)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result.toTypedArray()
|
return result.toTypedArray()
|
||||||
@ -62,9 +55,14 @@ internal fun File.deepListFiles(
|
|||||||
* @return 获取 Finder 的优先级.
|
* @return 获取 Finder 的优先级.
|
||||||
* @throws NoSuchFieldException 如果 Finder 没有添加 [FinderRules] 注解时抛出该异常.
|
* @throws NoSuchFieldException 如果 Finder 没有添加 [FinderRules] 注解时抛出该异常.
|
||||||
*/
|
*/
|
||||||
internal fun ExtensionPackageFinder.getPriority() =
|
internal fun ExtensionPackageFinder.getPriority(): Int {
|
||||||
this::class.java.getDeclaredAnnotation(FinderRules::class.java)?.priority
|
val value = this::class.java.getDeclaredAnnotation(FinderRules::class.java)?.priority
|
||||||
?: throw NoSuchFieldException("Finder did not add `FinderRules` annotation")
|
?: throw NoSuchFieldException("Finder did not add `FinderRules` annotation")
|
||||||
|
if (value < 0) {
|
||||||
|
throw IllegalArgumentException("Priority cannot be lower than 0. (Class: ${this::class.java})")
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 为 [AutoCloseable] 对象注册 Jvm Shutdown 钩子.
|
* 为 [AutoCloseable] 对象注册 Jvm Shutdown 钩子.
|
||||||
@ -82,30 +80,19 @@ private object UtilsInternal {
|
|||||||
val autoCloseableSet = mutableSetOf<AutoCloseable>()
|
val autoCloseableSet = mutableSetOf<AutoCloseable>()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
Runtime.getRuntime().addShutdownHook(Thread({
|
Runtime.getRuntime().addShutdownHook(Thread(this::doCloseResources, "Shutdown-AutoCloseable"))
|
||||||
log.debug { "Closing registered hook resources..." }
|
}
|
||||||
autoCloseableSet.forEach {
|
|
||||||
try {
|
fun doCloseResources() {
|
||||||
it.close()
|
log.debug { "Closing registered hook resources..." }
|
||||||
} catch (e: Exception) {
|
autoCloseableSet.removeIf {
|
||||||
log.error(e) { "An exception occurred while closing the resource. (Resource: `$it`)" }
|
try {
|
||||||
}
|
it.close()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.error(e) { "An exception occurred while closing the resource. (Resource: `$it`)" }
|
||||||
}
|
}
|
||||||
log.debug { "All registered hook resources have been closed." }
|
true
|
||||||
}, "Shutdown-AutoCloseable"))
|
}
|
||||||
}
|
log.debug { "All registered hook resources have been closed." }
|
||||||
}
|
|
||||||
|
|
||||||
fun URL.resolveToFile(canonical: Boolean = true): File {
|
|
||||||
if ("file" != protocol) {
|
|
||||||
throw ClassCastException("Only the URL of the `file` protocol can be converted into a File object.")
|
|
||||||
}
|
|
||||||
|
|
||||||
val urlString = toString().substringAfter(':')
|
|
||||||
val file = File(urlString)
|
|
||||||
return if (canonical) {
|
|
||||||
file.canonicalFile
|
|
||||||
} else {
|
|
||||||
file
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,8 @@
|
|||||||
<logger name="org.eclipse.aether.internal.impl.DefaultTransporterProvider" level="INFO"/>
|
<logger name="org.eclipse.aether.internal.impl.DefaultTransporterProvider" level="INFO"/>
|
||||||
<logger name="org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider" level="INFO"/>
|
<logger name="org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider" level="INFO"/>
|
||||||
<logger name="org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManager" level="INFO"/>
|
<logger name="org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManager" level="INFO"/>
|
||||||
|
<logger name="org.telegram.telegrambots.facilities.proxysocketfactorys" level="INFO"/>
|
||||||
|
<logger name="org.eclipse.aether.internal.impl.DefaultUpdateCheckManager" level="INFO"/>
|
||||||
|
|
||||||
<root level="DEBUG">
|
<root level="DEBUG">
|
||||||
<appender-ref ref="FILE_OUT"/>
|
<appender-ref ref="FILE_OUT"/>
|
||||||
|
127
scalabot-app/src/test/kotlin/AppConfigTest.kt
Normal file
127
scalabot-app/src/test/kotlin/AppConfigTest.kt
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
package net.lamgc.scalabot
|
||||||
|
|
||||||
|
import com.github.stefanbirkner.systemlambda.SystemLambda
|
||||||
|
import com.google.gson.Gson
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.mockk
|
||||||
|
import io.mockk.verify
|
||||||
|
import org.junit.jupiter.api.io.TempDir
|
||||||
|
import java.io.File
|
||||||
|
import java.util.*
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
internal class BotAccountTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun deserializerTest() {
|
||||||
|
val accountId = abs(Random().nextInt()).toLong()
|
||||||
|
val creatorId = abs(Random().nextInt()).toLong()
|
||||||
|
val botAccount = Gson().fromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"name": "TestBot",
|
||||||
|
"token": "${accountId}:AAHErDroUTznQsOd_oZPJ6cQEj4Z5mGHO10",
|
||||||
|
"creatorId": $creatorId
|
||||||
|
}
|
||||||
|
""".trimIndent(), BotAccount::class.java
|
||||||
|
)
|
||||||
|
assertEquals("TestBot", botAccount.name)
|
||||||
|
assertEquals("${accountId}:AAHErDroUTznQsOd_oZPJ6cQEj4Z5mGHO10", botAccount.token)
|
||||||
|
assertEquals(accountId, botAccount.id, "Botaccount ID does not match expectations.")
|
||||||
|
assertEquals(creatorId, botAccount.creatorId)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class AppPathsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Data root path priority`() {
|
||||||
|
System.setProperty("bot.path.data", "fromSystemProperties")
|
||||||
|
|
||||||
|
assertEquals("fromSystemProperties", AppPaths.DATA_ROOT.file.path, "`DATA_ROOT`没有优先返回 Property 的值.")
|
||||||
|
System.getProperties().remove("bot.path.data")
|
||||||
|
|
||||||
|
val expectEnvValue = "fromEnvironmentVariable"
|
||||||
|
SystemLambda.withEnvironmentVariable("BOT_DATA_PATH", expectEnvValue).execute {
|
||||||
|
assertEquals(
|
||||||
|
expectEnvValue, AppPaths.DATA_ROOT.file.path,
|
||||||
|
"`DATA_ROOT`没有优先返回 env 的值."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
SystemLambda.withEnvironmentVariable("BOT_DATA_PATH", null).execute {
|
||||||
|
assertEquals(
|
||||||
|
System.getProperty("user.dir"), AppPaths.DATA_ROOT.file.path,
|
||||||
|
"`DATA_ROOT`没有返回 System.properties `user.dir` 的值."
|
||||||
|
)
|
||||||
|
val userDir = System.getProperty("user.dir")
|
||||||
|
System.getProperties().remove("user.dir")
|
||||||
|
assertEquals(".", AppPaths.DATA_ROOT.file.path, "`DATA_ROOT`没有返回替补值 `.`(当前目录).")
|
||||||
|
System.setProperty("user.dir", userDir)
|
||||||
|
assertNotNull(System.getProperty("user.dir"), "环境还原失败!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `default initializer`(@TempDir testDir: File) {
|
||||||
|
val defaultInitializerMethod = Class.forName("net.lamgc.scalabot.AppConfigsKt")
|
||||||
|
.getDeclaredMethod("defaultInitializer", AppPaths::class.java)
|
||||||
|
.apply { isAccessible = true }
|
||||||
|
|
||||||
|
val dirPath = "${testDir.canonicalPath}/directory/"
|
||||||
|
val dirFile = File(dirPath)
|
||||||
|
mockk<AppPaths> {
|
||||||
|
every { file }.returns(File(dirPath))
|
||||||
|
every { path }.returns(dirPath)
|
||||||
|
every { initial() }.answers {
|
||||||
|
defaultInitializerMethod.invoke(null, this@mockk)
|
||||||
|
}
|
||||||
|
}.initial()
|
||||||
|
assertTrue(dirFile.exists() && dirFile.isDirectory, "默认初始器未正常初始化【文件夹】.")
|
||||||
|
|
||||||
|
File(testDir, "test.txt").apply {
|
||||||
|
mockk<AppPaths> {
|
||||||
|
every { file }.returns(this@apply)
|
||||||
|
every { path }.returns(this@apply.canonicalPath)
|
||||||
|
every { initial() }.answers {
|
||||||
|
defaultInitializerMethod.invoke(null, this@mockk)
|
||||||
|
}
|
||||||
|
}.initial()
|
||||||
|
assertTrue(this@apply.exists() && this@apply.isFile, "默认初始器未正常初始化【文件】.")
|
||||||
|
}
|
||||||
|
|
||||||
|
val alreadyExistsFile = File("${testDir.canonicalPath}/alreadyExists.txt").apply {
|
||||||
|
if (!exists()) {
|
||||||
|
createNewFile()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(alreadyExistsFile.exists(), "文件状态与预期不符.")
|
||||||
|
mockk<File> {
|
||||||
|
every { exists() }.returns(true)
|
||||||
|
every { canonicalPath }.answers { alreadyExistsFile.canonicalPath }
|
||||||
|
every { createNewFile() }.answers { alreadyExistsFile.createNewFile() }
|
||||||
|
every { mkdirs() }.answers { alreadyExistsFile.mkdirs() }
|
||||||
|
every { mkdir() }.answers { alreadyExistsFile.mkdir() }
|
||||||
|
}.apply {
|
||||||
|
mockk<AppPaths> {
|
||||||
|
every { file }.returns(this@apply)
|
||||||
|
every { path }.returns(this@apply.canonicalPath)
|
||||||
|
every { initial() }.answers {
|
||||||
|
defaultInitializerMethod.invoke(null, this@mockk)
|
||||||
|
}
|
||||||
|
}.initial()
|
||||||
|
verify(exactly = 0) { createNewFile() }
|
||||||
|
verify(exactly = 0) { mkdir() }
|
||||||
|
verify(exactly = 0) { mkdirs() }
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultInitializerMethod.isAccessible = false
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -18,13 +18,21 @@ internal class ArtifactSerializerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun serialize() {
|
fun `Basic format serialization`() {
|
||||||
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
|
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
|
||||||
val expectArtifact = DefaultArtifact(gav)
|
val expectArtifact = DefaultArtifact(gav)
|
||||||
val actualArtifact = DefaultArtifact(ArtifactSerializer.serialize(expectArtifact, null, null).asString)
|
val actualArtifact = DefaultArtifact(ArtifactSerializer.serialize(expectArtifact, null, null).asString)
|
||||||
assertEquals(expectArtifact, actualArtifact)
|
assertEquals(expectArtifact, actualArtifact)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Full format serialization`() {
|
||||||
|
val gav = "org.example.software:test:war:javadoc:1.0.0-SNAPSHOT"
|
||||||
|
val expectArtifact = DefaultArtifact(gav)
|
||||||
|
val actualArtifact = DefaultArtifact(ArtifactSerializer.serialize(expectArtifact, null, null).asString)
|
||||||
|
assertEquals(expectArtifact, actualArtifact)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun deserialize() {
|
fun deserialize() {
|
||||||
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
|
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
|
||||||
|
325
scalabot-app/src/test/kotlin/util/SerializersKtTest.kt
Normal file
325
scalabot-app/src/test/kotlin/util/SerializersKtTest.kt
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import com.google.gson.*
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.mockk
|
||||||
|
import io.mockk.verify
|
||||||
|
import net.lamgc.scalabot.MavenRepositoryConfig
|
||||||
|
import net.lamgc.scalabot.util.AuthenticationSerializer
|
||||||
|
import net.lamgc.scalabot.util.MavenRepositoryConfigSerializer
|
||||||
|
import net.lamgc.scalabot.util.ProxyTypeSerializer
|
||||||
|
import org.eclipse.aether.repository.Authentication
|
||||||
|
import org.eclipse.aether.repository.AuthenticationContext
|
||||||
|
import org.eclipse.aether.repository.Proxy
|
||||||
|
import org.intellij.lang.annotations.Language
|
||||||
|
import org.junit.jupiter.api.Assertions.assertThrows
|
||||||
|
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||||
|
import java.lang.reflect.InvocationTargetException
|
||||||
|
import java.lang.reflect.Method
|
||||||
|
import java.lang.reflect.Type
|
||||||
|
import java.net.URL
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
|
internal class SerializersKtTest {
|
||||||
|
|
||||||
|
private val instance: Any
|
||||||
|
private val method: Method
|
||||||
|
|
||||||
|
init {
|
||||||
|
val clazz = Class.forName("net.lamgc.scalabot.util.SerializerUtils")
|
||||||
|
method = clazz.getDeclaredMethod("checkJsonKey", JsonObject::class.java, String::class.java)
|
||||||
|
method.isAccessible = true
|
||||||
|
instance = clazz.getDeclaredField("INSTANCE").apply {
|
||||||
|
isAccessible = true
|
||||||
|
}.get(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun invoke(json: JsonObject, key: String): String {
|
||||||
|
try {
|
||||||
|
return method.invoke(instance, json, key) as String
|
||||||
|
} catch (e: InvocationTargetException) {
|
||||||
|
throw e.targetException
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Json key checker test`() {
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
invoke(JsonObject(), "NOT_EXIST_KEY")
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
invoke(JsonObject().apply { add("NULL_KEY", JsonNull.INSTANCE) }, "NULL_KEY")
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
invoke(JsonObject().apply { add("ARRAY_KEY", JsonArray()) }, "ARRAY_KEY")
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
invoke(JsonObject().apply { add("OBJECT_KEY", JsonObject()) }, "OBJECT_KEY")
|
||||||
|
}
|
||||||
|
|
||||||
|
val expectKey = "TEST"
|
||||||
|
val expectString = "testString"
|
||||||
|
val json = JsonObject().apply { addProperty(expectKey, expectString) }
|
||||||
|
|
||||||
|
assertEquals(expectString, invoke(json, expectKey))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class ProxyTypeSerializerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `serialize test`() {
|
||||||
|
for (type in DefaultBotOptions.ProxyType.values()) {
|
||||||
|
assertEquals(
|
||||||
|
JsonPrimitive(type.name), ProxyTypeSerializer.serialize(type, null, null),
|
||||||
|
"ProxyType 序列化结果与预期不符."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deserialize test`() {
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
ProxyTypeSerializer.deserialize(JsonObject(), null, null)
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
ProxyTypeSerializer.deserialize(JsonArray(), null, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
ProxyTypeSerializer.deserialize(JsonPrimitive("NOT_IN_ENUM_VALUE"), null, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
DefaultBotOptions.ProxyType.NO_PROXY,
|
||||||
|
ProxyTypeSerializer.deserialize(JsonNull.INSTANCE, null, null)
|
||||||
|
)
|
||||||
|
|
||||||
|
for (type in DefaultBotOptions.ProxyType.values()) {
|
||||||
|
assertEquals(
|
||||||
|
type, ProxyTypeSerializer.deserialize(JsonPrimitive(type.name), null, null),
|
||||||
|
"ProxyType 反序列化结果与预期不符."
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
type, ProxyTypeSerializer.deserialize(JsonPrimitive(" ${type.name} "), null, null),
|
||||||
|
"ProxyType 反序列化时未对 Json 字符串进行修剪(trim)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class MavenRepositoryConfigSerializerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `unsupported json type deserialize test`() {
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
JsonArray(),
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
JsonNull.INSTANCE,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `json primitive deserialize test`() {
|
||||||
|
val expectRepoUrl = "https://repo.example.org/maven"
|
||||||
|
val config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
JsonPrimitive(expectRepoUrl),
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNull(config.id)
|
||||||
|
assertEquals(URL(expectRepoUrl), config.url)
|
||||||
|
assertNull(config.proxy, "Proxy 默认值不为 null.")
|
||||||
|
assertEquals("default", config.layout)
|
||||||
|
assertTrue(config.enableReleases)
|
||||||
|
assertTrue(config.enableSnapshots)
|
||||||
|
assertNull(config.authentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `json object default deserialize test`() {
|
||||||
|
val expectRepoUrl = "https://repo.example.org/maven"
|
||||||
|
val jsonObject = JsonObject()
|
||||||
|
jsonObject.addProperty("url", expectRepoUrl)
|
||||||
|
val config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
jsonObject,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNull(config.id)
|
||||||
|
assertEquals(URL(expectRepoUrl), config.url)
|
||||||
|
assertNull(config.proxy, "Proxy 默认值不为 null.")
|
||||||
|
assertEquals("default", config.layout)
|
||||||
|
assertTrue(config.enableReleases)
|
||||||
|
assertTrue(config.enableSnapshots)
|
||||||
|
assertNull(config.authentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `json object deserialize test`() {
|
||||||
|
@Language("JSON5")
|
||||||
|
val looksGoodJsonString = """
|
||||||
|
{
|
||||||
|
"id": "test-repository",
|
||||||
|
"url": "https://repo.example.org/maven",
|
||||||
|
"proxy": {
|
||||||
|
"type": "http",
|
||||||
|
"host": "127.0.1.1",
|
||||||
|
"port": 10800
|
||||||
|
},
|
||||||
|
"layout": "default",
|
||||||
|
"enableReleases": false,
|
||||||
|
"enableSnapshots": true
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val jsonObject = Gson().fromJson(looksGoodJsonString, JsonObject::class.java)
|
||||||
|
var config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
jsonObject,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(jsonObject["id"].asString, config.id)
|
||||||
|
assertEquals(URL(jsonObject["url"].asString), config.url)
|
||||||
|
assertEquals(Proxy("http", "127.0.1.1", 10800), config.proxy)
|
||||||
|
assertEquals(jsonObject["layout"].asString, config.layout)
|
||||||
|
assertEquals(jsonObject["enableReleases"].asBoolean, config.enableReleases)
|
||||||
|
assertEquals(jsonObject["enableSnapshots"].asBoolean, config.enableSnapshots)
|
||||||
|
|
||||||
|
// ------------------------------------
|
||||||
|
|
||||||
|
jsonObject.add("proxy", JsonNull.INSTANCE)
|
||||||
|
jsonObject.remove("layout")
|
||||||
|
|
||||||
|
config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
jsonObject,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(jsonObject["id"].asString, config.id)
|
||||||
|
assertEquals(URL(jsonObject["url"].asString), config.url)
|
||||||
|
assertNull(config.proxy)
|
||||||
|
assertEquals("default", config.layout)
|
||||||
|
assertEquals(jsonObject["enableReleases"].asBoolean, config.enableReleases)
|
||||||
|
assertEquals(jsonObject["enableSnapshots"].asBoolean, config.enableSnapshots)
|
||||||
|
|
||||||
|
// ------------------------------------
|
||||||
|
|
||||||
|
jsonObject.add("authentication", JsonArray())
|
||||||
|
jsonObject.add("layout", mockk<JsonPrimitive> {
|
||||||
|
every { asString }.returns(null)
|
||||||
|
})
|
||||||
|
|
||||||
|
config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
jsonObject,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(jsonObject["id"].asString, config.id)
|
||||||
|
assertEquals(URL(jsonObject["url"].asString), config.url)
|
||||||
|
assertNull(config.proxy)
|
||||||
|
assertEquals("default", config.layout)
|
||||||
|
assertEquals(jsonObject["enableReleases"].asBoolean, config.enableReleases)
|
||||||
|
assertEquals(jsonObject["enableSnapshots"].asBoolean, config.enableSnapshots)
|
||||||
|
assertNull(config.authentication)
|
||||||
|
|
||||||
|
// ------------------------------------
|
||||||
|
|
||||||
|
jsonObject.add("authentication", JsonObject().apply {
|
||||||
|
addProperty("username", "testUsername")
|
||||||
|
addProperty("password", "testPassword")
|
||||||
|
})
|
||||||
|
|
||||||
|
config = MavenRepositoryConfigSerializer.deserialize(
|
||||||
|
jsonObject,
|
||||||
|
MavenRepositoryConfig::class.java,
|
||||||
|
TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(jsonObject["id"].asString, config.id)
|
||||||
|
assertEquals(URL(jsonObject["url"].asString), config.url)
|
||||||
|
assertNull(config.proxy)
|
||||||
|
assertEquals("default", config.layout)
|
||||||
|
assertEquals(jsonObject["enableReleases"].asBoolean, config.enableReleases)
|
||||||
|
assertEquals(jsonObject["enableSnapshots"].asBoolean, config.enableSnapshots)
|
||||||
|
assertNotNull(config.authentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private object TestJsonDeserializationContext : JsonDeserializationContext {
|
||||||
|
|
||||||
|
private val gson = GsonBuilder()
|
||||||
|
.registerTypeAdapter(Authentication::class.java, AuthenticationSerializer)
|
||||||
|
.create()
|
||||||
|
|
||||||
|
override fun <T : Any?> deserialize(json: JsonElement, typeOfT: Type): T {
|
||||||
|
return gson.fromJson(json, typeOfT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class AuthenticationSerializerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deserialize test`() {
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
AuthenticationSerializer.deserialize(
|
||||||
|
JsonNull.INSTANCE,
|
||||||
|
Authentication::class.java, TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
AuthenticationSerializer.deserialize(
|
||||||
|
JsonArray(),
|
||||||
|
Authentication::class.java, TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertThrows(JsonParseException::class.java) {
|
||||||
|
AuthenticationSerializer.deserialize(
|
||||||
|
JsonPrimitive("A STRING"),
|
||||||
|
Authentication::class.java, TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val expectJsonObject = JsonObject().apply {
|
||||||
|
addProperty("username", "testUsername")
|
||||||
|
addProperty("password", "testPassword")
|
||||||
|
}
|
||||||
|
|
||||||
|
val mockContext = mockk<AuthenticationContext> {
|
||||||
|
every { put(any(), any()) }.answers { }
|
||||||
|
}
|
||||||
|
|
||||||
|
val result = AuthenticationSerializer.deserialize(
|
||||||
|
expectJsonObject,
|
||||||
|
Authentication::class.java, TestJsonDeserializationContext
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(result)
|
||||||
|
result.fill(mockContext, "username", null)
|
||||||
|
result.fill(mockContext, "password", null)
|
||||||
|
|
||||||
|
verify {
|
||||||
|
mockContext.put("username", "testUsername")
|
||||||
|
mockContext.put("password", "testPassword".toCharArray())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
40
scalabot-app/src/test/kotlin/util/StdOutFilterTest.kt
Normal file
40
scalabot-app/src/test/kotlin/util/StdOutFilterTest.kt
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package net.lamgc.scalabot.util
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Level
|
||||||
|
import ch.qos.logback.classic.spi.LoggingEvent
|
||||||
|
import ch.qos.logback.core.spi.FilterReply
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.mockk
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class StdOutFilterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun filterTest() {
|
||||||
|
val filter = StdOutFilter()
|
||||||
|
|
||||||
|
for (level in listOf(
|
||||||
|
Level.ALL,
|
||||||
|
Level.TRACE,
|
||||||
|
Level.DEBUG,
|
||||||
|
Level.INFO
|
||||||
|
)) {
|
||||||
|
val loggingEvent = mockk<LoggingEvent> {
|
||||||
|
every { this@mockk.level }.returns(level)
|
||||||
|
}
|
||||||
|
assertEquals(FilterReply.ACCEPT, filter.decide(loggingEvent))
|
||||||
|
}
|
||||||
|
|
||||||
|
for (level in listOf(
|
||||||
|
Level.WARN,
|
||||||
|
Level.ERROR
|
||||||
|
)) {
|
||||||
|
val loggingEvent = mockk<LoggingEvent> {
|
||||||
|
every { this@mockk.level }.returns(level)
|
||||||
|
}
|
||||||
|
assertEquals(FilterReply.DENY, filter.decide(loggingEvent))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,9 +1,21 @@
|
|||||||
package net.lamgc.scalabot.util
|
package net.lamgc.scalabot.util
|
||||||
|
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.justRun
|
||||||
|
import io.mockk.mockk
|
||||||
|
import io.mockk.verify
|
||||||
|
import net.lamgc.scalabot.ExtensionPackageFinder
|
||||||
|
import net.lamgc.scalabot.FinderPriority
|
||||||
|
import net.lamgc.scalabot.FinderRules
|
||||||
|
import net.lamgc.scalabot.FoundExtensionPackage
|
||||||
|
import org.eclipse.aether.artifact.Artifact
|
||||||
import org.eclipse.aether.artifact.DefaultArtifact
|
import org.eclipse.aether.artifact.DefaultArtifact
|
||||||
import org.junit.jupiter.api.Assertions.assertFalse
|
import org.junit.jupiter.api.assertDoesNotThrow
|
||||||
import org.junit.jupiter.api.Assertions.assertTrue
|
import org.junit.jupiter.api.assertThrows
|
||||||
import org.junit.jupiter.api.Test
|
import java.io.File
|
||||||
|
import java.lang.reflect.InvocationTargetException
|
||||||
|
import java.nio.charset.StandardCharsets
|
||||||
|
import kotlin.test.*
|
||||||
|
|
||||||
internal class UtilsKtTest {
|
internal class UtilsKtTest {
|
||||||
|
|
||||||
@ -16,4 +28,92 @@ internal class UtilsKtTest {
|
|||||||
.equalsArtifact(DefaultArtifact("com.example:demo-2:1.0.0-SNAPSHOT"))
|
.equalsArtifact(DefaultArtifact("com.example:demo-2:1.0.0-SNAPSHOT"))
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `bytes to hex`() {
|
||||||
|
assertEquals("48656c6c6f20576f726c64", "Hello World".toByteArray(StandardCharsets.UTF_8).toHexString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `ExtensionPackageFinder - getPriority`() {
|
||||||
|
open class BaseTestFinder : ExtensionPackageFinder {
|
||||||
|
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<FoundExtensionPackage> {
|
||||||
|
throw IllegalStateException("Calling this class is not allowed.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@FinderRules(FinderPriority.ALTERNATE)
|
||||||
|
class StandardTestFinder : BaseTestFinder()
|
||||||
|
assertEquals(
|
||||||
|
FinderPriority.ALTERNATE, StandardTestFinder().getPriority(),
|
||||||
|
"获取到的优先值与预期不符"
|
||||||
|
)
|
||||||
|
|
||||||
|
@FinderRules(-1)
|
||||||
|
class OutOfRangePriorityFinder : BaseTestFinder()
|
||||||
|
assertThrows<IllegalArgumentException>("getPriority 方法没有对超出范围的优先值抛出异常.") {
|
||||||
|
OutOfRangePriorityFinder().getPriority()
|
||||||
|
}
|
||||||
|
|
||||||
|
class NoAnnotationFinder : BaseTestFinder()
|
||||||
|
assertThrows<NoSuchFieldException> {
|
||||||
|
NoAnnotationFinder().getPriority()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `AutoCloseable shutdown hook`() {
|
||||||
|
val utilsInternalClass = Class.forName("net.lamgc.scalabot.util.UtilsInternal")
|
||||||
|
val utilsInternalObject = utilsInternalClass.getDeclaredField("INSTANCE").get(null)
|
||||||
|
?: fail("无法获取 UtilsInternal 对象.")
|
||||||
|
val doCloseResourcesMethod = utilsInternalClass.getDeclaredMethod("doCloseResources")
|
||||||
|
.apply {
|
||||||
|
isAccessible = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 正常的运行过程.
|
||||||
|
val mockResource = mockk<AutoCloseable> {
|
||||||
|
justRun { close() }
|
||||||
|
}.registerShutdownHook()
|
||||||
|
doCloseResourcesMethod.invoke(utilsInternalObject)
|
||||||
|
verify { mockResource.close() }
|
||||||
|
|
||||||
|
// 异常捕获检查.
|
||||||
|
val exceptionMockResource = mockk<AutoCloseable> {
|
||||||
|
every { close() } throws RuntimeException("Expected exception.")
|
||||||
|
}.registerShutdownHook()
|
||||||
|
assertDoesNotThrow("在关闭资源时出现未捕获异常.") {
|
||||||
|
doCloseResourcesMethod.invoke(utilsInternalObject)
|
||||||
|
}
|
||||||
|
verify { exceptionMockResource.close() }
|
||||||
|
|
||||||
|
// 错误抛出检查.
|
||||||
|
val errorMockResource = mockk<AutoCloseable> {
|
||||||
|
every { close() } throws Error("Expected error.")
|
||||||
|
}.registerShutdownHook()
|
||||||
|
assertThrows<Error>("关闭资源时捕获了不该捕获的 Error.") {
|
||||||
|
try {
|
||||||
|
doCloseResourcesMethod.invoke(utilsInternalObject)
|
||||||
|
} catch (e: InvocationTargetException) {
|
||||||
|
throw e.targetException
|
||||||
|
}
|
||||||
|
}
|
||||||
|
verify { errorMockResource.close() }
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
val resourceSet = utilsInternalClass.getDeclaredMethod("getAutoCloseableSet").invoke(utilsInternalObject)
|
||||||
|
as MutableSet<AutoCloseable>
|
||||||
|
resourceSet.clear()
|
||||||
|
|
||||||
|
val closeRef = mockk<AutoCloseable> {
|
||||||
|
justRun { close() }
|
||||||
|
}
|
||||||
|
resourceSet.add(closeRef)
|
||||||
|
assertTrue(resourceSet.contains(closeRef), "测试用资源虚引用添加失败.")
|
||||||
|
doCloseResourcesMethod.invoke(utilsInternalObject)
|
||||||
|
assertFalse(resourceSet.contains(closeRef), "资源虚引用未从列表中删除.")
|
||||||
|
|
||||||
|
resourceSet.clear()
|
||||||
|
}
|
||||||
}
|
}
|
@ -37,11 +37,16 @@ public class SayHelloExtension implements AbilityExtension {
|
|||||||
*/
|
*/
|
||||||
public Ability test() {
|
public Ability test() {
|
||||||
ReplyFlow botHello = ReplyFlow.builder(bot.db())
|
ReplyFlow botHello = ReplyFlow.builder(bot.db())
|
||||||
|
.enableStats("say_hello")
|
||||||
.action((bot, upd) -> bot.silent().send("What is u name?", upd.getMessage().getChatId()))
|
.action((bot, upd) -> bot.silent().send("What is u name?", upd.getMessage().getChatId()))
|
||||||
.onlyIf(update -> "hello".equalsIgnoreCase(update.getMessage().getText()))
|
.onlyIf(update -> update.hasMessage()
|
||||||
|
&& update.getMessage().hasText()
|
||||||
|
&& "hello".equalsIgnoreCase(update.getMessage().getText()))
|
||||||
.next(Reply.of((bot, upd) -> bot.silent()
|
.next(Reply.of((bot, upd) -> bot.silent()
|
||||||
.send("OK! You name is " + upd.getMessage().getText().substring("my name is ".length()), upd.getMessage().getChatId()),
|
.send("OK! You name is " + upd.getMessage().getText().substring("my name is ".length()), upd.getMessage().getChatId()),
|
||||||
upd -> upd.getMessage().getText().startsWith("my name is ")))
|
upd -> upd.hasMessage()
|
||||||
|
&& upd.getMessage().hasText()
|
||||||
|
&& upd.getMessage().getText().startsWith("my name is ")))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
return Ability.builder()
|
return Ability.builder()
|
||||||
|
@ -4,14 +4,16 @@ plugins {
|
|||||||
kotlin("jvm") version "1.6.10"
|
kotlin("jvm") version "1.6.10"
|
||||||
java
|
java
|
||||||
`maven-publish`
|
`maven-publish`
|
||||||
|
signing
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api("org.telegram:telegrambots-abilities:5.6.0")
|
api("org.telegram:telegrambots-abilities:6.0.1")
|
||||||
api("org.slf4j:slf4j-api:1.7.36")
|
api("org.slf4j:slf4j-api:1.7.36")
|
||||||
|
|
||||||
// There is nothing to test.
|
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
|
||||||
// testImplementation(kotlin("test"))
|
testImplementation("org.mockito:mockito-core:4.4.0")
|
||||||
|
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType<Javadoc> {
|
tasks.withType<Javadoc> {
|
||||||
@ -23,6 +25,8 @@ tasks.withType<Javadoc> {
|
|||||||
java {
|
java {
|
||||||
withJavadocJar()
|
withJavadocJar()
|
||||||
withSourcesJar()
|
withSourcesJar()
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.test {
|
tasks.test {
|
||||||
@ -35,24 +39,21 @@ tasks.withType<KotlinCompile> {
|
|||||||
|
|
||||||
publishing {
|
publishing {
|
||||||
repositories {
|
repositories {
|
||||||
val repoRootKey = "maven.repo.local.root"
|
if (project.version.toString().endsWith("-SNAPSHOT")) {
|
||||||
val snapshot = project.version.toString().endsWith("-SNAPSHOT")
|
maven("https://nexus.kuku.me/repository/maven-snapshots/") {
|
||||||
val repoRoot = System.getProperty(repoRootKey)?.trim()
|
credentials {
|
||||||
if (repoRoot == null || repoRoot.isEmpty()) {
|
username = project.properties["repo.credentials.private.username"].toString()
|
||||||
logger.warn(
|
password = project.properties["repo.credentials.private.password"].toString()
|
||||||
"\"$repoRootKey\" configuration item is not specified, " +
|
}
|
||||||
"please add start parameter \"-D$repoRootKey {localPublishRepo}\"" +
|
}
|
||||||
" (if you are not currently executing the publish task, " +
|
|
||||||
"you can ignore this information)"
|
|
||||||
)
|
|
||||||
return@repositories
|
|
||||||
}
|
|
||||||
val repoUri = if (snapshot) {
|
|
||||||
uri("$repoRoot/snapshots")
|
|
||||||
} else {
|
} else {
|
||||||
uri("$repoRoot/releases")
|
maven("https://nexus.kuku.me/repository/maven-releases/") {
|
||||||
|
credentials {
|
||||||
|
username = project.properties["repo.credentials.private.username"].toString()
|
||||||
|
password = project.properties["repo.credentials.private.password"].toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
maven(repoUri)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
publications {
|
publications {
|
||||||
@ -94,3 +95,8 @@ publishing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
signing {
|
||||||
|
useGpgCmd()
|
||||||
|
sign(publishing.publications["maven"])
|
||||||
|
}
|
||||||
|
@ -13,6 +13,7 @@ import java.io.File;
|
|||||||
* 所以将通过该接口工厂来创建扩展对象.
|
* 所以将通过该接口工厂来创建扩展对象.
|
||||||
*
|
*
|
||||||
* @author LamGC
|
* @author LamGC
|
||||||
|
* @since 0.0.1
|
||||||
*/
|
*/
|
||||||
public interface BotExtensionFactory {
|
public interface BotExtensionFactory {
|
||||||
|
|
||||||
@ -21,11 +22,15 @@ public interface BotExtensionFactory {
|
|||||||
*
|
*
|
||||||
* <p> 如扩展无使用 {@link org.telegram.abilitybots.api.db.DBContext} 的话,
|
* <p> 如扩展无使用 {@link org.telegram.abilitybots.api.db.DBContext} 的话,
|
||||||
* 也可以返回扩展单例, 因为 AbilityBot 本身并不禁止多个机器人共用一个扩展对象
|
* 也可以返回扩展单例, 因为 AbilityBot 本身并不禁止多个机器人共用一个扩展对象
|
||||||
* (因为 AbilityBot 只是调用了扩展中的方法来创建了功能对象).
|
* (AbilityBot 只是调用了扩展中的方法来创建 Ability 对象).
|
||||||
*
|
*
|
||||||
* @param bot 机器人对象.
|
* @param bot 机器人对象.
|
||||||
* @param shareDataFolder ScalaBot App 为扩展提供的数据目录, 建议存储在数据目录中, 便于数据的存储管理.
|
* @param shareDataFolder ScalaBot App 为扩展提供的共享数据目录.
|
||||||
* @return 返回为该 Bot 对象创建的扩展对象.
|
* <p>路径格式为:
|
||||||
|
* <pre> $DATA_ROOT/data/extensions/{GroupId}/{ArtifactId}</pre>
|
||||||
|
* <b>同一个扩展包的 Factory</b> 接收到的共享数据目录<b>都是一样的</b>,
|
||||||
|
* 建议将数据存储在数据目录中, 便于数据的存储管理.
|
||||||
|
* @return 返回为该 Bot 对象创建的扩展对象, 如果不希望为该机器人提供扩展, 可返回 {@code null}.
|
||||||
*/
|
*/
|
||||||
AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder);
|
AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder);
|
||||||
|
|
||||||
|
@ -1,32 +0,0 @@
|
|||||||
package net.lamgc.scalabot.extension;
|
|
||||||
|
|
||||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
|
||||||
import org.telegram.abilitybots.api.db.DBContext;
|
|
||||||
import org.telegram.abilitybots.api.sender.MessageSender;
|
|
||||||
import org.telegram.abilitybots.api.util.AbilityExtension;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public abstract class ScalaBotExtension implements AbilityExtension {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 扩展所属的机器人对象.
|
|
||||||
*
|
|
||||||
* <p> 不要给该属性添加 Getter, 会被当成 Ability 添加, 导致出现异常.
|
|
||||||
*/
|
|
||||||
protected final BaseAbilityBot bot;
|
|
||||||
|
|
||||||
public ScalaBotExtension(BaseAbilityBot bot) {
|
|
||||||
this.bot = bot;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected MessageSender getSender() {
|
|
||||||
return bot.sender();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected DBContext getDBContext() {
|
|
||||||
return bot.db();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,52 @@
|
|||||||
|
package net.lamgc.scalabot.extension.util;
|
||||||
|
|
||||||
|
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
public class AbilityBots {
|
||||||
|
|
||||||
|
private final static Pattern botTokenPattern = Pattern.compile("([1-9]\\d+):([A-Za-z\\d_-]{35,})");
|
||||||
|
|
||||||
|
private AbilityBots() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 AbilityBot 的账户 Id.
|
||||||
|
*
|
||||||
|
* <p> 账户 Id 来自于 botToken 中, token 的格式为 "[AccountId]:[Secret]".
|
||||||
|
* <p> 账户 Id 的真实性与 botToken 的有效性有关, 本方法并不会确保 botToken 的有效性, 一般情况下也无需考虑 Id 的有效性,
|
||||||
|
* 如果有需要, 可尝试通过调用 {@link org.telegram.telegrambots.meta.api.methods.GetMe} 来确保 botToken 的有效性.
|
||||||
|
*
|
||||||
|
* @param bot 要获取账户 Id 的 AbilityBot 对象.
|
||||||
|
* @return 返回 AbilityBot 的账户 Id.
|
||||||
|
* @throws IllegalArgumentException 当 AbilityBot 的 botToken 格式错误时抛出该异常.
|
||||||
|
*/
|
||||||
|
public static long getBotAccountId(BaseAbilityBot bot) {
|
||||||
|
String botToken = bot.getBotToken();
|
||||||
|
Matcher matcher = botTokenPattern.matcher(botToken);
|
||||||
|
if (!matcher.matches()) {
|
||||||
|
throw new IllegalArgumentException("Invalid token format.");
|
||||||
|
}
|
||||||
|
return Long.parseLong(matcher.group(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消某一对话的状态机.
|
||||||
|
*
|
||||||
|
* @param bot AbilityBot 实例.
|
||||||
|
* @param chatId 要删除状态机的聊天 Id.
|
||||||
|
* @return 如果状态机存在, 则删除后返回 true, 不存在(未开启任何状态机, 即没有触发任何 Reply)则返回 false.
|
||||||
|
*/
|
||||||
|
public static boolean cancelReplyState(BaseAbilityBot bot, long chatId) {
|
||||||
|
Map<Long, Integer> stateMap = bot.db().getMap("user_state_replies");
|
||||||
|
if (!stateMap.containsKey(chatId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
stateMap.remove(chatId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,121 @@
|
|||||||
|
package net.lamgc.scalabot.extension.util;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mapdb.DBMaker;
|
||||||
|
import org.telegram.abilitybots.api.bot.AbilityBot;
|
||||||
|
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||||
|
import org.telegram.abilitybots.api.db.MapDBContext;
|
||||||
|
import org.telegram.abilitybots.api.objects.*;
|
||||||
|
import org.telegram.abilitybots.api.sender.SilentSender;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.Message;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
||||||
|
import org.telegram.telegrambots.meta.api.objects.User;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
public class AbilityBotsTest {
|
||||||
|
|
||||||
|
public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false);
|
||||||
|
public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false);
|
||||||
|
|
||||||
|
static Update mockFullUpdate(BaseAbilityBot bot, User user, String args) {
|
||||||
|
bot.users().put(USER.getId(), USER);
|
||||||
|
bot.users().put(CREATOR.getId(), CREATOR);
|
||||||
|
bot.userIds().put(CREATOR.getUserName(), CREATOR.getId());
|
||||||
|
bot.userIds().put(USER.getUserName(), USER.getId());
|
||||||
|
|
||||||
|
bot.admins().add(CREATOR.getId());
|
||||||
|
|
||||||
|
Update update = mock(Update.class);
|
||||||
|
when(update.hasMessage()).thenReturn(true);
|
||||||
|
Message message = mock(Message.class);
|
||||||
|
when(message.getFrom()).thenReturn(user);
|
||||||
|
when(message.getText()).thenReturn(args);
|
||||||
|
when(message.hasText()).thenReturn(true);
|
||||||
|
when(message.isUserMessage()).thenReturn(true);
|
||||||
|
when(message.getChatId()).thenReturn(user.getId());
|
||||||
|
when(update.getMessage()).thenReturn(message);
|
||||||
|
return update;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getBotAccountIdTest() {
|
||||||
|
String expectToken = "1234567890:AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo";
|
||||||
|
long actual = AbilityBots.getBotAccountId(new TestingAbilityBot(expectToken, "test"));
|
||||||
|
assertEquals(1234567890, actual);
|
||||||
|
|
||||||
|
String badTokenA = "12c34d56a7890:AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo";
|
||||||
|
assertThrows(IllegalArgumentException.class, () ->
|
||||||
|
AbilityBots.getBotAccountId(new TestingAbilityBot(badTokenA, "test")));
|
||||||
|
|
||||||
|
String badTokenB = "12c34d56a7890AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo";
|
||||||
|
assertThrows(IllegalArgumentException.class, () ->
|
||||||
|
AbilityBots.getBotAccountId(new TestingAbilityBot(badTokenB, "test")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cancelReplyStateTest() {
|
||||||
|
User userA = new User(10001L, "first", false, "last", "username", null, false, false, false);
|
||||||
|
User userB = new User(10101L, "first", false, "last", "username", null, false, false, false);
|
||||||
|
SilentSender silent = mock(SilentSender.class);
|
||||||
|
BaseAbilityBot bot = new TestingAbilityBot("", "", silent);
|
||||||
|
bot.onRegister();
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "/set_reply"));
|
||||||
|
verify(silent, times(1)).send("Reply set!", userA.getId());
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "reply_01"));
|
||||||
|
verify(silent, times(1)).send("Reply 01", userA.getId());
|
||||||
|
assertTrue(AbilityBots.cancelReplyState(bot, userA.getId()));
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "reply_02"));
|
||||||
|
verify(silent, never()).send("Reply 02", userA.getId());
|
||||||
|
|
||||||
|
assertFalse(AbilityBots.cancelReplyState(bot, userB.getId()));
|
||||||
|
|
||||||
|
silent = mock(SilentSender.class);
|
||||||
|
bot = new TestingAbilityBot("", "", silent);
|
||||||
|
bot.onRegister();
|
||||||
|
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "/set_reply"));
|
||||||
|
verify(silent, times(1)).send("Reply set!", userA.getId());
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "reply_01"));
|
||||||
|
verify(silent, times(1)).send("Reply 01", userA.getId());
|
||||||
|
bot.onUpdateReceived(mockFullUpdate(bot, userA, "reply_02"));
|
||||||
|
verify(silent, times(1)).send("Reply 02", userA.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class TestingAbilityBot extends AbilityBot {
|
||||||
|
|
||||||
|
public TestingAbilityBot(String botToken, String botUsername) {
|
||||||
|
super(botToken, botUsername, new MapDBContext(DBMaker.heapDB().make()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public TestingAbilityBot(String botToken, String botUsername, SilentSender silentSender) {
|
||||||
|
super(botToken, botUsername, new MapDBContext(DBMaker.heapDB().make()));
|
||||||
|
this.silent = silentSender;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Ability setReply() {
|
||||||
|
return Ability.builder()
|
||||||
|
.name("set_reply")
|
||||||
|
.enableStats()
|
||||||
|
.locality(Locality.ALL)
|
||||||
|
.privacy(Privacy.PUBLIC)
|
||||||
|
.action(ctx -> ctx.bot().silent().send("Reply set!", ctx.chatId()))
|
||||||
|
.reply(ReplyFlow.builder(db())
|
||||||
|
.action((bot, upd) -> bot.silent().send("Reply 01", upd.getMessage().getChatId()))
|
||||||
|
.onlyIf(upd -> upd.hasMessage() && upd.getMessage().getText().equals("reply_01"))
|
||||||
|
.next(Reply.of((bot, upd) ->
|
||||||
|
bot.silent().send("Reply 02", upd.getMessage().getChatId()),
|
||||||
|
upd -> upd.hasMessage() && upd.getMessage().getText().equals("reply_02")))
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long creatorId() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Reference in New Issue
Block a user