Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

支持在配置文件读取的时候使用 SerializersModule #713

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,23 @@ public open class SimbotSpringBootBotAutoRegisterBuildConfigure {
if (it.isFile) {
kotlin.runCatching {
botVerifyInfo =
it.file.takeIf { f -> f.exists() }?.toPath()?.toBotVerifyInfo(decoderFactory)
?: return@runCatching
it.file.takeIf { f -> f.exists() }?.toPath()?.let { path ->
if (decoderFactory is StandardBotVerifyInfoDecoderFactory) {
path.toBotVerifyInfo(decoderFactory.create(application.environment.serializersModule))
} else {
path.toBotVerifyInfo(decoderFactory)
}
} ?: return@runCatching
}.getOrNull()
}

botVerifyInfo ?: it.url.toBotVerifyInfo(decoderFactory)
botVerifyInfo ?: it.url.let { url ->
if (decoderFactory is StandardBotVerifyInfoDecoderFactory) {
url.toBotVerifyInfo(decoderFactory.create(application.environment.serializersModule))
} else {
url.toBotVerifyInfo(decoderFactory)
}
}
}.toList()

if (botConfigResources.isNotEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,14 @@ public open class SimbotSpringBootComponentAutoInstallBuildConfigure {
val factories0 = factories ?: emptyList()
return SimbotSpringBootApplicationBuildConfigure { configuration ->
logger.info("The number of Installable Event Provider Factories is {}", factories0.size)
if (factories0.isEmpty()) {
val classLoader = configuration.classLoader
logger.info("Install components by [installAllComponents] via classLoader {}", classLoader)
installAllComponents(classLoader)
} else {
logger.debug("Install components by: {}", factories)
factories0.forEach {
install(it)
}

val classLoader = configuration.classLoader
logger.info("Install components by [installAllComponents] via classLoader {}", classLoader)
installAllComponents(classLoader)

logger.debug("Install components by: {}", factories)
factories0.forEach {
install(it)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@

package love.forli.test

import love.forte.simboot.annotation.AnnotationEventFilterFactory
import love.forte.simboot.annotation.Filter
import love.forte.simboot.annotation.Filters
import love.forte.simboot.annotation.Listener
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import love.forte.simboot.spring.autoconfigure.EnableSimbot
import love.forte.simbot.MutableAttributeMap
import love.forte.simbot.event.*
import org.springframework.beans.factory.annotation.Autowired
import love.forte.simbot.Attribute
import love.forte.simbot.ComponentFactory
import love.forte.simbot.application.Application
import org.springframework.beans.factory.getBean
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.stereotype.Component
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration


@EnableSimbot
Expand All @@ -32,41 +34,52 @@ open class SpringBootApp


fun main(vararg args: String) {
runApplication<SpringBootApp>(args = args)
}
val app = runApplication<SpringBootApp>(args = args)

val simbotApp = app.getBean<Application>()

@Component
open class MyListener {
println(simbotApp.environment.components)

@Filter(by = MyFilterFactory::class)
@Listener
fun FriendMessageEvent.listen(){}
println(simbotApp.environment.serializersModule)

// TODO Json decode BUG
println(Json {
isLenient = true
ignoreUnknownKeys = true
serializersModule = simbotApp.environment.serializersModule
}.decodeFromString<Root>("""{"config": {"a": 1}}"""))
}

@Component
open class MyInterceptor : EventProcessingInterceptor {
override suspend fun intercept(context: EventProcessingInterceptor.Context): EventProcessingResult {
return context.proceed()
}
@Configuration
open class CompConfig {

@Bean
open fun myCp() = MyComponent
}

@Component
open class MyFilterFactory @Autowired constructor(private val filter: MyEventFilter) : AnnotationEventFilterFactory {
override fun resolveFilter(
listener: EventListener,
listenerAttributes: MutableAttributeMap,
filter: Filter,
filters: Filters
): EventFilter {
return this.filter
}
@Serializable
data class Root(val config: Config)

@Serializable
sealed class Config {
@Serializable
@SerialName("def")
class Default : Config()

@Serializable
@SerialName("value")
data class Value(val value: Int) : Config()
}

@Component
open class MyEventFilter : EventFilter {
override suspend fun test(context: EventListenerProcessingContext): Boolean {
println("FILTER!")
return true
class MyComponent : love.forte.simbot.Component {
override val id: String = "simbot.test"
override val componentSerializersModule: SerializersModule = SerializersModule {
polymorphicDefaultDeserializer(Config::class) { Config.Default.serializer() }
}

companion object Factory : ComponentFactory<MyComponent, Unit> {
override val key: Attribute<MyComponent> = Attribute.Companion.of("simbot.test")

override suspend fun create(configurator: Unit.() -> Unit): MyComponent = MyComponent()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -201,15 +201,15 @@ public open class BootApplicationConfiguration : SimpleApplicationConfiguration(
}

@OptIn(ExperimentalSimbotApi::class, ExperimentalSerializationApi::class)
internal fun botVerifyDecodersOrDefaultStandards(): List<BotVerifyInfoDecoderFactoryWithConfiguration> {
internal fun botVerifyDecodersOrDefaultStandards(environment: BootEnvironment): List<BotVerifyInfoDecoderFactoryWithConfiguration> {
if (botVerifyInfoDecoderFactories.isNotEmpty()) {
return botVerifyInfoDecoderFactories.map { (k, v) ->
BotVerifyInfoDecoderFactoryWithConfiguration(k, v)
}
}

return StandardBotVerifyInfoDecoderFactory.supportDecoderFactories(logger, classLoader)
.map { BotVerifyInfoDecoderFactoryWithConfiguration(it) { it.create() } }
.map { BotVerifyInfoDecoderFactoryWithConfiguration(it) { it.create(environment.serializersModule) } }
}

/**
Expand Down Expand Up @@ -543,7 +543,7 @@ private class BootApplicationBuilderImpl : BootApplicationBuilder, BaseStandardA
logger.debug("Resolving bot verify infos and bot verify decoders...")
// scan and auto register bot

val botVerifyDecoderFactories = configuration.botVerifyDecodersOrDefaultStandards()
val botVerifyDecoderFactories = configuration.botVerifyDecodersOrDefaultStandards(environment)
if (logger.isDebugEnabled) {
logger.debug("Using bot verify info decoder factories: {}", botVerifyDecoderFactories.map { it.factory })
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import com.charleskorn.kaml.YamlConfiguration
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonBuilder
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.plus
import kotlinx.serialization.properties.Properties
import love.forte.simbot.ExperimentalSimbotApi
import love.forte.simbot.logger.LoggerFactory
Expand Down Expand Up @@ -171,6 +173,18 @@ public interface BotVerifyInfoDecoder : DeserializableResourceDecoder {
public sealed class StandardBotVerifyInfoDecoderFactory<C : Any, D : BotVerifyInfoDecoder> :
BotVerifyInfoDecoderFactory<C, D> {

abstract override fun create(configurator: C.() -> Unit): D

/**
* 提供一个 [serializersModule] 来构建目标序列化器。
*
* @since 3.2.0
*/
public open fun create(serializersModule: SerializersModule, configurator: C.() -> Unit = {}) : D =
// 为了兼容旧版本,此函数必须提供默认实现
// 字类需要重新此函数
create(configurator)

public companion object {
private val logger: Logger = LoggerFactory.getLogger("love.forte.simbot.bot.StandardBotVerifyInfoDecoderFactory")

Expand Down Expand Up @@ -399,6 +413,18 @@ public class JsonBotVerifyInfoDecoder(override val format: Json) :
})
}

override fun create(
serializersModule: SerializersModule,
configurator: JsonBuilder.() -> Unit
): JsonBotVerifyInfoDecoder {
return JsonBotVerifyInfoDecoder(Json {
this.serializersModule = serializersModule
isLenient = true
ignoreUnknownKeys = true
configurator()
})
}

public fun create(decoder: Json): JsonBotVerifyInfoDecoder {
return JsonBotVerifyInfoDecoder(decoder)
}
Expand Down Expand Up @@ -435,9 +461,24 @@ public class YamlBotVerifyInfoDecoder(override val format: Yaml) :
)
}

override fun create(
serializersModule: SerializersModule,
configurator: YamlBotVerifyInfoDecoderConfiguration.() -> Unit
): YamlBotVerifyInfoDecoder {
val configuration = YamlBotVerifyInfoDecoderConfiguration().also(configurator)
return YamlBotVerifyInfoDecoder(
Yaml(
serializersModule + configuration.serializersModule,
configuration.createYamlConfiguration()
)
)
}

public fun create(decoder: Yaml): YamlBotVerifyInfoDecoder {
return YamlBotVerifyInfoDecoder(decoder)
}


}

/**
Expand Down Expand Up @@ -521,13 +562,20 @@ public class PropertiesBotVerifyInfoDecoder(override val format: Properties) :
override fun create(configurator: PropertiesConfiguration.() -> Unit): PropertiesBotVerifyInfoDecoder {
return PropertiesBotVerifyInfoDecoder(Properties(PropertiesConfiguration().also(configurator).serializersModule))
}

override fun create(
serializersModule: SerializersModule,
configurator: PropertiesConfiguration.() -> Unit
): PropertiesBotVerifyInfoDecoder {
return PropertiesBotVerifyInfoDecoder(Properties(serializersModule + PropertiesConfiguration().also(configurator).serializersModule))
}
}

/**
* 服务于 [PropertiesBotVerifyInfoDecoder.Factory] 的配置类。
*/
public open class PropertiesConfiguration {
public var serializersModule: SerializersModule = SerializersModule {}
public var serializersModule: SerializersModule = EmptySerializersModule()
}
}

Expand Down