mirror of
https://github.com/LamGC/ScalaBot.git
synced 2025-07-01 04:47:24 +00:00
Compare commits
170 Commits
v0.4.0
...
refactor-g
Author | SHA1 | Date | |
---|---|---|---|
cc7ef37539
|
|||
4cf670a4d0
|
|||
63f68acccd
|
|||
506f073bf6
|
|||
9dc4bfa28f | |||
92a1deac50
|
|||
0e2ce68a9c
|
|||
d57e63f8de
|
|||
73653cabc6 | |||
9e87591671 | |||
126092487d | |||
44bc52050c | |||
f809076df0 | |||
b34f05a90b | |||
ddc4de1340 | |||
a9134f378e | |||
dbb2fcdee1 | |||
ce00369a22 | |||
65bac28303 | |||
8bd6d5ffe5 | |||
1c4cc122c9 | |||
6083f4fc68 | |||
b33de4d63a | |||
fd67eb99eb
|
|||
ba306e679f | |||
f188d5bfa9 | |||
376086daa1 | |||
cee8797c40 | |||
77b5867dd7 | |||
33eefd9e60 | |||
0c81ca6d5f | |||
705150b961 | |||
e6f0550985 | |||
90c57ff9b1 | |||
d773cba776 | |||
f1c36aacdb | |||
fe9e7059c8 | |||
b42cc6bd2c | |||
ebfc387505 | |||
340f6ba3f3 | |||
e8f9dbbb05 | |||
cdbfa822b0 | |||
6d5ce324a5 | |||
734a871fdc | |||
a9ee432dec | |||
1fc386a226 | |||
40524e89c6 | |||
c972759ffb | |||
9b169ac957 | |||
f93a41af96
|
|||
8eb993da3e | |||
9065df0e04 | |||
9514c7b57e | |||
24219df63b
|
|||
14e9c4d686 | |||
8e83f714a7 | |||
939aed5850 | |||
a839cc63e6 | |||
8be3f770bf | |||
b1e7643b09
|
|||
4537e08107
|
|||
3ea1eec2dd
|
|||
fe9978dbe8 | |||
aece8221f1 | |||
4c9256f82f | |||
3f2e4e2d1f | |||
3810224667 | |||
3241bd2da9 | |||
dcac53fe65 | |||
0bc77ada5f | |||
f0b45568d1 | |||
a3dd9d4114 | |||
3afe3b52ed | |||
bdf75f1046 | |||
e834d4c7c7 | |||
2e1fae87b3 | |||
191bef5d68 | |||
55c435c4c0 | |||
758e0a9f16 | |||
5814817f3a | |||
2641901240 | |||
0070b400bb | |||
73e20ab737 | |||
03d24fbfe3 | |||
53e47353e8 | |||
81a97ee8e3 | |||
dbcbc88e1b | |||
f233a25323 | |||
2c91884db8 | |||
6b92b7e377
|
|||
375b815659
|
|||
f26d642320
|
|||
2db0b78962
|
|||
8b76a9aa9b
|
|||
bbc3288535 | |||
45ad734c7b | |||
1eaed8ce6f | |||
a624fcd37d | |||
59aa83c93e | |||
3ea0f4eacb
|
|||
d3e18d80ca
|
|||
1e0eebbd7e
|
|||
6f3c1ec592 | |||
c013dafdd7 | |||
e0bfd8796c | |||
67d561c0ab | |||
63687da0bb
|
|||
cd76249c33 | |||
5a8afd1549 | |||
651569dc8f | |||
bf2ea9a367
|
|||
540fe84f26
|
|||
712378b3ff
|
|||
961382fb56
|
|||
34d9ece6d7
|
|||
30a2cb34d5
|
|||
c94e0476b5
|
|||
6e5cd07c51
|
|||
d4b1438b0b
|
|||
90110335f5
|
|||
9c32d26c0d
|
|||
dfab6b14bd
|
|||
437cee499a
|
|||
4c30a1ac68
|
|||
3932db11a1
|
|||
d18c059498
|
|||
e6b581b8cd
|
|||
26d7443c87
|
|||
2bf4eb684e
|
|||
5251b62733
|
|||
3ec5a8e9c3
|
|||
62f6c08cd2
|
|||
5e6f64f056
|
|||
a036695330
|
|||
e9c975f5c5
|
|||
9aac42d414
|
|||
5add6d9909
|
|||
eee6b7d2c9
|
|||
ff396425a7
|
|||
580d9122e5
|
|||
2a607f1129
|
|||
2d6da7c1ae
|
|||
6235c5f51a
|
|||
255a02c93c
|
|||
dce28be9c7
|
|||
673c6d8392
|
|||
d586ca378e
|
|||
3ba4364a07
|
|||
eda0e522cd
|
|||
c7fedf3882
|
|||
a7de85eacb
|
|||
b6013e2fbe
|
|||
f79a4e4ff3
|
|||
93b9c6b727
|
|||
a8a0a9576f
|
|||
e8711e9974
|
|||
93685e9440
|
|||
92b7e84b3a
|
|||
8c4e48e3eb
|
|||
7f7b2b8895
|
|||
441991b705
|
|||
51d036c4c6
|
|||
3c54c33364
|
|||
43dd0e7bea
|
|||
c144755913
|
|||
9ed55204c0
|
|||
9b7fc30512
|
|||
27dc26160d
|
|||
ae411ce829
|
|||
1afe0f07a8
|
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@ -0,0 +1,2 @@
|
||||
**/
|
||||
!scalabot-app/build/install/
|
33
.github/dependabot.yml
vendored
Normal file
33
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: "gradle"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
# - package-ecosystem: "gradle"
|
||||
# directory: "/scalabot-app"
|
||||
# schedule:
|
||||
# interval: "weekly"
|
||||
# - package-ecosystem: "gradle"
|
||||
# directory: "/scalabot-meta"
|
||||
# schedule:
|
||||
# interval: "weekly"
|
||||
# - package-ecosystem: "gradle"
|
||||
# directory: "/scalabot-extension"
|
||||
# schedule:
|
||||
# interval: "weekly"
|
||||
# - package-ecosystem: "gradle"
|
||||
# directory: "/scalabot-ext-example"
|
||||
# schedule:
|
||||
# interval: "weekly"
|
33
.github/workflows/binary-compatibility-verification.yml
vendored
Normal file
33
.github/workflows/binary-compatibility-verification.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: Binary compatibility verification (for API)
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'scalabot-meta/**'
|
||||
- 'scalabot-extension/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'scalabot-meta/**'
|
||||
- 'scalabot-extension/**'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
apiCompatibilityCheck:
|
||||
timeout-minutes: 8
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '11'
|
||||
distribution: 'adopt-hotspot'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
- name: Build and run binary compatibility verification
|
||||
run: ./gradlew apiCheck
|
12
.github/workflows/build-and-test.yml
vendored
12
.github/workflows/build-and-test.yml
vendored
@ -18,17 +18,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v3
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '11'
|
||||
distribution: 'adopt-hotspot'
|
||||
cache: 'gradle'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
- name: Build and test
|
||||
uses: gradle/gradle-build-action@v2.2.1
|
||||
with:
|
||||
gradle-version: 'wrapper'
|
||||
arguments: test
|
||||
run: ./gradlew clean test
|
||||
|
63
.github/workflows/create-release.yml
vendored
Normal file
63
.github/workflows/create-release.yml
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
name: Create release draft
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v[0-9]+.[0-9]+.[0-9]+*'
|
||||
|
||||
# 该 Action 有以下步骤:
|
||||
# 1. 拉取并构建代码, 然后生成 Application 发行包;
|
||||
# 2. 创建 Release, 并标记为 Draft(草稿);
|
||||
# 3. 上传 Application 发行包;
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
create-release:
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# 创建更新日志.
|
||||
- name: 'Get Previous tag'
|
||||
id: previous-tag
|
||||
uses: younited/get-previous-tag-action@v1.1.0
|
||||
with:
|
||||
match: "v*.*.*"
|
||||
- name: Set up Python 3
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
- name: Install Commitizen
|
||||
run: pip install -U commitizen
|
||||
- name: Create Change log
|
||||
run: cz ch --start-rev ${{ steps.previous-tag.outputs.previous-tag }} --file-name ${{ github.workspace }}/CURRENT_CHANGELOG.md
|
||||
|
||||
# 开始构建项目.
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '11'
|
||||
distribution: 'adopt-hotspot'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
- name: Build and test
|
||||
uses: gradle/gradle-build-action@v3.1.0
|
||||
run: ./gradlew clean test assembleDist
|
||||
|
||||
# 创建新的发行版本
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
draft: true
|
||||
body_path: ${{ github.workspace }}/CURRENT_CHANGELOG.md
|
||||
files: |
|
||||
*/build/distributions/*
|
||||
*/build/libs/*
|
10
.github/workflows/gradle-wrapper-validation.yml
vendored
10
.github/workflows/gradle-wrapper-validation.yml
vendored
@ -1,10 +0,0 @@
|
||||
name: "Validate Gradle Wrapper"
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
validation:
|
||||
name: "Validation"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: gradle/wrapper-validation-action@v1
|
46
.github/workflows/publish-artifacts.yml
vendored
Normal file
46
.github/workflows/publish-artifacts.yml
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
name: Publish artifacts
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
|
||||
env:
|
||||
IMAGE_NAME: lamgc/scalabot
|
||||
|
||||
jobs:
|
||||
publish-container-image:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '11'
|
||||
distribution: 'adopt-hotspot'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
- name: Build and test
|
||||
run: ./gradlew clean test installDist
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker BuildX
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push container image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ env.IMAGE_NAME }}:latest, ${{ env.IMAGE_NAME }}:${{ github.ref_name }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
46
.github/workflows/release-dev-container-image.yml
vendored
Normal file
46
.github/workflows/release-dev-container-image.yml
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
name: Build development version container image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "main"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 11
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: '11'
|
||||
distribution: 'adopt-hotspot'
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
- name: Build project and install Distribution package
|
||||
run: ./gradlew clean test installDist
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker BuildX
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push container image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: lamgc/scalabot:dev
|
||||
platforms: linux/amd64,linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
8
Dockerfile
Normal file
8
Dockerfile
Normal file
@ -0,0 +1,8 @@
|
||||
FROM eclipse-temurin:21-jdk-alpine
|
||||
|
||||
ENV BOT_DATA_PATH /scalabot/data/
|
||||
WORKDIR /scalabot/run/
|
||||
|
||||
CMD ["/scalabot/app/bin/scalabot-app"]
|
||||
|
||||
COPY scalabot-app/build/install/scalabot-app/ /scalabot/app/
|
@ -1,6 +1,7 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "1.6.10" apply false
|
||||
id("org.jetbrains.kotlinx.kover") version "0.5.1" apply false
|
||||
kotlin("jvm") version "1.9.23" apply false
|
||||
id("org.jetbrains.kotlinx.kover") version "0.7.5" apply false
|
||||
id("org.jetbrains.kotlinx.binary-compatibility-validator") version "0.14.0" apply false
|
||||
}
|
||||
|
||||
allprojects {
|
||||
@ -12,5 +13,5 @@ allprojects {
|
||||
|
||||
}
|
||||
group = "net.lamgc"
|
||||
version = "0.4.0"
|
||||
version = "0.7.0"
|
||||
}
|
@ -10,9 +10,9 @@ dependencies {
|
||||
implementation(project(":scalabot-meta"))
|
||||
implementation(project(":scalabot-extension"))
|
||||
|
||||
implementation("org.slf4j:slf4j-api:1.7.36")
|
||||
implementation("io.github.microutils:kotlin-logging:2.1.23")
|
||||
implementation("ch.qos.logback:logback-classic:1.2.11")
|
||||
implementation("org.slf4j:slf4j-api:2.0.11")
|
||||
implementation("io.github.microutils:kotlin-logging:3.0.5")
|
||||
implementation("ch.qos.logback:logback-classic:1.4.14")
|
||||
|
||||
val aetherVersion = "1.1.0"
|
||||
implementation("org.eclipse.aether:aether-api:$aetherVersion")
|
||||
@ -23,20 +23,20 @@ dependencies {
|
||||
implementation("org.eclipse.aether:aether-connector-basic:$aetherVersion")
|
||||
implementation("org.apache.maven:maven-aether-provider:3.3.9")
|
||||
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.2")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.20")
|
||||
implementation("com.google.code.gson:gson:2.9.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.23")
|
||||
implementation("com.google.code.gson:gson:2.10.1")
|
||||
|
||||
implementation("org.jdom:jdom2:2.0.6.1")
|
||||
|
||||
implementation("org.telegram:telegrambots-abilities:6.0.1")
|
||||
implementation("org.telegram:telegrambots:6.0.1")
|
||||
implementation("org.telegram:telegrambots-abilities:6.9.7.1")
|
||||
implementation("org.telegram:telegrambots:6.9.7.1")
|
||||
|
||||
implementation("io.prometheus:simpleclient:0.15.0")
|
||||
implementation("io.prometheus:simpleclient_httpserver:0.15.0")
|
||||
implementation("io.prometheus:simpleclient:0.16.0")
|
||||
implementation("io.prometheus:simpleclient_httpserver:0.16.0")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
testImplementation("io.mockk:mockk:1.12.4")
|
||||
testImplementation("io.mockk:mockk:1.13.9")
|
||||
testImplementation("com.github.stefanbirkner:system-lambda:1.2.1")
|
||||
}
|
||||
|
||||
@ -56,3 +56,8 @@ application {
|
||||
tasks.jar.configure {
|
||||
exclude("**/logback-test.xml")
|
||||
}
|
||||
|
||||
tasks.withType<AbstractArchiveTask>().configureEach {
|
||||
isPreserveFileTimestamps = false
|
||||
isReproducibleFileOrder = true
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package net.lamgc.scalabot
|
||||
import ch.qos.logback.core.PropertyDefinerBase
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.google.gson.JsonArray
|
||||
import mu.KotlinLogging
|
||||
import net.lamgc.scalabot.config.*
|
||||
import net.lamgc.scalabot.config.serializer.*
|
||||
@ -12,13 +12,15 @@ import org.eclipse.aether.repository.Authentication
|
||||
import org.eclipse.aether.repository.Proxy
|
||||
import org.eclipse.aether.repository.RemoteRepository
|
||||
import org.eclipse.aether.repository.RepositoryPolicy
|
||||
import org.slf4j.event.Level
|
||||
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||
import java.io.File
|
||||
import java.net.URL
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.system.exitProcess
|
||||
import java.util.function.Supplier
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
private val log = KotlinLogging.logger { }
|
||||
|
||||
@ -41,13 +43,32 @@ internal fun ProxyConfig.toAetherProxy(): Proxy? {
|
||||
return Proxy(typeStr, host, port)
|
||||
}
|
||||
|
||||
internal fun MavenRepositoryConfig.toRemoteRepository(proxyConfig: ProxyConfig): RemoteRepository {
|
||||
val builder =
|
||||
RemoteRepository.Builder(id ?: createDefaultRepositoryId(), checkRepositoryLayout(layout), url.toString())
|
||||
internal fun MavenRepositoryConfig.toRemoteRepository(proxyConfig: ProxyConfig? = null): RemoteRepository {
|
||||
val repositoryId = if (id == null) {
|
||||
val generatedRepoId = createDefaultRepositoryId()
|
||||
log.debug { "仓库 Url `$url` 未设置仓库 Id, 已分配缺省 Id: $generatedRepoId" }
|
||||
generatedRepoId
|
||||
} else if ("local".contentEquals(id, ignoreCase = true)) {
|
||||
val generatedRepoId = createDefaultRepositoryId()
|
||||
log.debug { "仓库 Url `$url` 不允许使用 `local` 作为仓库 Id, 已分配缺省 Id: $generatedRepoId" }
|
||||
generatedRepoId
|
||||
} else {
|
||||
id
|
||||
}
|
||||
val builder = RemoteRepository.Builder(repositoryId, checkRepositoryLayout(layout), url.toString())
|
||||
if (proxy != null) {
|
||||
builder.setProxy(proxy)
|
||||
} else if (proxyConfig.type == ProxyType.HTTP) {
|
||||
val selfProxy = proxy!!
|
||||
builder.setProxy(selfProxy)
|
||||
log.debug { "仓库 $repositoryId 已使用独立的代理配置: ${selfProxy.type}://${selfProxy.host}:${selfProxy.port}" }
|
||||
} else if (proxyConfig != null) {
|
||||
if (proxyConfig.type in (ProxyType.HTTP..ProxyType.HTTPS)) {
|
||||
builder.setProxy(proxyConfig.toAetherProxy())
|
||||
log.debug { "仓库 $repositoryId 已使用 全局/Bot 代理配置: $proxyConfig" }
|
||||
} else {
|
||||
log.debug { "仓库 $repositoryId 不支持 全局/Bot 的代理配置: `$proxyConfig` (仅支持 HTTP 和 HTTPS)" }
|
||||
}
|
||||
} else {
|
||||
log.debug { "仓库 $repositoryId 不使用代理." }
|
||||
}
|
||||
|
||||
builder.setReleasePolicy(
|
||||
@ -88,9 +109,9 @@ private fun createDefaultRepositoryId(): String {
|
||||
* 必须提供 `pathSupplier` 或 `fileSupplier` 其中一个, 才能正常提供路径.
|
||||
*/
|
||||
internal enum class AppPaths(
|
||||
private val pathSupplier: () -> String = { fileSupplier.invoke().canonicalPath },
|
||||
private val pathSupplier: PathSupplier,
|
||||
private val initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer,
|
||||
private val fileSupplier: () -> File = { File(pathSupplier()) }
|
||||
private val fileSupplier: FileSupplier,
|
||||
) {
|
||||
/**
|
||||
* 数据根目录.
|
||||
@ -99,7 +120,7 @@ internal enum class AppPaths(
|
||||
*
|
||||
* 提示: 结尾不带 `/`.
|
||||
*/
|
||||
DATA_ROOT(fileSupplier = {
|
||||
DATA_ROOT(fileSupplier = FileSupplier {
|
||||
File(
|
||||
System.getProperty(PathConst.PROP_DATA_PATH) ?: System.getenv(PathConst.ENV_DATA_PATH)
|
||||
?: System.getProperty("user.dir") ?: "."
|
||||
@ -111,10 +132,10 @@ internal enum class AppPaths(
|
||||
}
|
||||
}),
|
||||
|
||||
DEFAULT_CONFIG_APPLICATION({ "$DATA_ROOT/config.json" }, {
|
||||
CONFIG_APPLICATION(PathSupplier { "$DATA_ROOT/config.json" }, {
|
||||
if (!file.exists()) {
|
||||
file.bufferedWriter(StandardCharsets.UTF_8).use {
|
||||
GsonConst.botConfigGson.toJson(
|
||||
GsonConst.appConfigGson.toJson(
|
||||
AppConfig(
|
||||
mavenRepositories = listOf(
|
||||
MavenRepositoryConfig(
|
||||
@ -127,7 +148,7 @@ internal enum class AppPaths(
|
||||
}
|
||||
}
|
||||
}),
|
||||
DEFAULT_CONFIG_BOT({ "$DATA_ROOT/bot.json" }, {
|
||||
CONFIG_BOT(PathSupplier { "$DATA_ROOT/bot.json" }, {
|
||||
if (!file.exists()) {
|
||||
file.bufferedWriter(StandardCharsets.UTF_8).use {
|
||||
GsonConst.botConfigGson.toJson(
|
||||
@ -153,10 +174,25 @@ internal enum class AppPaths(
|
||||
TEMP({ "$DATA_ROOT/tmp/" })
|
||||
;
|
||||
|
||||
val file: File
|
||||
get() = fileSupplier.invoke()
|
||||
val path: String
|
||||
get() = pathSupplier.invoke()
|
||||
constructor(pathSupplier: PathSupplier, initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer) : this(
|
||||
fileSupplier = FileSupplier { File(pathSupplier.path).canonicalFile },
|
||||
pathSupplier = pathSupplier,
|
||||
initializer = initializer
|
||||
)
|
||||
|
||||
constructor(fileSupplier: FileSupplier, initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer) : this(
|
||||
fileSupplier = fileSupplier,
|
||||
pathSupplier = PathSupplier { fileSupplier.file.canonicalPath },
|
||||
initializer = initializer
|
||||
)
|
||||
|
||||
constructor(pathSupplier: () -> String) : this(
|
||||
fileSupplier = FileSupplier { File(pathSupplier.invoke()).canonicalFile },
|
||||
pathSupplier = PathSupplier { pathSupplier.invoke() }
|
||||
)
|
||||
|
||||
val file: File by fileSupplier
|
||||
val path: String by pathSupplier
|
||||
|
||||
private val initialized = AtomicBoolean(false)
|
||||
|
||||
@ -168,15 +204,44 @@ internal enum class AppPaths(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个内部方法, 用于将 [initialized] 状态重置.
|
||||
*
|
||||
* 如果不重置该状态, 将使得单元测试无法让 AppPath 重新初始化文件.
|
||||
*
|
||||
* 警告: 该方法不应该被非测试代码调用.
|
||||
*/
|
||||
@Suppress("unused")
|
||||
private fun reset() {
|
||||
log.warn {
|
||||
"初始化状态已重置: `${this.name}`, 如果在非测试环境中重置状态, 请报告该问题."
|
||||
}
|
||||
initialized.set(false)
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return path
|
||||
}
|
||||
|
||||
private object PathConst {
|
||||
object PathConst {
|
||||
const val PROP_DATA_PATH = "bot.path.data"
|
||||
const val ENV_DATA_PATH = "BOT_DATA_PATH"
|
||||
}
|
||||
|
||||
private class FileSupplier(private val supplier: Supplier<File>) {
|
||||
operator fun getValue(appPaths: AppPaths, property: KProperty<*>): File = supplier.get()
|
||||
|
||||
val file: File
|
||||
get() = supplier.get()
|
||||
}
|
||||
|
||||
private class PathSupplier(private val supplier: Supplier<String>) {
|
||||
operator fun getValue(appPaths: AppPaths, property: KProperty<*>): String = supplier.get()
|
||||
|
||||
val path: String
|
||||
get() = supplier.get()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -188,8 +253,37 @@ internal class LogDirectorySupplier : PropertyDefinerBase() {
|
||||
}
|
||||
}
|
||||
|
||||
internal class LogLevelSupplier : PropertyDefinerBase() {
|
||||
override fun getPropertyValue(): String {
|
||||
val property = System.getProperty("scalabot.log.level", System.getenv("BOT_LOG_LEVEL"))
|
||||
val level = if (property != null) {
|
||||
try {
|
||||
Level.valueOf(property.uppercase())
|
||||
} catch (e: IllegalArgumentException) {
|
||||
addWarn("Invalid log level: `$property`, the log will be output using the Info log level.")
|
||||
Level.INFO
|
||||
}
|
||||
} else {
|
||||
Level.INFO
|
||||
}
|
||||
return level.name
|
||||
}
|
||||
}
|
||||
|
||||
internal class NetworkVerboseLogSupplier : PropertyDefinerBase() {
|
||||
override fun getPropertyValue(): String {
|
||||
val propertyValue = System.getProperty("scalabot.log.network.verbose", "false")
|
||||
return if (propertyValue.toBoolean()) {
|
||||
"DEBUG"
|
||||
} else {
|
||||
"INFO"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object Const {
|
||||
val config = loadAppConfig()
|
||||
const val METRICS_NAMESPACE = "scalabot"
|
||||
}
|
||||
|
||||
private fun AppPaths.defaultInitializer() {
|
||||
@ -207,9 +301,14 @@ private fun AppPaths.defaultInitializer() {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun initialFiles() {
|
||||
val configFilesNotInitialized = !AppPaths.DEFAULT_CONFIG_APPLICATION.file.exists()
|
||||
&& !AppPaths.DEFAULT_CONFIG_BOT.file.exists()
|
||||
/**
|
||||
* 执行 AppPaths 所有项目的初始化, 并检查是否停止运行, 让用户编辑配置.
|
||||
*
|
||||
* @return 如果需要让用户编辑配置, 则返回 `true`.
|
||||
*/
|
||||
internal fun initialFiles(): Boolean {
|
||||
val configFilesNotInitialized = !AppPaths.CONFIG_APPLICATION.file.exists()
|
||||
&& !AppPaths.CONFIG_BOT.file.exists()
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
path.initial()
|
||||
@ -217,12 +316,13 @@ internal fun initialFiles() {
|
||||
|
||||
if (configFilesNotInitialized) {
|
||||
log.warn { "配置文件已初始化, 请根据需要修改配置文件后重新启动本程序." }
|
||||
exitProcess(1)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private object GsonConst {
|
||||
val baseGson: Gson = GsonBuilder()
|
||||
internal object GsonConst {
|
||||
private val baseGson: Gson = GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.serializeNulls()
|
||||
.create()
|
||||
@ -238,10 +338,11 @@ private object GsonConst {
|
||||
.registerTypeAdapter(ProxyType::class.java, ProxyTypeSerializer)
|
||||
.registerTypeAdapter(BotConfig::class.java, BotConfigSerializer)
|
||||
.registerTypeAdapter(Artifact::class.java, ArtifactSerializer)
|
||||
.registerTypeAdapter(BotAccount::class.java, BotAccountSerializer)
|
||||
.create()
|
||||
}
|
||||
|
||||
internal fun loadAppConfig(configFile: File = AppPaths.DEFAULT_CONFIG_APPLICATION.file): AppConfig {
|
||||
internal fun loadAppConfig(configFile: File = AppPaths.CONFIG_APPLICATION.file): AppConfig {
|
||||
try {
|
||||
configFile.bufferedReader(StandardCharsets.UTF_8).use {
|
||||
return GsonConst.appConfigGson.fromJson(it, AppConfig::class.java)!!
|
||||
@ -252,10 +353,10 @@ internal fun loadAppConfig(configFile: File = AppPaths.DEFAULT_CONFIG_APPLICATIO
|
||||
}
|
||||
}
|
||||
|
||||
internal fun loadBotConfig(botConfigFile: File = AppPaths.DEFAULT_CONFIG_BOT.file): Set<BotConfig>? {
|
||||
internal fun loadBotConfigJson(botConfigFile: File = AppPaths.CONFIG_BOT.file): JsonArray? {
|
||||
try {
|
||||
botConfigFile.bufferedReader(StandardCharsets.UTF_8).use {
|
||||
return GsonConst.botConfigGson.fromJson(it, object : TypeToken<Set<BotConfig>>() {}.type)!!
|
||||
return GsonConst.botConfigGson.fromJson(it, JsonArray::class.java)!!
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
log.error(e) { "读取 Bot 配置文件 (bot.json) 时发生错误, 请检查配置格式是否正确." }
|
||||
|
@ -1,16 +1,16 @@
|
||||
package net.lamgc.scalabot
|
||||
|
||||
import com.google.gson.JsonParseException
|
||||
import io.prometheus.client.exporter.HTTPServer
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import mu.KotlinLogging
|
||||
import net.lamgc.scalabot.config.AppConfig
|
||||
import net.lamgc.scalabot.config.BotConfig
|
||||
import net.lamgc.scalabot.config.MetricsConfig
|
||||
import net.lamgc.scalabot.config.ProxyType
|
||||
import net.lamgc.scalabot.config.*
|
||||
import net.lamgc.scalabot.util.registerShutdownHook
|
||||
import org.eclipse.aether.repository.LocalRepository
|
||||
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||
import org.telegram.telegrambots.meta.TelegramBotsApi
|
||||
import org.telegram.telegrambots.meta.api.methods.GetMe
|
||||
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException
|
||||
import org.telegram.telegrambots.meta.generics.BotSession
|
||||
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
|
||||
import java.io.File
|
||||
@ -28,12 +28,15 @@ private val log = KotlinLogging.logger { }
|
||||
fun main(args: Array<String>): Unit = runBlocking {
|
||||
log.info { "ScalaBot 正在启动中..." }
|
||||
log.info { "数据目录: ${AppPaths.DATA_ROOT}" }
|
||||
log.debug { "Kotlin: ${KotlinVersion.CURRENT}, JVM: ${Runtime.version()}" }
|
||||
log.debug { "启动参数: ${args.joinToString(prefix = "[", postfix = "]")}" }
|
||||
initialFiles()
|
||||
if (initialFiles()) {
|
||||
exitProcess(1)
|
||||
}
|
||||
|
||||
val launcher = Launcher()
|
||||
.registerShutdownHook()
|
||||
startMetricsServer()
|
||||
startMetricsServer()?.registerShutdownHook()
|
||||
if (!launcher.launch()) {
|
||||
exitProcess(1)
|
||||
}
|
||||
@ -57,12 +60,14 @@ internal fun startMetricsServer(config: MetricsConfig = Const.config.metrics): H
|
||||
|
||||
val httpServer = builder
|
||||
.build()
|
||||
.registerShutdownHook()
|
||||
log.info { "运行指标服务器已启动. (Port: ${httpServer.port})" }
|
||||
return httpServer
|
||||
}
|
||||
|
||||
internal class Launcher(private val config: AppConfig = Const.config) : AutoCloseable {
|
||||
internal class Launcher(
|
||||
private val config: AppConfig = Const.config,
|
||||
private val configFile: File = AppPaths.CONFIG_APPLICATION.file,
|
||||
) : AutoCloseable {
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
@ -76,9 +81,7 @@ internal class Launcher(private val config: AppConfig = Const.config) : AutoClos
|
||||
private fun getMavenLocalRepository(): LocalRepository {
|
||||
val localPath =
|
||||
if (config.mavenLocalRepository != null && config.mavenLocalRepository!!.isNotEmpty()) {
|
||||
val repoPath = AppPaths.DATA_ROOT.file.toPath()
|
||||
.resolve(config.mavenLocalRepository!!)
|
||||
.apply {
|
||||
val repoPath = configFile.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.")
|
||||
@ -111,22 +114,43 @@ internal class Launcher(private val config: AppConfig = Const.config) : AutoClos
|
||||
|
||||
@Synchronized
|
||||
fun launch(): Boolean {
|
||||
val botConfigs = loadBotConfig() ?: return false
|
||||
if (botConfigs.isEmpty()) {
|
||||
val botConfigs = loadBotConfigJson() ?: return false
|
||||
if (botConfigs.isEmpty) {
|
||||
log.warn { "尚未配置任何机器人, 请先配置机器人后再启动本程序." }
|
||||
return false
|
||||
} else if (botConfigs.none { it.enabled }) {
|
||||
log.warn { "配置文件中没有已启用的机器人, 请至少启用一个机器人." }
|
||||
return false
|
||||
}
|
||||
for (botConfig in botConfigs) {
|
||||
var launchedCounts = 0
|
||||
for (botConfigJson in botConfigs) {
|
||||
val botConfig = try {
|
||||
GsonConst.botConfigGson.fromJson(botConfigJson, BotConfig::class.java)
|
||||
} catch (e: JsonParseException) {
|
||||
val botName = try {
|
||||
botConfigJson.asJsonObject.get("account")?.asJsonObject?.get("name")?.asString ?: "Unknown"
|
||||
} catch (e: Exception) {
|
||||
"Unknown"
|
||||
}
|
||||
log.error(e) { "机器人 `$botName` 配置有误, 跳过该机器人的启动." }
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
launchBot(botConfig)
|
||||
launchedCounts++
|
||||
} catch (e: Exception) {
|
||||
if (e is TelegramApiRequestException && e.errorCode == 401) {
|
||||
log.error { "机器人 `${botConfig.account.name}` 的 Bot Token 无效, 请检查配置: [${e.errorCode}] ${e.apiResponse}" }
|
||||
} else {
|
||||
log.error(e) { "机器人 `${botConfig.account.name}` 启动时发生错误." }
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return if (launchedCounts != 0) {
|
||||
log.info { "已启动 $launchedCounts 个机器人." }
|
||||
true
|
||||
} else {
|
||||
log.warn { "未启动任何机器人, 请检查配置并至少启用一个机器人." }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchBot(botConfig: BotConfig) {
|
||||
@ -135,16 +159,20 @@ internal class Launcher(private val config: AppConfig = Const.config) : AutoClos
|
||||
return
|
||||
}
|
||||
log.info { "正在启动机器人 `${botConfig.account.name}`..." }
|
||||
val botOption = DefaultBotOptions().apply {
|
||||
val proxyConfig =
|
||||
if (botConfig.proxy.type != ProxyType.NO_PROXY) {
|
||||
log.debug { "[Bot ${botConfig.account.name}] 使用独立代理: ${botConfig.proxy.type}" }
|
||||
botConfig.proxy
|
||||
} else if (config.proxy.type != ProxyType.NO_PROXY) {
|
||||
log.debug { "[Bot ${botConfig.account.name}] 使用全局代理: ${botConfig.proxy.type}" }
|
||||
config.proxy
|
||||
} else {
|
||||
null
|
||||
log.debug { "[Bot ${botConfig.account.name}] 不使用代理." }
|
||||
ProxyConfig(type = ProxyType.NO_PROXY)
|
||||
}
|
||||
if (proxyConfig != null) {
|
||||
|
||||
val botOption = DefaultBotOptions().apply {
|
||||
if (proxyConfig.type != ProxyType.NO_PROXY) {
|
||||
proxyType = proxyConfig.type.toTelegramBotsType()
|
||||
proxyHost = config.proxy.host
|
||||
proxyPort = config.proxy.port
|
||||
@ -156,13 +184,13 @@ internal class Launcher(private val config: AppConfig = Const.config) : AutoClos
|
||||
val account = botConfig.account
|
||||
|
||||
val remoteRepositories = config.mavenRepositories
|
||||
.map { it.toRemoteRepository(config.proxy) }
|
||||
.map { it.toRemoteRepository(proxyConfig) }
|
||||
.toMutableList().apply {
|
||||
if (this.none {
|
||||
it.url == MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL
|
||||
|| it.url == MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL.trimEnd('/')
|
||||
}) {
|
||||
add(MavenRepositoryExtensionFinder.getMavenCentralRepository(proxy = config.proxy.toAetherProxy()))
|
||||
add(MavenRepositoryExtensionFinder.getMavenCentralRepository(proxy = proxyConfig.toAetherProxy()))
|
||||
}
|
||||
}.toList()
|
||||
val extensionPackageFinders = setOf(
|
||||
@ -179,6 +207,10 @@ internal class Launcher(private val config: AppConfig = Const.config) : AutoClos
|
||||
extensionPackageFinders,
|
||||
botConfig
|
||||
)
|
||||
|
||||
val botUser = bot.execute(GetMe())
|
||||
log.debug { "已验证 Bot Token 有效性, Bot Username: ${botUser.userName}" }
|
||||
|
||||
botSessionMap[bot] = botApi.registerBot(bot)
|
||||
log.info { "机器人 `${bot.botUsername}` 已启动." }
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
package net.lamgc.scalabot
|
||||
|
||||
import mu.KotlinLogging
|
||||
import net.lamgc.scalabot.extension.BotExtensionCreateOptions
|
||||
import net.lamgc.scalabot.extension.BotExtensionFactory
|
||||
import net.lamgc.scalabot.util.getPriority
|
||||
import org.eclipse.aether.artifact.Artifact
|
||||
@ -14,6 +15,18 @@ import java.nio.charset.StandardCharsets
|
||||
import java.util.*
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* 扩展加载器.
|
||||
*
|
||||
* 扩展加载器并非负责加载扩展的 Class, 而是委派搜索器发现并获取扩展, 然后加载扩展实例.
|
||||
*
|
||||
* 注意, 扩展加载器将内置两个 Finder: [FileNameFinder] 和 [MavenMetaInformationFinder].
|
||||
*
|
||||
* @param bot 扩展加载器所负责的 ScalaBot 实例.
|
||||
* @param extensionsDataFolder 提供给扩展用于数据存储的根目录(实际目录为 `{root}/{group...}/{artifact}`).
|
||||
* @param extensionsPath 提供给 Finder 用于搜索扩展的本地扩展包存放路径.
|
||||
* @param extensionFinders 加载器所使用的搜索器集合. 加载扩展时将使用所提供的的加载器.
|
||||
*/
|
||||
internal class ExtensionLoader(
|
||||
private val bot: ScalaBot,
|
||||
private val extensionsDataFolder: File = AppPaths.DATA_EXTENSIONS.file,
|
||||
@ -27,6 +40,13 @@ internal class ExtensionLoader(
|
||||
MavenMetaInformationFinder
|
||||
).apply { addAll(extensionFinders) }.toSet()
|
||||
|
||||
/**
|
||||
* 加载扩展, 并返回扩展项.
|
||||
*
|
||||
* 调用本方法后, 将会指派提供的 Finder 搜索 ScalaBot 配置的扩展包.
|
||||
*
|
||||
* @return 返回存放了所有已加载扩展项的 Set. 可通过 [LoadedExtensionEntry] 获取扩展的有关信息.
|
||||
*/
|
||||
fun getExtensions(): Set<LoadedExtensionEntry> {
|
||||
val extensionEntries = mutableSetOf<LoadedExtensionEntry>()
|
||||
for (extensionArtifact in bot.extensions) {
|
||||
@ -52,6 +72,17 @@ internal class ExtensionLoader(
|
||||
|
||||
/**
|
||||
* 检查是否发生冲突.
|
||||
*
|
||||
* 扩展包冲突有两种情况:
|
||||
* 1. 有多个同为最高优先级的搜索器搜索到了扩展包.
|
||||
* 2. 唯一的最高优先级搜索器搜索到了多个扩展包.
|
||||
*
|
||||
* 扩展包冲突指的是**有多个具有相同构件坐标的扩展包被搜索到**,
|
||||
* 如果不顾扩展包冲突直接加载的话, 将会出现安全隐患,
|
||||
* 因此在加载器发现冲突的情况下将输出相关信息, 提示用户进行排查.
|
||||
*
|
||||
* @param foundResult 扩展包搜索结果.
|
||||
*
|
||||
* @return 如果出现冲突, 返回 `true`.
|
||||
*/
|
||||
private fun checkConflict(foundResult: Map<ExtensionPackageFinder, Set<FoundExtensionPackage>>): Boolean {
|
||||
@ -68,6 +99,9 @@ internal class ExtensionLoader(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从结果中过滤出由最高优先级的搜索器搜索到的扩展包.
|
||||
*/
|
||||
private fun filterHighPriorityResult(foundResult: Map<ExtensionPackageFinder, Set<FoundExtensionPackage>>)
|
||||
: Map<ExtensionPackageFinder, Set<FoundExtensionPackage>> {
|
||||
val finders: List<ExtensionPackageFinder> = foundResult.keys
|
||||
@ -89,7 +123,12 @@ internal class ExtensionLoader(
|
||||
for (factory in extClassLoader.serviceLoader) {
|
||||
try {
|
||||
val extension =
|
||||
factory.createExtensionInstance(bot, getExtensionDataFolder(extensionArtifact))
|
||||
factory.createExtensionInstance(
|
||||
bot, getExtensionDataFolder(extensionArtifact),
|
||||
BotExtensionCreateOptions(
|
||||
bot.botConfig.proxy.copy()
|
||||
)
|
||||
)
|
||||
if (extension == null) {
|
||||
log.debug { "Factory ${factory::class.java} 创建插件时返回了 null, 已跳过. (BotName: ${bot.botUsername})" }
|
||||
continue
|
||||
@ -102,6 +141,11 @@ internal class ExtensionLoader(
|
||||
return factories.toSet()
|
||||
}
|
||||
|
||||
/**
|
||||
* 只是用来统计扩展包搜索结果的数量而已.
|
||||
*
|
||||
* @return 返回扩展包的数量.
|
||||
*/
|
||||
private fun allFoundedPackageNumber(filesMap: Map<ExtensionPackageFinder, Set<FoundExtensionPackage>>): Int {
|
||||
var number = 0
|
||||
for (files in filesMap.values) {
|
||||
@ -110,6 +154,14 @@ internal class ExtensionLoader(
|
||||
return number
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索指定构件坐标的依赖包.
|
||||
*
|
||||
* 搜索扩展包将根据搜索器优先级从高到低依次搜索, 当某一个优先级的搜索器搜到扩展包后将停止搜索.
|
||||
* 可以根据不同优先级的搜索器, 配置扩展包的主用与备用文件.
|
||||
*
|
||||
* @return 返回各个搜索器返回的搜索结果.
|
||||
*/
|
||||
private fun findExtensionPackage(
|
||||
extensionArtifact: Artifact,
|
||||
): Map<ExtensionPackageFinder, Set<FoundExtensionPackage>> {
|
||||
@ -138,13 +190,21 @@ internal class ExtensionLoader(
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查扩展包搜索器是否设置了 [FinderRules] 注解.
|
||||
* @return 如果已设置注解, 则返回 `true`.
|
||||
*/
|
||||
private fun checkExtensionPackageFinder(finder: ExtensionPackageFinder): Boolean =
|
||||
finder::class.java.getDeclaredAnnotation(FinderRules::class.java) != null
|
||||
|
||||
/**
|
||||
* 在日志中输出有关扩展包冲突的错误信息.
|
||||
*/
|
||||
private fun printExtensionFileConflictError(
|
||||
extensionArtifact: Artifact,
|
||||
foundResult: Map<ExtensionPackageFinder, Set<FoundExtensionPackage>>
|
||||
) {
|
||||
log.error {
|
||||
val errMessage = StringBuilder(
|
||||
"""
|
||||
[Bot ${bot.botUsername}] 扩展包 $extensionArtifact 存在多个文件, 为防止安全问题, 已禁止加载该扩展包:
|
||||
@ -160,9 +220,15 @@ internal class ExtensionLoader(
|
||||
.append(URLDecoder.decode(file.getRawUrl().toString(), StandardCharsets.UTF_8)).append('\n')
|
||||
}
|
||||
}
|
||||
log.error { errMessage }
|
||||
errMessage
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建扩展数据目录, 并返回 [File] 对象.
|
||||
* @param extensionArtifact 扩展包构件坐标.
|
||||
* @return 返回对应的数据存储目录.
|
||||
*/
|
||||
private fun getExtensionDataFolder(extensionArtifact: Artifact): File {
|
||||
val dataFolder =
|
||||
File(extensionsDataFolder, "${extensionArtifact.groupId}/${extensionArtifact.artifactId}")
|
||||
@ -172,6 +238,12 @@ internal class ExtensionLoader(
|
||||
return dataFolder
|
||||
}
|
||||
|
||||
/**
|
||||
* 已加载扩展项.
|
||||
* @property extensionArtifact 扩展的构件坐标([Artifact]).
|
||||
* @property factoryClass 扩展的工厂类.
|
||||
* @property extension 扩展实例.
|
||||
*/
|
||||
data class LoadedExtensionEntry(
|
||||
val extensionArtifact: Artifact,
|
||||
val factoryClass: Class<out BotExtensionFactory>,
|
||||
@ -181,6 +253,10 @@ internal class ExtensionLoader(
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展的类加载器清除器.
|
||||
*
|
||||
* 原计划是用来通过关闭 ClassLoader 来卸载扩展的, 但似乎并没有这么做.
|
||||
*
|
||||
* 该类为保留措施, 尚未启用.
|
||||
*/
|
||||
internal object ExtensionClassLoaderCleaner {
|
||||
@ -257,7 +333,7 @@ internal interface ExtensionPackageFinder {
|
||||
|
||||
/**
|
||||
* 已找到的扩展包信息.
|
||||
* 通过实现该接口, 以寻找远端文件的 [ExtensionPackageFinder]
|
||||
* 通过实现该接口, 以寻找远端文件的 [ExtensionPackageFinder];
|
||||
* 可以在适当的时候将扩展包下载到本地, 而无需在搜索阶段下载扩展包.
|
||||
*/
|
||||
internal interface FoundExtensionPackage {
|
||||
@ -296,6 +372,7 @@ private fun FoundExtensionPackage.createClassLoader(): ExtensionClassLoader =
|
||||
* 已找到的扩展包文件.
|
||||
* @param artifact 扩展包构件坐标.
|
||||
* @param file 已找到的扩展包文件.
|
||||
* @param finder 搜索到该扩展包的搜索器.
|
||||
*/
|
||||
internal class FileFoundExtensionPackage(
|
||||
private val artifact: Artifact,
|
||||
@ -342,14 +419,14 @@ internal class ExtensionClassLoader(urls: Array<URL>, dependencyLoader: ClassLoa
|
||||
// 以免使用了不来自扩展包的机器人扩展.
|
||||
|
||||
override fun getResources(name: String?): Enumeration<URL> {
|
||||
if (BotExtensionFactory::class.java.equals(name)) {
|
||||
if ("META-INF/services/${BotExtensionFactory::class.java.name}" == name) {
|
||||
return findResources(name)
|
||||
}
|
||||
return super.getResources(name)
|
||||
}
|
||||
|
||||
override fun getResource(name: String?): URL? {
|
||||
if (BotExtensionFactory::class.java.equals(name)) {
|
||||
if ("META-INF/services/${BotExtensionFactory::class.java}" == name) {
|
||||
return findResource(name)
|
||||
}
|
||||
return super.getResource(name)
|
||||
|
@ -257,23 +257,25 @@ internal class MavenRepositoryExtensionFinder(
|
||||
}
|
||||
|
||||
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<FoundExtensionPackage> {
|
||||
val repositories = repositorySystem.newResolutionRepositories(repoSystemSession, remoteRepositories).toList()
|
||||
log.debug {
|
||||
StringBuilder().apply {
|
||||
append("构件 $extensionArtifact 将在以下仓库拉取: \n")
|
||||
remoteRepositories.forEach {
|
||||
append("\t- ${it}\n")
|
||||
repositories.forEach {
|
||||
append("\t- $it\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val extensionArtifactResult = repositorySystem.resolveArtifact(
|
||||
repoSystemSession,
|
||||
ArtifactRequest(
|
||||
extensionArtifact,
|
||||
repositorySystem.newResolutionRepositories(repoSystemSession, remoteRepositories),
|
||||
repositories,
|
||||
null
|
||||
)
|
||||
)
|
||||
val extResolvedArtifact = extensionArtifactResult.artifact
|
||||
val resolvedArtifact: Artifact? = extensionArtifactResult.artifact
|
||||
if (!extensionArtifactResult.isResolved) {
|
||||
if (extensionArtifactResult.isMissing) {
|
||||
log.warn { "在指定的仓库中找不到构件: ${extensionArtifactResult.artifact}" }
|
||||
@ -281,17 +283,26 @@ internal class MavenRepositoryExtensionFinder(
|
||||
printArtifactResultExceptions(extensionArtifactResult.exceptions)
|
||||
}
|
||||
return emptySet()
|
||||
} else if (resolvedArtifact == null) {
|
||||
log.warn { "无法在指定的仓库中解析构件: $extensionArtifact" }
|
||||
return emptySet()
|
||||
}
|
||||
|
||||
log.info {
|
||||
"已从 Maven 仓库 `${extensionArtifactResult.repository.id}` 中找到" +
|
||||
"扩展包 `${resolvedArtifact.groupId}:${resolvedArtifact.artifactId}` " +
|
||||
"版本号 `${resolvedArtifact.version}`."
|
||||
}
|
||||
|
||||
val request = DependencyRequest(
|
||||
CollectRequest(Dependency(extResolvedArtifact, null), remoteRepositories),
|
||||
CollectRequest(Dependency(resolvedArtifact, null), repositories),
|
||||
ScopeDependencyFilter(setOf("runtime", "compile", "provided"), null)
|
||||
)
|
||||
val dependencyResult = repositorySystem.resolveDependencies(repoSystemSession, request)
|
||||
val dependencies = checkAndCollectDependencyArtifacts(extensionArtifact, dependencyResult.artifactResults)
|
||||
?: return emptySet()
|
||||
|
||||
return setOf(MavenExtensionPackage(this, extResolvedArtifact, extensionArtifactResult.repository, dependencies))
|
||||
return setOf(MavenExtensionPackage(this, resolvedArtifact, extensionArtifactResult.repository, dependencies))
|
||||
}
|
||||
|
||||
private fun checkAndCollectDependencyArtifacts(
|
||||
|
@ -29,7 +29,7 @@ internal class ScalaBot(
|
||||
db: DBContext,
|
||||
options: DefaultBotOptions,
|
||||
extensionFinders: Set<ExtensionPackageFinder>,
|
||||
botConfig: BotConfig,
|
||||
val botConfig: BotConfig,
|
||||
private val creatorId: Long = botConfig.account.creatorId,
|
||||
val accountId: Long = botConfig.account.id,
|
||||
val extensions: Set<Artifact> = botConfig.extensions
|
||||
@ -50,6 +50,8 @@ internal class ScalaBot(
|
||||
extensionFinders = extensionFinders
|
||||
)
|
||||
|
||||
private val accountIdString = accountId.toString()
|
||||
|
||||
init {
|
||||
log.info { "[Bot $botUsername] 正在加载扩展..." }
|
||||
val extensionEntries = extensionLoader.getExtensions()
|
||||
@ -66,18 +68,18 @@ internal class ScalaBot(
|
||||
override fun creatorId(): Long = creatorId
|
||||
|
||||
override fun onUpdateReceived(update: Update?) {
|
||||
botUpdateCounter.labels(botUsername).inc()
|
||||
botUpdateGauge.labels(botUsername).inc()
|
||||
botUpdateCounter.labels(botUsername, accountIdString).inc()
|
||||
botUpdateGauge.labels(botUsername, accountIdString).inc()
|
||||
|
||||
val timer = updateProcessTime.labels(botUsername).startTimer()
|
||||
val timer = updateProcessTime.labels(botUsername, accountIdString).startTimer()
|
||||
try {
|
||||
super.onUpdateReceived(update)
|
||||
} catch (e: Exception) {
|
||||
exceptionHandlingCounter.labels(botUsername).inc()
|
||||
exceptionHandlingCounter.labels(botUsername, accountIdString).inc()
|
||||
throw e
|
||||
} finally {
|
||||
timer.observeDuration()
|
||||
botUpdateGauge.labels(botUsername).dec()
|
||||
botUpdateGauge.labels(botUsername, accountIdString).dec()
|
||||
}
|
||||
}
|
||||
|
||||
@ -134,7 +136,8 @@ internal class ScalaBot(
|
||||
private val botUpdateCounter = Counter.build()
|
||||
.name("updates_total")
|
||||
.help("Total number of updates received by all bots.")
|
||||
.labelNames("bot_name")
|
||||
.labelNames("bot_name", "bot_id")
|
||||
.namespace(Const.METRICS_NAMESPACE)
|
||||
.subsystem("telegrambots")
|
||||
.register()
|
||||
|
||||
@ -142,7 +145,8 @@ internal class ScalaBot(
|
||||
private val botUpdateGauge = Gauge.build()
|
||||
.name("updates_in_progress")
|
||||
.help("Number of updates in process by all bots.")
|
||||
.labelNames("bot_name")
|
||||
.labelNames("bot_name", "bot_id")
|
||||
.namespace(Const.METRICS_NAMESPACE)
|
||||
.subsystem("telegrambots")
|
||||
.register()
|
||||
|
||||
@ -150,6 +154,7 @@ internal class ScalaBot(
|
||||
private val onlineBotGauge = Gauge.build()
|
||||
.name("bots_online")
|
||||
.help("Number of bots Online.")
|
||||
.namespace(Const.METRICS_NAMESPACE)
|
||||
.subsystem("telegrambots")
|
||||
.register()
|
||||
|
||||
@ -161,7 +166,8 @@ internal class ScalaBot(
|
||||
"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)"
|
||||
)
|
||||
.labelNames("bot_name")
|
||||
.labelNames("bot_name", "bot_id")
|
||||
.namespace(Const.METRICS_NAMESPACE)
|
||||
.subsystem("telegrambots")
|
||||
.register()
|
||||
|
||||
@ -169,7 +175,8 @@ internal class ScalaBot(
|
||||
private val exceptionHandlingCounter = Counter.build()
|
||||
.name("updates_exception_handling")
|
||||
.help("Number of exceptions during processing.")
|
||||
.labelNames("bot_name")
|
||||
.labelNames("bot_name", "bot_id")
|
||||
.namespace(Const.METRICS_NAMESPACE)
|
||||
.subsystem("telegrambots")
|
||||
.register()
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ fun <T : AutoCloseable> T.registerShutdownHook(): T {
|
||||
private object UtilsInternal {
|
||||
|
||||
val autoCloseableSet = mutableSetOf<AutoCloseable>()
|
||||
private val log = KotlinLogging.logger { }
|
||||
private val log = KotlinLogging.logger(UtilsInternal::class.java.name)
|
||||
|
||||
init {
|
||||
Runtime.getRuntime().addShutdownHook(Thread(this::doCloseResources, "Shutdown-AutoCloseable"))
|
||||
|
@ -1,6 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<included>
|
||||
<define name="DATA_LOGS" class="net.lamgc.scalabot.LogDirectorySupplier"/>
|
||||
<define name="LOG_LEVEL" class="net.lamgc.scalabot.LogLevelSupplier"/>
|
||||
<define name="NETWORK_LOG_LEVEL" class="net.lamgc.scalabot.NetworkVerboseLogSupplier"/>
|
||||
|
||||
<appender name="STD_OUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
@ -24,7 +26,7 @@
|
||||
<appender name="FILE_OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${DATA_LOGS}/latest.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>data/logs/%d{yyyy-MM-dd}.log.gz</fileNamePattern>
|
||||
<fileNamePattern>${DATA_LOGS}/%d{yyyy-MM-dd}.log.gz</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
|
@ -1,16 +0,0 @@
|
||||
<configuration scan="false" debug="false">
|
||||
<include resource="base-logback.xml"/>
|
||||
|
||||
<logger name="org.apache.http" 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.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">
|
||||
<appender-ref ref="FILE_OUT"/>
|
||||
<appender-ref ref="STD_ERR"/>
|
||||
<appender-ref ref="STD_OUT"/>
|
||||
</root>
|
||||
</configuration>
|
@ -1,7 +1,14 @@
|
||||
<configuration scan="false" debug="false">
|
||||
<include resource="base-logback.xml"/>
|
||||
|
||||
<root level="INFO">
|
||||
<logger name="org.apache.http" level="${NETWORK_LOG_LEVEL}"/>
|
||||
<logger name="org.eclipse.aether.internal.impl.DefaultTransporterProvider" level="${NETWORK_LOG_LEVEL}"/>
|
||||
<logger name="org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider" level="${NETWORK_LOG_LEVEL}"/>
|
||||
<logger name="org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManager" level="${NETWORK_LOG_LEVEL}"/>
|
||||
<logger name="org.telegram.telegrambots.facilities.proxysocketfactorys" level="${NETWORK_LOG_LEVEL}"/>
|
||||
<logger name="org.eclipse.aether.internal.impl.DefaultUpdateCheckManager" level="${NETWORK_LOG_LEVEL}"/>
|
||||
|
||||
<root level="${LOG_LEVEL}">
|
||||
<appender-ref ref="FILE_OUT"/>
|
||||
<appender-ref ref="STD_ERR"/>
|
||||
<appender-ref ref="STD_OUT"/>
|
||||
|
@ -4,31 +4,50 @@ import com.github.stefanbirkner.systemlambda.SystemLambda
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.verify
|
||||
import mu.KotlinLogging
|
||||
import net.lamgc.scalabot.config.MavenRepositoryConfig
|
||||
import net.lamgc.scalabot.config.ProxyConfig
|
||||
import net.lamgc.scalabot.config.ProxyType
|
||||
import org.junit.jupiter.api.assertThrows
|
||||
import org.junit.jupiter.api.io.TempDir
|
||||
import org.telegram.telegrambots.bots.DefaultBotOptions
|
||||
import java.io.File
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertTrue
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.deleteExisting
|
||||
import kotlin.test.*
|
||||
|
||||
internal class AppPathsTest {
|
||||
|
||||
@Test
|
||||
fun `Consistency check`() {
|
||||
for (path in AppPaths.values()) {
|
||||
assertEquals(
|
||||
File(path.path).canonicalPath,
|
||||
path.file.canonicalPath,
|
||||
"路径 File 与 Path 不一致: ${path.name}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Data root path priority`() {
|
||||
System.setProperty("bot.path.data", "fromSystemProperties")
|
||||
System.setProperty(AppPaths.PathConst.PROP_DATA_PATH, "fromSystemProperties")
|
||||
|
||||
assertEquals("fromSystemProperties", AppPaths.DATA_ROOT.file.path, "`DATA_ROOT`没有优先返回 Property 的值.")
|
||||
System.getProperties().remove("bot.path.data")
|
||||
System.getProperties().remove(AppPaths.PathConst.PROP_DATA_PATH)
|
||||
|
||||
val expectEnvValue = "fromEnvironmentVariable"
|
||||
SystemLambda.withEnvironmentVariable("BOT_DATA_PATH", expectEnvValue).execute {
|
||||
SystemLambda.withEnvironmentVariable(AppPaths.PathConst.ENV_DATA_PATH, expectEnvValue).execute {
|
||||
assertEquals(
|
||||
expectEnvValue, AppPaths.DATA_ROOT.file.path,
|
||||
"`DATA_ROOT`没有优先返回 env 的值."
|
||||
)
|
||||
}
|
||||
|
||||
SystemLambda.withEnvironmentVariable("BOT_DATA_PATH", null).execute {
|
||||
SystemLambda.withEnvironmentVariable(AppPaths.PathConst.ENV_DATA_PATH, null).execute {
|
||||
assertEquals(
|
||||
System.getProperty("user.dir"), AppPaths.DATA_ROOT.file.path,
|
||||
"`DATA_ROOT`没有返回 System.properties `user.dir` 的值."
|
||||
@ -116,5 +135,282 @@ internal class AppPathsTest {
|
||||
defaultInitializerMethod.isAccessible = false
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
fun `loadBotConfig test`(@TempDir testDir: File) {
|
||||
assertNull(loadBotConfigJson(File("/NOT_EXISTS_FILE")), "加载 BotConfigs 失败时应该返回 null.")
|
||||
|
||||
SystemLambda.withEnvironmentVariable(AppPaths.PathConst.ENV_DATA_PATH, testDir.canonicalPath).execute {
|
||||
assertNull(loadBotConfigJson(), "加载 BotConfigs 失败时应该返回 null.")
|
||||
|
||||
File(testDir, "bot.json").apply {
|
||||
//language=JSON5
|
||||
writeText(
|
||||
"""
|
||||
[
|
||||
{
|
||||
"enabled": false,
|
||||
"account": {
|
||||
"name": "TestBot",
|
||||
"token": "123456789:AAHErDroUTznQsOd_oZPJ6cQEj4Z5mGHO10",
|
||||
"creatorId": 123456789
|
||||
},
|
||||
"proxy": {
|
||||
"host": "localhost",
|
||||
"port": 8080,
|
||||
"type": "HTTP"
|
||||
},
|
||||
"disableBuiltInAbility": false,
|
||||
"autoUpdateCommandList": true,
|
||||
"extensions": [
|
||||
"org.example.test:test-extension:1.0.0"
|
||||
],
|
||||
"baseApiUrl": "http://localhost:8080"
|
||||
}
|
||||
]
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
val botConfigJsons = loadBotConfigJson()
|
||||
assertNotNull(botConfigJsons)
|
||||
assertEquals(1, botConfigJsons.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadAppConfig test`(@TempDir testDir: File) {
|
||||
assertThrows<IOException>("加载失败时应该抛出 IOException.") {
|
||||
loadAppConfig(File("/NOT_EXISTS_FILE"))
|
||||
}
|
||||
|
||||
SystemLambda.withEnvironmentVariable(AppPaths.PathConst.ENV_DATA_PATH, testDir.canonicalPath).execute {
|
||||
assertThrows<IOException>("加载失败时应该抛出 IOException.") {
|
||||
loadAppConfig()
|
||||
}
|
||||
|
||||
File(testDir, "config.json").apply {
|
||||
//language=JSON5
|
||||
writeText(
|
||||
"""
|
||||
{
|
||||
"proxy": {
|
||||
"type": "HTTP",
|
||||
"host": "localhost",
|
||||
"port": 8080
|
||||
},
|
||||
"metrics": {
|
||||
"enable": true,
|
||||
"port": 8800,
|
||||
"bindAddress": "127.0.0.1",
|
||||
"authenticator": {
|
||||
"username": "username",
|
||||
"password": "password"
|
||||
}
|
||||
},
|
||||
"mavenRepositories": [
|
||||
{
|
||||
"url": "https://repository.maven.apache.org/maven2/"
|
||||
}
|
||||
],
|
||||
"mavenLocalRepository": "file:///tmp/maven-local-repository"
|
||||
}
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
val appConfigs = loadAppConfig()
|
||||
assertNotNull(appConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ProxyType_toTelegramBotsType test`() {
|
||||
val expectTypeMapping = mapOf(
|
||||
ProxyType.NO_PROXY to DefaultBotOptions.ProxyType.NO_PROXY,
|
||||
ProxyType.SOCKS5 to DefaultBotOptions.ProxyType.SOCKS5,
|
||||
ProxyType.SOCKS4 to DefaultBotOptions.ProxyType.SOCKS4,
|
||||
ProxyType.HTTP to DefaultBotOptions.ProxyType.HTTP,
|
||||
ProxyType.HTTPS to DefaultBotOptions.ProxyType.HTTP
|
||||
)
|
||||
|
||||
for (proxyType in ProxyType.values()) {
|
||||
assertEquals(
|
||||
expectTypeMapping[proxyType],
|
||||
proxyType.toTelegramBotsType(),
|
||||
"ProxyType 转换失败."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ProxyConfig_toAetherProxy test`() {
|
||||
val host = "proxy.example.org"
|
||||
val port = 1080
|
||||
|
||||
val expectNotNullProxyType = setOf(
|
||||
ProxyType.HTTP,
|
||||
ProxyType.HTTPS
|
||||
)
|
||||
for (proxyType in ProxyType.values()) {
|
||||
val proxyConfig = ProxyConfig(proxyType, host, port)
|
||||
val aetherProxy = proxyConfig.toAetherProxy()
|
||||
if (expectNotNullProxyType.contains(proxyType)) {
|
||||
assertNotNull(aetherProxy, "支持的代理类型应该不为 null.")
|
||||
assertEquals(host, aetherProxy.host)
|
||||
assertEquals(port, aetherProxy.port)
|
||||
} else {
|
||||
assertNull(aetherProxy, "不支持的代理类型应该返回 null.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `MavenRepositoryConfig_toRemoteRepository test`() {
|
||||
val defaultMavenRepositoryConfig = MavenRepositoryConfig(
|
||||
url = URL(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL),
|
||||
enableReleases = true,
|
||||
enableSnapshots = false
|
||||
)
|
||||
val remoteRepositoryWithoutId = defaultMavenRepositoryConfig.toRemoteRepository(
|
||||
ProxyConfig(ProxyType.NO_PROXY, "", 0)
|
||||
)
|
||||
assertEquals(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL, remoteRepositoryWithoutId.url.toString())
|
||||
assertNotNull(remoteRepositoryWithoutId.id)
|
||||
assertTrue(remoteRepositoryWithoutId.getPolicy(false).isEnabled)
|
||||
assertFalse(remoteRepositoryWithoutId.getPolicy(true).isEnabled)
|
||||
|
||||
val remoteRepositoryWithId = defaultMavenRepositoryConfig.copy(id = "test-repo").toRemoteRepository(
|
||||
ProxyConfig(ProxyType.HTTP, "127.0.0.1", 1080)
|
||||
)
|
||||
|
||||
assertEquals("test-repo", remoteRepositoryWithId.id)
|
||||
assertEquals(MavenRepositoryExtensionFinder.MAVEN_CENTRAL_URL, remoteRepositoryWithId.url.toString())
|
||||
assertEquals("http", remoteRepositoryWithId.proxy.type)
|
||||
assertEquals("127.0.0.1", remoteRepositoryWithId.proxy.host)
|
||||
assertEquals(1080, remoteRepositoryWithId.proxy.port)
|
||||
assertEquals(remoteRepositoryWithId.id, remoteRepositoryWithId.id)
|
||||
|
||||
val remoteRepositoryWithProxy = defaultMavenRepositoryConfig.copy(
|
||||
id = "test-repo",
|
||||
proxy = ProxyConfig(ProxyType.HTTP, "example.org", 1080).toAetherProxy()
|
||||
).toRemoteRepository(ProxyConfig(ProxyType.HTTP, "localhost", 8080))
|
||||
assertEquals("http", remoteRepositoryWithProxy.proxy.type)
|
||||
assertEquals("example.org", remoteRepositoryWithProxy.proxy.host, "未优先使用 MavenRepositoryConfig 中的 proxy 属性.")
|
||||
assertEquals(1080, remoteRepositoryWithProxy.proxy.port, "未优先使用 MavenRepositoryConfig 中的 proxy 属性.")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `checkRepositoryLayout test`() {
|
||||
val noProxyConfig = ProxyConfig(ProxyType.NO_PROXY, "", 0)
|
||||
assertEquals(
|
||||
"default", MavenRepositoryConfig(url = URL("https://repo.example.org"))
|
||||
.toRemoteRepository(noProxyConfig).contentType
|
||||
)
|
||||
assertEquals(
|
||||
"legacy", MavenRepositoryConfig(url = URL("https://repo.example.org"), layout = "LEgaCY")
|
||||
.toRemoteRepository(noProxyConfig).contentType
|
||||
)
|
||||
assertThrows<IllegalArgumentException> {
|
||||
MavenRepositoryConfig(
|
||||
url = URL("https://repo.example.org"),
|
||||
layout = "NOT_EXISTS_LAYOUT"
|
||||
).toRemoteRepository(noProxyConfig)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `initialFiles test`(@TempDir testDir: Path) {
|
||||
// 这么做是为了让日志文件创建在其他地方, 由于日志文件在运行时会持续占用, 在 windows 中文件会被锁定,
|
||||
// 导致测试框架无法正常清除测试所使用的临时文件夹.
|
||||
val logsDir = Files.createTempDirectory("ammmmmm-logs-")
|
||||
System.setProperty(AppPaths.PathConst.PROP_DATA_PATH, logsDir.toString())
|
||||
assertEquals(logsDir.toString(), AppPaths.DATA_ROOT.path, "日志目录设定失败.")
|
||||
KotlinLogging.logger("TEST").error { "日志占用.(无需理会), 日志目录: $logsDir" }
|
||||
AppPaths.DATA_LOGS.file.listFiles { _, name -> name.endsWith(".log") }?.forEach {
|
||||
it.deleteOnExit()
|
||||
}
|
||||
|
||||
val fullInitializeDir = Files.createTempDirectory(testDir, "fullInitialize")
|
||||
fullInitializeDir.deleteExisting()
|
||||
System.setProperty(AppPaths.PathConst.PROP_DATA_PATH, fullInitializeDir.toString())
|
||||
assertEquals(fullInitializeDir.toString(), AppPaths.DATA_ROOT.path, "测试路径设定失败.")
|
||||
|
||||
assertTrue(initialFiles(), "方法未能提醒用户编辑初始配置文件.")
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
|
||||
if (path.file.isFile) {
|
||||
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
|
||||
}
|
||||
path.reset()
|
||||
}
|
||||
|
||||
assertFalse(initialFiles(), "方法试图在配置已初始化的情况下提醒用户编辑初始配置文件.")
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
|
||||
if (path.file.isFile) {
|
||||
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
|
||||
}
|
||||
path.reset()
|
||||
}
|
||||
|
||||
assertTrue(AppPaths.CONFIG_APPLICATION.file.delete(), "config.json 删除失败.")
|
||||
assertFalse(initialFiles(), "方法试图在部分配置已初始化的情况下提醒用户编辑初始配置文件.")
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
|
||||
if (path.file.isFile) {
|
||||
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
|
||||
}
|
||||
path.reset()
|
||||
}
|
||||
|
||||
assertTrue(AppPaths.CONFIG_BOT.file.delete(), "bot.json 删除失败.")
|
||||
assertFalse(initialFiles(), "方法试图在部分配置已初始化的情况下提醒用户编辑初始配置文件.")
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
|
||||
if (path.file.isFile) {
|
||||
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
|
||||
}
|
||||
path.reset()
|
||||
}
|
||||
|
||||
assertTrue(AppPaths.CONFIG_APPLICATION.file.delete(), "config.json 删除失败.")
|
||||
assertTrue(AppPaths.CONFIG_BOT.file.delete(), "bot.json 删除失败.")
|
||||
assertTrue(
|
||||
initialFiles(),
|
||||
"在主要配置文件(config.json 和 bot.json)不存在的情况下初始化文件后, 方法未能提醒用户编辑初始配置文件."
|
||||
)
|
||||
|
||||
for (path in AppPaths.values()) {
|
||||
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
|
||||
if (path.file.isFile) {
|
||||
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
|
||||
}
|
||||
}
|
||||
|
||||
AppPaths.CONFIG_APPLICATION.file.writeText("Test-APPLICATION")
|
||||
AppPaths.CONFIG_BOT.file.writeText("Test-BOT")
|
||||
assertFalse(initialFiles(), "方法试图在部分配置已初始化的情况下提醒用户编辑初始配置文件.")
|
||||
assertEquals(
|
||||
"Test-APPLICATION", AppPaths.CONFIG_APPLICATION.file.readText(),
|
||||
"config.json 被覆盖. initialized 并未阻止重复初始化."
|
||||
)
|
||||
assertEquals(
|
||||
"Test-BOT", AppPaths.CONFIG_BOT.file.readText(),
|
||||
"bot.json 被覆盖. initialized 并未阻止重复初始化."
|
||||
)
|
||||
|
||||
System.getProperties().remove(AppPaths.PathConst.PROP_DATA_PATH)
|
||||
}
|
||||
|
||||
private fun AppPaths.reset() {
|
||||
val method = AppPaths::class.java.getDeclaredMethod("reset")
|
||||
method.isAccessible = true
|
||||
method.invoke(this)
|
||||
method.isAccessible = false
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ plugins {
|
||||
dependencies {
|
||||
compileOnly(project(":scalabot-extension"))
|
||||
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.1")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
package net.lamgc.scalabot.simple;
|
||||
|
||||
import net.lamgc.scalabot.extension.BotExtensionCreateOptions;
|
||||
import net.lamgc.scalabot.extension.BotExtensionFactory;
|
||||
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
|
||||
import org.telegram.abilitybots.api.util.AbilityExtension;
|
||||
@ -9,7 +10,7 @@ import java.io.File;
|
||||
public class SimpleExtensionFactory implements BotExtensionFactory {
|
||||
|
||||
@Override
|
||||
public AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder) {
|
||||
public AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder, BotExtensionCreateOptions options) {
|
||||
return new SayHelloExtension(bot);
|
||||
}
|
||||
|
||||
|
9
scalabot-extension/api/scalabot-extension.api
Normal file
9
scalabot-extension/api/scalabot-extension.api
Normal file
@ -0,0 +1,9 @@
|
||||
public abstract interface class net/lamgc/scalabot/extension/BotExtensionFactory {
|
||||
public abstract fun createExtensionInstance (Lorg/telegram/abilitybots/api/bot/BaseAbilityBot;Ljava/io/File;)Lorg/telegram/abilitybots/api/util/AbilityExtension;
|
||||
}
|
||||
|
||||
public class net/lamgc/scalabot/extension/util/AbilityBots {
|
||||
public static fun cancelReplyState (Lorg/telegram/abilitybots/api/bot/BaseAbilityBot;J)Z
|
||||
public static fun getBotAccountId (Lorg/telegram/abilitybots/api/bot/BaseAbilityBot;)J
|
||||
}
|
||||
|
@ -1,16 +1,18 @@
|
||||
plugins {
|
||||
kotlin("jvm")
|
||||
java
|
||||
`java-library`
|
||||
jacoco
|
||||
`maven-publish`
|
||||
signing
|
||||
id("org.jetbrains.kotlinx.binary-compatibility-validator")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api("org.telegram:telegrambots-abilities:6.0.1")
|
||||
api("org.slf4j:slf4j-api:1.7.36")
|
||||
implementation("commons-codec:commons-codec:1.16.1")
|
||||
api("org.telegram:telegrambots-abilities:6.9.7.1")
|
||||
api(project(":scalabot-meta"))
|
||||
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
|
||||
testImplementation("org.mockito:mockito-core:4.6.1")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.1")
|
||||
testImplementation("org.mockito:mockito-core:5.11.0")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
|
||||
}
|
||||
|
||||
@ -29,23 +31,35 @@ java {
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
finalizedBy(tasks.jacocoTestReport)
|
||||
}
|
||||
|
||||
tasks.jacocoTestReport {
|
||||
dependsOn(tasks.test)
|
||||
}
|
||||
|
||||
tasks.withType<AbstractArchiveTask>().configureEach {
|
||||
isPreserveFileTimestamps = false
|
||||
isReproducibleFileOrder = true
|
||||
}
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
if (project.version.toString().endsWith("-SNAPSHOT")) {
|
||||
maven("https://nexus.kuku.me/repository/maven-snapshots/") {
|
||||
maven("https://git.lamgc.me/api/packages/LamGC/maven") {
|
||||
credentials {
|
||||
username = project.properties["repo.credentials.private.username"].toString()
|
||||
password = project.properties["repo.credentials.private.password"].toString()
|
||||
username = project.properties["repo.credentials.self-git.username"].toString()
|
||||
password = project.properties["repo.credentials.self-git.password"].toString()
|
||||
}
|
||||
}
|
||||
val kukuRepoUrl = if (project.version.toString().endsWith("-SNAPSHOT", ignoreCase = true)) {
|
||||
"https://nexus.kuku.me/repository/maven-snapshots/"
|
||||
} else {
|
||||
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()
|
||||
"https://nexus.kuku.me/repository/maven-releases/"
|
||||
}
|
||||
maven(kukuRepoUrl) {
|
||||
credentials {
|
||||
username = project.properties["repo.credentials.kuku-repo.username"].toString()
|
||||
password = project.properties["repo.credentials.kuku-repo.password"].toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,22 @@
|
||||
package net.lamgc.scalabot.extension;
|
||||
|
||||
import net.lamgc.scalabot.config.ProxyConfig;
|
||||
|
||||
/**
|
||||
* BotExtension 创建参数.
|
||||
* <p>
|
||||
* 通过该类可向 {@link BotExtensionFactory} 提供更多创建 BotExtension 时可用的参数.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class BotExtensionCreateOptions {
|
||||
|
||||
private final ProxyConfig proxy;
|
||||
|
||||
public BotExtensionCreateOptions(ProxyConfig proxy) {
|
||||
this.proxy = proxy;
|
||||
}
|
||||
|
||||
public ProxyConfig getProxy() {
|
||||
return proxy;
|
||||
}
|
||||
}
|
@ -31,7 +31,34 @@ public interface BotExtensionFactory {
|
||||
* <b>同一个扩展包的 Factory</b> 接收到的共享数据目录<b>都是一样的</b>,
|
||||
* 建议将数据存储在数据目录中, 便于数据的存储管理.
|
||||
* @return 返回为该 Bot 对象创建的扩展对象, 如果不希望为该机器人提供扩展, 可返回 {@code null}.
|
||||
* @deprecated 请使用 {@link #createExtensionInstance(BaseAbilityBot, File, BotExtensionCreateOptions)},
|
||||
* 该方法最迟在 1.0.0 正式版中移除.
|
||||
* @since 0.0.1
|
||||
*/
|
||||
AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder);
|
||||
@Deprecated(since = "0.7.0", forRemoval = true)
|
||||
default AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder) {
|
||||
throw new UnsupportedOperationException("The method has not been implemented.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为给定的 {@link BaseAbilityBot} 对象创建扩展.
|
||||
*
|
||||
* <p> 如扩展无使用 {@link org.telegram.abilitybots.api.db.DBContext} 的话,
|
||||
* 也可以返回扩展单例, 因为 AbilityBot 本身并不禁止多个机器人共用一个扩展对象
|
||||
* (AbilityBot 只是调用了扩展中的方法来创建 Ability 对象).
|
||||
*
|
||||
* @param bot 机器人对象.
|
||||
* @param shareDataFolder ScalaBot App 为扩展提供的共享数据目录.
|
||||
* <p>路径格式为:
|
||||
* <pre> $DATA_ROOT/data/extensions/{GroupId}/{ArtifactId}</pre>
|
||||
* <b>同一个扩展包的 Factory</b> 接收到的共享数据目录<b>都是一样的</b>,
|
||||
* 建议将数据存储在数据目录中, 便于数据的存储管理.
|
||||
* @param options 创建扩展时可用的参数.
|
||||
* @return 返回为该 Bot 对象创建的扩展对象, 如果不希望为该机器人提供扩展, 可返回 {@code null}.
|
||||
* @since 0.7.0
|
||||
*/
|
||||
default AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder, BotExtensionCreateOptions options) {
|
||||
return createExtensionInstance(bot, shareDataFolder);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -24,7 +24,9 @@ public class AbilityBots {
|
||||
* @return 返回 AbilityBot 的账户 Id.
|
||||
* @throws IllegalArgumentException 当 AbilityBot 的 botToken 格式错误时抛出该异常.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static long getBotAccountId(BaseAbilityBot bot) {
|
||||
// 根据文档说明, 弃用仅针对重写方法, 使用该方法并无大碍.
|
||||
String botToken = bot.getBotToken();
|
||||
Matcher matcher = botTokenPattern.matcher(botToken);
|
||||
if (!matcher.matches()) {
|
||||
|
@ -16,8 +16,8 @@ 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);
|
||||
public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false, false, false);
|
||||
public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false, false, false);
|
||||
|
||||
static Update mockFullUpdate(BaseAbilityBot bot, User user, String args) {
|
||||
bot.users().put(USER.getId(), USER);
|
||||
@ -56,8 +56,8 @@ public class AbilityBotsTest {
|
||||
|
||||
@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);
|
||||
User userA = new User(10001L, "first", false, "last", "username", null, false, false, false, false, false);
|
||||
User userB = new User(10101L, "first", false, "last", "username", null, false, false, false, false, false);
|
||||
SilentSender silent = mock(SilentSender.class);
|
||||
BaseAbilityBot bot = new TestingAbilityBot("", "", silent);
|
||||
bot.onRegister();
|
||||
@ -94,6 +94,7 @@ public class AbilityBotsTest {
|
||||
this.silent = silentSender;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public Ability setReply() {
|
||||
return Ability.builder()
|
||||
.name("set_reply")
|
||||
|
13
scalabot-meta/README.md
Normal file
13
scalabot-meta/README.md
Normal file
@ -0,0 +1,13 @@
|
||||
# scalabot-meta
|
||||
|
||||
本模块用于将 ScalaBot 的一些配置相关内容发布出去,以便于其他项目使用。
|
||||
|
||||
主要是配置类和相应的 Gson 序列化器(如果有,或者必要)。
|
||||
|
||||
## 关于序列化器
|
||||
|
||||
强烈建议使用序列化器!由于 Kotlin 与 Gson 之间的一些兼容性问题
|
||||
(参见[本提交](https://github.com/LamGC/ScalaBot/commit/084280564af58d1af22db5b57c67577d93bd820e)),
|
||||
如果直接让 Gson 解析 Kotlin Data 类,将会出现一些潜在的问题(比如无法使用默认值)。
|
||||
部分序列化器也可以帮助检查字段值是否合法,以防止因字段值不正确导致出现更多的问题
|
||||
(例如 BotAccount 中,如果 `token` 的格式有误,那么获取 `id` 时将引发 `NumberFormatException` 异常)。
|
196
scalabot-meta/api/scalabot-meta.api
Normal file
196
scalabot-meta/api/scalabot-meta.api
Normal file
@ -0,0 +1,196 @@
|
||||
public final class net/lamgc/scalabot/config/AppConfig {
|
||||
public fun <init> ()V
|
||||
public fun <init> (Lnet/lamgc/scalabot/config/ProxyConfig;Lnet/lamgc/scalabot/config/MetricsConfig;Ljava/util/List;Ljava/lang/String;)V
|
||||
public synthetic fun <init> (Lnet/lamgc/scalabot/config/ProxyConfig;Lnet/lamgc/scalabot/config/MetricsConfig;Ljava/util/List;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||
public final fun component1 ()Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public final fun component2 ()Lnet/lamgc/scalabot/config/MetricsConfig;
|
||||
public final fun component3 ()Ljava/util/List;
|
||||
public final fun component4 ()Ljava/lang/String;
|
||||
public final fun copy (Lnet/lamgc/scalabot/config/ProxyConfig;Lnet/lamgc/scalabot/config/MetricsConfig;Ljava/util/List;Ljava/lang/String;)Lnet/lamgc/scalabot/config/AppConfig;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/AppConfig;Lnet/lamgc/scalabot/config/ProxyConfig;Lnet/lamgc/scalabot/config/MetricsConfig;Ljava/util/List;Ljava/lang/String;ILjava/lang/Object;)Lnet/lamgc/scalabot/config/AppConfig;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getMavenLocalRepository ()Ljava/lang/String;
|
||||
public final fun getMavenRepositories ()Ljava/util/List;
|
||||
public final fun getMetrics ()Lnet/lamgc/scalabot/config/MetricsConfig;
|
||||
public final fun getProxy ()Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/BotAccount {
|
||||
public fun <init> (Ljava/lang/String;Ljava/lang/String;J)V
|
||||
public final fun component1 ()Ljava/lang/String;
|
||||
public final fun component2 ()Ljava/lang/String;
|
||||
public final fun component3 ()J
|
||||
public final fun copy (Ljava/lang/String;Ljava/lang/String;J)Lnet/lamgc/scalabot/config/BotAccount;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/BotAccount;Ljava/lang/String;Ljava/lang/String;JILjava/lang/Object;)Lnet/lamgc/scalabot/config/BotAccount;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getCreatorId ()J
|
||||
public final fun getId ()J
|
||||
public final fun getName ()Ljava/lang/String;
|
||||
public final fun getToken ()Ljava/lang/String;
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/BotConfig {
|
||||
public fun <init> (ZLnet/lamgc/scalabot/config/BotAccount;ZZLjava/util/Set;Lnet/lamgc/scalabot/config/ProxyConfig;Ljava/lang/String;)V
|
||||
public synthetic fun <init> (ZLnet/lamgc/scalabot/config/BotAccount;ZZLjava/util/Set;Lnet/lamgc/scalabot/config/ProxyConfig;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||
public final fun component1 ()Z
|
||||
public final fun component2 ()Lnet/lamgc/scalabot/config/BotAccount;
|
||||
public final fun component3 ()Z
|
||||
public final fun component4 ()Z
|
||||
public final fun component5 ()Ljava/util/Set;
|
||||
public final fun component6 ()Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public final fun component7 ()Ljava/lang/String;
|
||||
public final fun copy (ZLnet/lamgc/scalabot/config/BotAccount;ZZLjava/util/Set;Lnet/lamgc/scalabot/config/ProxyConfig;Ljava/lang/String;)Lnet/lamgc/scalabot/config/BotConfig;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/BotConfig;ZLnet/lamgc/scalabot/config/BotAccount;ZZLjava/util/Set;Lnet/lamgc/scalabot/config/ProxyConfig;Ljava/lang/String;ILjava/lang/Object;)Lnet/lamgc/scalabot/config/BotConfig;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getAccount ()Lnet/lamgc/scalabot/config/BotAccount;
|
||||
public final fun getAutoUpdateCommandList ()Z
|
||||
public final fun getBaseApiUrl ()Ljava/lang/String;
|
||||
public final fun getDisableBuiltInAbility ()Z
|
||||
public final fun getEnabled ()Z
|
||||
public final fun getExtensions ()Ljava/util/Set;
|
||||
public final fun getProxy ()Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/MavenRepositoryConfig {
|
||||
public fun <init> (Ljava/lang/String;Ljava/net/URL;Lorg/eclipse/aether/repository/Proxy;Ljava/lang/String;ZZLorg/eclipse/aether/repository/Authentication;)V
|
||||
public synthetic fun <init> (Ljava/lang/String;Ljava/net/URL;Lorg/eclipse/aether/repository/Proxy;Ljava/lang/String;ZZLorg/eclipse/aether/repository/Authentication;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||
public final fun component1 ()Ljava/lang/String;
|
||||
public final fun component2 ()Ljava/net/URL;
|
||||
public final fun component3 ()Lorg/eclipse/aether/repository/Proxy;
|
||||
public final fun component4 ()Ljava/lang/String;
|
||||
public final fun component5 ()Z
|
||||
public final fun component6 ()Z
|
||||
public final fun component7 ()Lorg/eclipse/aether/repository/Authentication;
|
||||
public final fun copy (Ljava/lang/String;Ljava/net/URL;Lorg/eclipse/aether/repository/Proxy;Ljava/lang/String;ZZLorg/eclipse/aether/repository/Authentication;)Lnet/lamgc/scalabot/config/MavenRepositoryConfig;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/MavenRepositoryConfig;Ljava/lang/String;Ljava/net/URL;Lorg/eclipse/aether/repository/Proxy;Ljava/lang/String;ZZLorg/eclipse/aether/repository/Authentication;ILjava/lang/Object;)Lnet/lamgc/scalabot/config/MavenRepositoryConfig;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getAuthentication ()Lorg/eclipse/aether/repository/Authentication;
|
||||
public final fun getEnableReleases ()Z
|
||||
public final fun getEnableSnapshots ()Z
|
||||
public final fun getId ()Ljava/lang/String;
|
||||
public final fun getLayout ()Ljava/lang/String;
|
||||
public final fun getProxy ()Lorg/eclipse/aether/repository/Proxy;
|
||||
public final fun getUrl ()Ljava/net/URL;
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/MetricsConfig {
|
||||
public fun <init> ()V
|
||||
public fun <init> (ZILjava/lang/String;Lnet/lamgc/scalabot/config/UsernameAuthenticator;)V
|
||||
public synthetic fun <init> (ZILjava/lang/String;Lnet/lamgc/scalabot/config/UsernameAuthenticator;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||
public final fun component1 ()Z
|
||||
public final fun component2 ()I
|
||||
public final fun component3 ()Ljava/lang/String;
|
||||
public final fun component4 ()Lnet/lamgc/scalabot/config/UsernameAuthenticator;
|
||||
public final fun copy (ZILjava/lang/String;Lnet/lamgc/scalabot/config/UsernameAuthenticator;)Lnet/lamgc/scalabot/config/MetricsConfig;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/MetricsConfig;ZILjava/lang/String;Lnet/lamgc/scalabot/config/UsernameAuthenticator;ILjava/lang/Object;)Lnet/lamgc/scalabot/config/MetricsConfig;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getAuthenticator ()Lnet/lamgc/scalabot/config/UsernameAuthenticator;
|
||||
public final fun getBindAddress ()Ljava/lang/String;
|
||||
public final fun getEnable ()Z
|
||||
public final fun getPort ()I
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/ProxyConfig {
|
||||
public fun <init> ()V
|
||||
public fun <init> (Lnet/lamgc/scalabot/config/ProxyType;Ljava/lang/String;I)V
|
||||
public synthetic fun <init> (Lnet/lamgc/scalabot/config/ProxyType;Ljava/lang/String;IILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||
public final fun component1 ()Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public final fun component2 ()Ljava/lang/String;
|
||||
public final fun component3 ()I
|
||||
public final fun copy (Lnet/lamgc/scalabot/config/ProxyType;Ljava/lang/String;I)Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public static synthetic fun copy$default (Lnet/lamgc/scalabot/config/ProxyConfig;Lnet/lamgc/scalabot/config/ProxyType;Ljava/lang/String;IILjava/lang/Object;)Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public final fun getHost ()Ljava/lang/String;
|
||||
public final fun getPort ()I
|
||||
public final fun getType ()Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public fun hashCode ()I
|
||||
public fun toString ()Ljava/lang/String;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/ProxyType : java/lang/Enum {
|
||||
public static final field HTTP Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static final field HTTPS Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static final field NO_PROXY Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static final field SOCKS4 Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static final field SOCKS5 Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static fun getEntries ()Lkotlin/enums/EnumEntries;
|
||||
public static fun valueOf (Ljava/lang/String;)Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public static fun values ()[Lnet/lamgc/scalabot/config/ProxyType;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/UsernameAuthenticator : com/sun/net/httpserver/BasicAuthenticator {
|
||||
public fun <init> (Ljava/lang/String;Ljava/lang/String;)V
|
||||
public fun checkCredentials (Ljava/lang/String;Ljava/lang/String;)Z
|
||||
public fun equals (Ljava/lang/Object;)Z
|
||||
public fun hashCode ()I
|
||||
public final fun toJsonObject ()Lcom/google/gson/JsonObject;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/ArtifactSerializer : com/google/gson/JsonDeserializer, com/google/gson/JsonSerializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/ArtifactSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lorg/eclipse/aether/artifact/Artifact;
|
||||
public synthetic fun serialize (Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
public fun serialize (Lorg/eclipse/aether/artifact/Artifact;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/AuthenticationSerializer : com/google/gson/JsonDeserializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/AuthenticationSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lorg/eclipse/aether/repository/Authentication;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/BotAccountSerializer : com/google/gson/JsonDeserializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/BotAccountSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/BotAccount;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/BotConfigSerializer : com/google/gson/JsonDeserializer, com/google/gson/JsonSerializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/BotConfigSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/BotConfig;
|
||||
public synthetic fun serialize (Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
public fun serialize (Lnet/lamgc/scalabot/config/BotConfig;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/MavenRepositoryConfigSerializer : com/google/gson/JsonDeserializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/MavenRepositoryConfigSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/MavenRepositoryConfig;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/ProxyConfigSerializer : com/google/gson/JsonDeserializer, com/google/gson/JsonSerializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/ProxyConfigSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/ProxyConfig;
|
||||
public synthetic fun serialize (Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
public fun serialize (Lnet/lamgc/scalabot/config/ProxyConfig;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/ProxyTypeSerializer : com/google/gson/JsonDeserializer, com/google/gson/JsonSerializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/ProxyTypeSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/ProxyType;
|
||||
public synthetic fun serialize (Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
public fun serialize (Lnet/lamgc/scalabot/config/ProxyType;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
}
|
||||
|
||||
public final class net/lamgc/scalabot/config/serializer/UsernameAuthenticatorSerializer : com/google/gson/JsonDeserializer, com/google/gson/JsonSerializer {
|
||||
public static final field INSTANCE Lnet/lamgc/scalabot/config/serializer/UsernameAuthenticatorSerializer;
|
||||
public synthetic fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Ljava/lang/Object;
|
||||
public fun deserialize (Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/lamgc/scalabot/config/UsernameAuthenticator;
|
||||
public synthetic fun serialize (Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
public fun serialize (Lnet/lamgc/scalabot/config/UsernameAuthenticator;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;
|
||||
}
|
||||
|
@ -1,26 +1,27 @@
|
||||
plugins {
|
||||
kotlin("jvm")
|
||||
id("org.jetbrains.kotlinx.kover")
|
||||
id("org.jetbrains.dokka") version "1.7.0"
|
||||
id("org.jetbrains.dokka") version "1.9.10"
|
||||
`maven-publish`
|
||||
signing
|
||||
id("org.jetbrains.kotlinx.binary-compatibility-validator")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
val aetherVersion = "1.1.0"
|
||||
implementation("org.eclipse.aether:aether-api:$aetherVersion")
|
||||
api("org.eclipse.aether:aether-api:$aetherVersion")
|
||||
implementation("org.eclipse.aether:aether-util:$aetherVersion")
|
||||
|
||||
implementation("org.telegram:telegrambots-meta:6.0.1")
|
||||
implementation("org.telegram:telegrambots-meta:6.9.7.1")
|
||||
|
||||
implementation("com.google.code.gson:gson:2.9.0")
|
||||
api("com.google.code.gson:gson:2.10.1")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
testImplementation("io.mockk:mockk:1.12.4")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.2")
|
||||
testImplementation("io.mockk:mockk:1.13.9")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.1")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.1")
|
||||
|
||||
dokkaHtmlPlugin("org.jetbrains.dokka:javadoc-plugin:1.7.0")
|
||||
dokkaHtmlPlugin("org.jetbrains.dokka:javadoc-plugin:1.9.10")
|
||||
}
|
||||
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
|
||||
@ -36,6 +37,11 @@ java {
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
tasks.withType<AbstractArchiveTask>().configureEach {
|
||||
isPreserveFileTimestamps = false
|
||||
isReproducibleFileOrder = true
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
@ -46,19 +52,21 @@ val javadocJar = tasks.named<Jar>("javadocJar") {
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
if (project.version.toString().endsWith("-SNAPSHOT", ignoreCase = true)) {
|
||||
maven("https://nexus.kuku.me/repository/maven-snapshots/") {
|
||||
maven("https://git.lamgc.me/api/packages/LamGC/maven") {
|
||||
credentials {
|
||||
username = project.properties["repo.credentials.private.username"].toString()
|
||||
password = project.properties["repo.credentials.private.password"].toString()
|
||||
username = project.properties["repo.credentials.self-git.username"].toString()
|
||||
password = project.properties["repo.credentials.self-git.password"].toString()
|
||||
}
|
||||
}
|
||||
val kukuRepoUrl = if (project.version.toString().endsWith("-SNAPSHOT", ignoreCase = true)) {
|
||||
"https://nexus.kuku.me/repository/maven-snapshots/"
|
||||
} else {
|
||||
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()
|
||||
"https://nexus.kuku.me/repository/maven-releases/"
|
||||
}
|
||||
maven(kukuRepoUrl) {
|
||||
credentials {
|
||||
username = project.properties["repo.credentials.kuku-repo.username"].toString()
|
||||
password = project.properties["repo.credentials.kuku-repo.password"].toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -28,6 +28,13 @@ data class BotAccount(
|
||||
|
||||
/**
|
||||
* 机器人配置.
|
||||
*
|
||||
* 使用 Gson 解析时, 请添加以下类型适配器:
|
||||
* - [net.lamgc.scalabot.config.serializer.ProxyTypeSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.BotConfigSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.BotAccountSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.ArtifactSerializer]
|
||||
*
|
||||
* @property enabled 是否启用机器人.
|
||||
* @property account 机器人帐号信息, 用于访问 API.
|
||||
* @property disableBuiltInAbility 是否禁用 AbilityBot 自带命令.
|
||||
@ -72,8 +79,16 @@ enum class ProxyType {
|
||||
data class ProxyConfig(
|
||||
val type: ProxyType = ProxyType.NO_PROXY,
|
||||
val host: String = "127.0.0.1",
|
||||
val port: Int = 1080
|
||||
)
|
||||
val port: Int = 1080,
|
||||
) {
|
||||
override fun toString(): String {
|
||||
return if (type != ProxyType.NO_PROXY) {
|
||||
"$type://$host:$port"
|
||||
} else {
|
||||
"NO_PROXY"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ScalaBot 的运行指标公开配置.
|
||||
@ -118,6 +133,13 @@ data class MavenRepositoryConfig(
|
||||
* ScalaBot App 配置.
|
||||
*
|
||||
* App 配置信息与 BotConfig 分开, 分别存储在各自单独的文件中.
|
||||
*
|
||||
* 使用 Gson 解析时, 请添加以下类型适配器:
|
||||
* - [net.lamgc.scalabot.config.serializer.ProxyTypeSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.MavenRepositoryConfigSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.AuthenticationSerializer]
|
||||
* - [net.lamgc.scalabot.config.serializer.UsernameAuthenticatorSerializer]
|
||||
*
|
||||
* @property proxy Telegram API 代理配置.
|
||||
* @property metrics 运行指标数据配置. 可通过时序数据库记录运行数据.
|
||||
* @property mavenRepositories Maven 远端仓库配置.
|
||||
|
@ -3,6 +3,7 @@ package net.lamgc.scalabot.config.serializer
|
||||
import com.google.gson.*
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import net.lamgc.scalabot.config.*
|
||||
import net.lamgc.scalabot.config.serializer.SerializeUtils.getPrimitiveValueOrThrow
|
||||
import org.eclipse.aether.artifact.AbstractArtifact
|
||||
import org.eclipse.aether.artifact.Artifact
|
||||
import org.eclipse.aether.artifact.DefaultArtifact
|
||||
@ -12,6 +13,7 @@ import org.eclipse.aether.util.repository.AuthenticationBuilder
|
||||
import java.lang.reflect.Type
|
||||
import java.net.MalformedURLException
|
||||
import java.net.URL
|
||||
import java.util.regex.Pattern
|
||||
|
||||
object ProxyTypeSerializer : JsonDeserializer<ProxyType>,
|
||||
JsonSerializer<ProxyType> {
|
||||
@ -81,8 +83,8 @@ object AuthenticationSerializer : JsonDeserializer<Authentication> {
|
||||
if (json !is JsonObject) {
|
||||
throw JsonParseException("Unsupported JSON type.")
|
||||
}
|
||||
val username = SerializerUtils.checkJsonKey(json, "username")
|
||||
val password = SerializerUtils.checkJsonKey(json, "password")
|
||||
val username = json.getPrimitiveValueOrThrow("username").asString
|
||||
val password = json.getPrimitiveValueOrThrow("password").asString
|
||||
val builder = AuthenticationBuilder()
|
||||
builder.addUsername(username)
|
||||
builder.addPassword(password)
|
||||
@ -91,14 +93,14 @@ object AuthenticationSerializer : JsonDeserializer<Authentication> {
|
||||
|
||||
}
|
||||
|
||||
private object SerializerUtils {
|
||||
fun checkJsonKey(json: JsonObject, key: String): String {
|
||||
if (!json.has(key)) {
|
||||
throw JsonParseException("Required field does not exist: $key")
|
||||
} else if (!json.get(key).isJsonPrimitive) {
|
||||
throw JsonParseException("Wrong field `$key` type: ${json.get(key)::class.java}")
|
||||
internal object SerializeUtils {
|
||||
|
||||
fun JsonObject.getPrimitiveValueOrThrow(fieldName: String): JsonPrimitive {
|
||||
val value = get(fieldName) ?: throw JsonParseException("Missing `$fieldName` field.")
|
||||
if (value !is JsonPrimitive) {
|
||||
throw JsonParseException("Invalid `account` field type.")
|
||||
}
|
||||
return json.get(key).asString
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
@ -114,7 +116,7 @@ object MavenRepositoryConfigSerializer
|
||||
is JsonObject -> {
|
||||
MavenRepositoryConfig(
|
||||
id = json.get("id")?.asString,
|
||||
url = URL(SerializerUtils.checkJsonKey(json, "url")),
|
||||
url = URL(json.getPrimitiveValueOrThrow("url").asString),
|
||||
proxy = if (json.has("proxy"))
|
||||
context.deserialize<Proxy>(
|
||||
json.get("proxy"), Proxy::class.java
|
||||
@ -260,3 +262,39 @@ object BotConfigSerializer : JsonSerializer<BotConfig>, JsonDeserializer<BotConf
|
||||
}
|
||||
}
|
||||
|
||||
object BotAccountSerializer : JsonDeserializer<BotAccount> {
|
||||
|
||||
private val tokenCheckRegex = Pattern.compile("\\d+:[a-zA-Z\\d_-]{35}")
|
||||
|
||||
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): BotAccount {
|
||||
if (json == null || json.isJsonNull) {
|
||||
throw JsonParseException("Missing `account` field.")
|
||||
} else if (!json.isJsonObject) {
|
||||
throw JsonParseException("Invalid `account` field type.")
|
||||
}
|
||||
val jsonObj = json.asJsonObject
|
||||
|
||||
val name = jsonObj.getPrimitiveValueOrThrow("name").asString
|
||||
val token = jsonObj.getPrimitiveValueOrThrow("token").asString.let {
|
||||
if (it.isEmpty()) {
|
||||
throw JsonParseException("`token` cannot be empty.")
|
||||
} else if (!tokenCheckRegex.matcher(it).matches()) {
|
||||
throw JsonParseException("`token` is invalid.")
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}
|
||||
val creatorId = try {
|
||||
jsonObj.getPrimitiveValueOrThrow("creatorId").asLong
|
||||
} catch (e: NumberFormatException) {
|
||||
throw JsonParseException("`creatorId` must be a number.")
|
||||
}.apply {
|
||||
if (this < 0) {
|
||||
throw JsonParseException("`creatorId` must be a positive number.")
|
||||
}
|
||||
}
|
||||
|
||||
return BotAccount(name, token, creatorId)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -219,6 +219,12 @@ internal class ProxyConfigTest {
|
||||
assertEquals(8080, actualConfig.port)
|
||||
assertEquals(ProxyType.HTTP, actualConfig.type)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `toString test`() {
|
||||
assertEquals("NO_PROXY", ProxyConfig(ProxyType.NO_PROXY).toString())
|
||||
assertEquals("HTTP://example.org:1008", ProxyConfig(ProxyType.HTTP, "example.org", 1008).toString())
|
||||
}
|
||||
}
|
||||
|
||||
internal class MetricsConfigTest {
|
||||
|
@ -5,6 +5,7 @@ import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.verify
|
||||
import net.lamgc.scalabot.config.*
|
||||
import net.lamgc.scalabot.config.serializer.SerializeUtils.getPrimitiveValueOrThrow
|
||||
import org.eclipse.aether.artifact.Artifact
|
||||
import org.eclipse.aether.artifact.DefaultArtifact
|
||||
import org.eclipse.aether.repository.Authentication
|
||||
@ -12,54 +13,39 @@ 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 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.config.serializer.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
|
||||
}
|
||||
}
|
||||
internal class SerializeUtilsTest {
|
||||
|
||||
@Test
|
||||
fun `Json key checker test`() {
|
||||
fun `getPrimitiveValueOrThrow 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")
|
||||
JsonObject().getPrimitiveValueOrThrow("NOT_EXIST_KEY")
|
||||
}
|
||||
|
||||
val expectKey = "TEST"
|
||||
val expectString = "testString"
|
||||
val json = JsonObject().apply { addProperty(expectKey, expectString) }
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
JsonObject().apply {
|
||||
add("testKey", JsonArray())
|
||||
}.getPrimitiveValueOrThrow("testKey")
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
JsonObject().apply {
|
||||
add("testKey", JsonObject())
|
||||
}.getPrimitiveValueOrThrow("testKey")
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
JsonObject().apply {
|
||||
add("testKey", JsonNull.INSTANCE)
|
||||
}.getPrimitiveValueOrThrow("testKey")
|
||||
}
|
||||
|
||||
assertEquals(expectString, invoke(json, expectKey))
|
||||
val expectKey = "STRING_KEY"
|
||||
val expectValue = JsonPrimitive("A STRING")
|
||||
assertEquals(expectValue, JsonObject()
|
||||
.apply { add(expectKey, expectValue) }
|
||||
.getPrimitiveValueOrThrow(expectKey))
|
||||
}
|
||||
}
|
||||
|
||||
@ -706,3 +692,161 @@ internal class UsernameAuthenticatorSerializerTest {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal class BotAccountSerializerTest {
|
||||
|
||||
private val expectToken = "123456789:AAHErDroUTznQsOd_oZPJ6cQEj4Z5mGHO10"
|
||||
private val gson = GsonBuilder()
|
||||
.registerTypeAdapter(BotAccount::class.java, BotAccountSerializer)
|
||||
.create()
|
||||
|
||||
@Test
|
||||
fun `Invalid json type check test`() {
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(null, null, null)
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonNull.INSTANCE, null, null)
|
||||
}
|
||||
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonPrimitive("A STRING"), null, null)
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonArray(), null, null)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Field missing test`() {
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonObject(), null, null)
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonObject().apply {
|
||||
addProperty("token", expectToken)
|
||||
addProperty("creatorId", 1)
|
||||
}, null, null)
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("creatorId", 1)
|
||||
}, null, null)
|
||||
}
|
||||
assertThrows(JsonParseException::class.java) {
|
||||
BotAccountSerializer.deserialize(JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("token", expectToken)
|
||||
}, null, null)
|
||||
}
|
||||
|
||||
val account = BotAccountSerializer.deserialize(JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("token", expectToken)
|
||||
addProperty("creatorId", 1)
|
||||
}, null, null)
|
||||
assertNotNull(account)
|
||||
assertEquals("testUser", account.name)
|
||||
assertEquals(expectToken, account.token)
|
||||
assertEquals(1, account.creatorId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `'token' check test`() {
|
||||
val jsonObject = JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("token", expectToken)
|
||||
addProperty("creatorId", 123456789123456789)
|
||||
}
|
||||
|
||||
val looksGoodAccount = BotAccountSerializer.deserialize(jsonObject, null, null)
|
||||
|
||||
assertNotNull(looksGoodAccount)
|
||||
assertEquals("testUser", looksGoodAccount.name)
|
||||
assertEquals(expectToken, looksGoodAccount.token)
|
||||
assertEquals(123456789123456789, looksGoodAccount.creatorId)
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("token", "")
|
||||
}, null, null)
|
||||
fail("Token 为空,但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`token` cannot be empty.", e.message)
|
||||
}
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("token", "abcdefghijklmnopqrstuvwxyz")
|
||||
}, null, null)
|
||||
fail("Token 格式错误(基本格式错误),但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`token` is invalid.", e.message)
|
||||
}
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("token", "abcdefgh:ijklmnopqrstuvwxyz-1234567890_abcde")
|
||||
}, null, null)
|
||||
fail("Token 格式错误(ID 不为数字),但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`token` is invalid.", e.message)
|
||||
}
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("token", "0123456789:ijklmnopqrstu-vwxyz_123456")
|
||||
}, null, null)
|
||||
fail("Token 格式错误(授权令牌长度错误),但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`token` is invalid.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `'creatorId' check test`() {
|
||||
val jsonObject = JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("token", expectToken)
|
||||
addProperty("creatorId", 1)
|
||||
}
|
||||
|
||||
val looksGoodAccount = gson.fromJson(jsonObject, BotAccount::class.java)
|
||||
assertEquals(1, looksGoodAccount.creatorId)
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("creatorId", "A STRING")
|
||||
}, null, null)
|
||||
fail("creatorId 不是一个数字,但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`creatorId` must be a number.", e.message)
|
||||
}
|
||||
|
||||
try {
|
||||
BotAccountSerializer.deserialize(jsonObject.deepCopy().apply {
|
||||
addProperty("creatorId", -1)
|
||||
}, null, null)
|
||||
fail("creatorId 不能为负数,但是没有抛出异常。")
|
||||
} catch (e: JsonParseException) {
|
||||
assertEquals("`creatorId` must be a positive number.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `json deserialize test`() {
|
||||
val jsonObject = JsonObject().apply {
|
||||
addProperty("name", "testUser")
|
||||
addProperty("token", expectToken)
|
||||
addProperty("creatorId", 1)
|
||||
}
|
||||
|
||||
val looksGoodAccount = gson.fromJson(jsonObject, BotAccount::class.java)
|
||||
|
||||
assertNotNull(looksGoodAccount)
|
||||
assertEquals("testUser", looksGoodAccount.name)
|
||||
assertEquals(expectToken, looksGoodAccount.token)
|
||||
assertEquals(1, looksGoodAccount.creatorId)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user