diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..59116a28 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,42 @@ +# https://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +max_line_length = 140 + +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{java,kt,kts,scala,rs,xml,kt.spec,kts.spec}] +indent_size = 4 + +[*.{kt,kts}] +ktlint_code_style = intellij_idea +ktlint_ignore_back_ticked_identifier = true + +ktlint_standard = enabled + +# Experimental rules run by default run on the ktlint code base itself. Experimental rules should not be released if +# we are not pleased ourselves with the results on the ktlint code base. +ktlint_experimental = disabled + +# Don't allow any wildcard imports +ij_kotlin_packages_to_use_import_on_demand = unset + +# Prevent wildcard imports +ij_kotlin_name_count_to_use_star_import = 99 +ij_kotlin_name_count_to_use_star_import_for_members = 99 + +[*.md] +trim_trailing_whitespace = false +max_line_length = unset + +[gradle/verification-metadata.xml] +indent_size = 3 + +[*.yml] +ij_yaml_spaces_within_brackets = false \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 7c424e37..439e10e0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,6 @@ import org.hidetake.gradle.swagger.generator.GenerateSwaggerCode import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jlleitschuh.gradle.ktlint.reporter.ReporterType plugins { java @@ -13,6 +14,8 @@ plugins { kotlin("jvm") version "1.9.22" kotlin("plugin.spring") version "1.9.22" kotlin("kapt") version "1.9.22" + + id("org.jlleitschuh.gradle.ktlint") version "12.1.0" } group = "plus.maa" @@ -28,7 +31,6 @@ repositories { mavenCentral() } - dependencies { val hutoolVersion = "5.8.26" val mapstructVersion = "1.5.5.Final" @@ -68,8 +70,8 @@ dependencies { implementation("cn.hutool:hutool-dfa:$hutoolVersion") // mapstruct - implementation("org.mapstruct:mapstruct:${mapstructVersion}") - kapt("org.mapstruct:mapstruct-processor:${mapstructVersion}") + implementation("org.mapstruct:mapstruct:$mapstructVersion") + kapt("org.mapstruct:mapstruct-processor:$mapstructVersion") implementation("org.eclipse.jgit:org.eclipse.jgit:6.8.0.202311291450-r") implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.apache.agent:6.8.0.202311291450-r") @@ -84,7 +86,6 @@ dependencies { implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") swaggerCodegen("org.openapitools:openapi-generator-cli:7.2.0") - } kapt { @@ -102,11 +103,9 @@ tasks.withType { useJUnitPlatform() } - val swaggerOutputDir = layout.buildDirectory.dir("docs") val swaggerOutputName = "swagger.json" - openApi { apiDocsUrl = "http://localhost:8848/v3/api-docs" outputDir = swaggerOutputDir @@ -119,38 +118,46 @@ swaggerSources { val swaggerOutputFile = swaggerOutputDir.get().file(swaggerOutputName) create("TsFetch") { setInputFile(file(swaggerOutputFile)) - code(closureOf { - language = "typescript-fetch" - configFile = file("client-config/ts-fetch.json") + code( + closureOf { + language = "typescript-fetch" + configFile = file("client-config/ts-fetch.json") // templateDir = file('client-config/typescript-fetch') - rawOptions = listOf("-e", "mustache") - outputDir = file(clientDir.dir("ts-fetch-client")) - }) + rawOptions = listOf("-e", "mustache") + outputDir = file(clientDir.dir("ts-fetch-client")) + }, + ) } create("CSharp") { setInputFile(file(swaggerOutputFile)) - code(closureOf { - language = "csharp" - configFile = file("client-config/csharp-netcore.json") - outputDir = file(clientDir.dir("csharp-client")) + code( + closureOf { + language = "csharp" + configFile = file("client-config/csharp-netcore.json") + outputDir = file(clientDir.dir("csharp-client")) // rawOptions = listOf("--type-mappings", "binary=System.IO.Stream") - }) + }, + ) } create("Cpp") { setInputFile(file(swaggerOutputFile)) - code(closureOf { - language = "cpp-restsdk" - configFile = file("client-config/cpp.json") - outputDir = file(clientDir.dir("cpp-client")) - }) + code( + closureOf { + language = "cpp-restsdk" + configFile = file("client-config/cpp.json") + outputDir = file(clientDir.dir("cpp-client")) + }, + ) } create("Rust") { setInputFile(file(swaggerOutputFile)) - code(closureOf { - language = "rust" - configFile = file("client-config/rust.json") - outputDir = file(clientDir.dir("rust-client")) - }) + code( + closureOf { + language = "rust" + configFile = file("client-config/rust.json") + outputDir = file(clientDir.dir("rust-client")) + }, + ) } } @@ -160,8 +167,15 @@ tasks { } } - gitProperties { failOnNoGitDirectory = false keys = listOf("git.branch", "git.commit.id", "git.commit.id.abbrev", "git.commit.time") } + +ktlint { + ignoreFailures = false + + reporters { + reporter(ReporterType.PLAIN) + } +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b1b7ead9..6d8c9a9e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://mirrors.huaweicloud.com/gradle/gradle-8.6-bin.zip +distributionUrl=https://mirrors.huaweicloud.com/gradle/gradle-8.6-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/src/main/kotlin/plus/maa/backend/common/MaaStatusCode.kt b/src/main/kotlin/plus/maa/backend/common/MaaStatusCode.kt index 4e86edb8..17370ef9 100644 --- a/src/main/kotlin/plus/maa/backend/common/MaaStatusCode.kt +++ b/src/main/kotlin/plus/maa/backend/common/MaaStatusCode.kt @@ -3,7 +3,10 @@ package plus.maa.backend.common /** * @author AnselYuki */ -enum class MaaStatusCode(val code:Int,val message:String) { +enum class MaaStatusCode( + val code: Int, + val message: String, +) { /** * MAA自定义状态码 */ @@ -12,5 +15,4 @@ enum class MaaStatusCode(val code:Int,val message:String) { MAA_USER_NOT_ENABLED(10003, "用户未启用"), MAA_USER_EXISTS(10004, "用户已存在"), MAA_REGISTRATION_CODE_NOT_FOUND(10011, "注册验证码错误"), - } diff --git a/src/main/kotlin/plus/maa/backend/common/annotation/SensitiveWordDetection.kt b/src/main/kotlin/plus/maa/backend/common/annotation/SensitiveWordDetection.kt index 6f8e22e0..d976ec10 100644 --- a/src/main/kotlin/plus/maa/backend/common/annotation/SensitiveWordDetection.kt +++ b/src/main/kotlin/plus/maa/backend/common/annotation/SensitiveWordDetection.kt @@ -15,5 +15,5 @@ annotation class SensitiveWordDetection( /** * SpEL 表达式 */ - vararg val value: String = [] + vararg val value: String = [], ) diff --git a/src/main/kotlin/plus/maa/backend/common/aop/JsonSchemaAop.kt b/src/main/kotlin/plus/maa/backend/common/aop/JsonSchemaAop.kt index 66fce403..4f684be6 100644 --- a/src/main/kotlin/plus/maa/backend/common/aop/JsonSchemaAop.kt +++ b/src/main/kotlin/plus/maa/backend/common/aop/JsonSchemaAop.kt @@ -30,7 +30,7 @@ private val log = KotlinLogging.logger { } @Component @Aspect class JsonSchemaAop( - private val mapper: ObjectMapper + private val mapper: ObjectMapper, ) { @Pointcut("@annotation(plus.maa.backend.common.annotation.JsonSchema)") fun pt() { @@ -46,7 +46,7 @@ class JsonSchemaAop( fun before(joinPoint: JoinPoint, jsonSchema: JsonSchema?) { var schemaJson: String? = null var content: String? = null - //判断是验证的是Copilot还是Rating + // 判断是验证的是Copilot还是Rating for (arg in joinPoint.args) { if (arg is CopilotCUDRequest) { content = arg.content @@ -63,8 +63,7 @@ class JsonSchemaAop( } if (schemaJson == null || content == null) return - - //获取json schema json路径并验证 + // 获取json schema json路径并验证 try { ClassPathResource(schemaJson).inputStream.use { inputStream -> val json = JSONObject(content) @@ -84,4 +83,4 @@ class JsonSchemaAop( private const val COPILOT_SCHEMA_JSON = "static/templates/maa-copilot-schema.json" private const val RATING_SCHEMA_JSON = "static/templates/maa-rating-schema.json" } -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/common/aop/SensitiveWordAop.kt b/src/main/kotlin/plus/maa/backend/common/aop/SensitiveWordAop.kt index e95eed9d..f19be503 100644 --- a/src/main/kotlin/plus/maa/backend/common/aop/SensitiveWordAop.kt +++ b/src/main/kotlin/plus/maa/backend/common/aop/SensitiveWordAop.kt @@ -26,9 +26,8 @@ import plus.maa.backend.controller.response.MaaResultException class SensitiveWordAop( // 敏感词库 private val wordTree: WordTree, - private val objectMapper: ObjectMapper + private val objectMapper: ObjectMapper, ) { - // SpEL 表达式解析器 private val parser = SpelExpressionParser() diff --git a/src/main/kotlin/plus/maa/backend/common/utils/ArkLevelUtil.kt b/src/main/kotlin/plus/maa/backend/common/utils/ArkLevelUtil.kt index 6c52bfb5..876cd79f 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/ArkLevelUtil.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/ArkLevelUtil.kt @@ -3,8 +3,9 @@ package plus.maa.backend.common.utils import java.util.regex.Pattern object ArkLevelUtil { - private val NOT_KEY_INFO: Pattern = Pattern.compile( // level_、各种难度前缀、season_、前导零、以-或者_划分的后缀 - "^level_|^easy_|^hard_|^tough_|^main_|season_|(? = ConcurrentHashMap() @@ -41,11 +41,10 @@ class IdComponent( return v.incrementAndGet() } - private fun getMax(entityClass: Class, idGetter: (T) -> Long, fieldName: String) = - mongoTemplate.findOne( - Query().with(Sort.by(fieldName).descending()).limit(1), - entityClass - ) - ?.let(idGetter) - ?: 20000L + private fun getMax(entityClass: Class, idGetter: (T) -> Long, fieldName: String) = mongoTemplate.findOne( + Query().with(Sort.by(fieldName).descending()).limit(1), + entityClass, + ) + ?.let(idGetter) + ?: 20000L } diff --git a/src/main/kotlin/plus/maa/backend/common/utils/IpUtil.kt b/src/main/kotlin/plus/maa/backend/common/utils/IpUtil.kt index d9384dc8..27185384 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/IpUtil.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/IpUtil.kt @@ -20,13 +20,13 @@ object IpUtil { if (ip.isNullOrEmpty() || "unknown".equals(ip, ignoreCase = true)) { ip = request.getHeader("Proxy-Client-IP") } - if (ip.isNullOrEmpty()|| "unknown".equals(ip, ignoreCase = true)) { + if (ip.isNullOrEmpty() || "unknown".equals(ip, ignoreCase = true)) { ip = request.getHeader("WL-Proxy-Client-IP") } - if (ip.isNullOrEmpty()|| "unknown".equals(ip, ignoreCase = true)) { + if (ip.isNullOrEmpty() || "unknown".equals(ip, ignoreCase = true)) { ip = request.remoteAddr if (ip == "127.0.0.1") { - //根据网卡取本机配置的IP + // 根据网卡取本机配置的IP val inet: InetAddress? try { inet = InetAddress.getLocalHost() diff --git a/src/main/kotlin/plus/maa/backend/common/utils/KtExtensions.kt b/src/main/kotlin/plus/maa/backend/common/utils/KtExtensions.kt index 9753e3e7..ba19bb0a 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/KtExtensions.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/KtExtensions.kt @@ -1,4 +1,3 @@ package plus.maa.backend.common.utils - -inline fun T?.requireNotNull(lazyMessage: () -> Any): T = requireNotNull(this, lazyMessage) \ No newline at end of file +inline fun T?.requireNotNull(lazyMessage: () -> Any): T = requireNotNull(this, lazyMessage) diff --git a/src/main/kotlin/plus/maa/backend/common/utils/OkHttpUtils.kt b/src/main/kotlin/plus/maa/backend/common/utils/OkHttpUtils.kt index 225e2627..34df0bfc 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/OkHttpUtils.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/OkHttpUtils.kt @@ -17,11 +17,10 @@ class OkHttpUtils { * @return OkHttpClient */ @Bean - fun defaultOkHttpClient(): OkHttpClient { - return OkHttpClient().newBuilder() - .connectTimeout(5, TimeUnit.SECONDS) - .readTimeout(5, TimeUnit.SECONDS) - .connectionPool(ConnectionPool(10, 5, TimeUnit.MINUTES)) - .build() - } + fun defaultOkHttpClient(): OkHttpClient = OkHttpClient() + .newBuilder() + .connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .connectionPool(ConnectionPool(10, 5, TimeUnit.MINUTES)) + .build() } diff --git a/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotConverter.kt b/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotConverter.kt index 2cdcf4fe..ee4798c4 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotConverter.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotConverter.kt @@ -1,6 +1,10 @@ package plus.maa.backend.common.utils.converter -import org.mapstruct.* +import org.mapstruct.BeanMapping +import org.mapstruct.Mapper +import org.mapstruct.Mapping +import org.mapstruct.MappingTarget +import org.mapstruct.NullValuePropertyMappingStrategy import plus.maa.backend.controller.request.copilot.CopilotDTO import plus.maa.backend.controller.response.copilot.CopilotInfo import plus.maa.backend.repository.entity.Copilot @@ -48,13 +52,7 @@ interface CopilotConverter { @Mapping(target = "uploadTime", source = "now") @Mapping(target = "firstUploadTime", source = "now") @Mapping(target = "uploaderId", source = "userId") - fun toCopilot( - copilotDto: CopilotDTO, - copilotId: Long, - userId: String, - now: LocalDateTime, - content: String? - ): Copilot + fun toCopilot(copilotDto: CopilotDTO, copilotId: Long, userId: String, now: LocalDateTime, content: String?): Copilot @Mapping(target = "ratingType", ignore = true) @Mapping(target = "ratingRatio", ignore = true) diff --git a/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotSetConverter.kt b/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotSetConverter.kt index f07c1c5b..5c3bf95f 100644 --- a/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotSetConverter.kt +++ b/src/main/kotlin/plus/maa/backend/common/utils/converter/CopilotSetConverter.kt @@ -13,7 +13,8 @@ import java.time.LocalDateTime * create on 2024-01-01 */ @Mapper( - componentModel = "spring", imports = [LocalDateTime::class] + componentModel = "spring", + imports = [LocalDateTime::class], ) interface CopilotSetConverter { @Mapping(target = "delete", ignore = true) diff --git a/src/main/kotlin/plus/maa/backend/config/HttpInterfaceConfig.kt b/src/main/kotlin/plus/maa/backend/config/HttpInterfaceConfig.kt index 9f22afdc..cce20431 100644 --- a/src/main/kotlin/plus/maa/backend/config/HttpInterfaceConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/HttpInterfaceConfig.kt @@ -25,17 +25,19 @@ class HttpInterfaceConfig { val client = WebClient.builder() .baseUrl("https://api.github.com") - .exchangeStrategies(ExchangeStrategies - .builder() - .codecs { codecs: ClientCodecConfigurer -> - codecs.defaultCodecs() - .jackson2JsonEncoder(Jackson2JsonEncoder(mapper)) - codecs.defaultCodecs() - .jackson2JsonDecoder(Jackson2JsonDecoder(mapper)) - // 最大 20MB - codecs.defaultCodecs().maxInMemorySize(20 * 1024 * 1024) - } - .build()) + .exchangeStrategies( + ExchangeStrategies + .builder() + .codecs { codecs: ClientCodecConfigurer -> + codecs.defaultCodecs() + .jackson2JsonEncoder(Jackson2JsonEncoder(mapper)) + codecs.defaultCodecs() + .jackson2JsonDecoder(Jackson2JsonDecoder(mapper)) + // 最大 20MB + codecs.defaultCodecs().maxInMemorySize(20 * 1024 * 1024) + } + .build(), + ) .defaultHeaders { headers: HttpHeaders -> headers.add("Accept", "application/vnd.github+json") headers.add("X-GitHub-Api-Version", "2022-11-28") diff --git a/src/main/kotlin/plus/maa/backend/config/JacksonConfig.kt b/src/main/kotlin/plus/maa/backend/config/JacksonConfig.kt index 7fa35089..45a442cc 100644 --- a/src/main/kotlin/plus/maa/backend/config/JacksonConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/JacksonConfig.kt @@ -9,26 +9,29 @@ import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder import java.io.IOException -import java.time.* +import java.time.LocalDateTime +import java.time.ZoneId import java.time.format.DateTimeFormatter @Configuration -class JacksonConfig(private val jacksonProperties: JacksonProperties) { +class JacksonConfig( + private val jacksonProperties: JacksonProperties, +) { @Bean - fun jsonCustomizer(): Jackson2ObjectMapperBuilderCustomizer { - return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> + fun jsonCustomizer(): Jackson2ObjectMapperBuilderCustomizer = + Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> val format = jacksonProperties.dateFormat val timeZone = jacksonProperties.timeZone val formatter = DateTimeFormatter.ofPattern(format).withZone(timeZone.toZoneId()) builder.serializers(LocalDateTimeSerializer(formatter)) } - } - class LocalDateTimeSerializer(private val formatter: DateTimeFormatter) : - StdSerializer(LocalDateTime::class.java) { + class LocalDateTimeSerializer( + private val formatter: DateTimeFormatter, + ) : StdSerializer(LocalDateTime::class.java) { @Throws(IOException::class) override fun serialize(value: LocalDateTime, gen: JsonGenerator, provider: SerializerProvider) { gen.writeString(value.atZone(ZoneId.systemDefault()).format(formatter)) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/config/NativeReflectionConfig.kt b/src/main/kotlin/plus/maa/backend/config/NativeReflectionConfig.kt index 1e112e9f..30d89048 100644 --- a/src/main/kotlin/plus/maa/backend/config/NativeReflectionConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/NativeReflectionConfig.kt @@ -5,8 +5,13 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategies.LowerCamelCaseStr import org.springframework.aot.hint.annotation.RegisterReflectionForBinding import org.springframework.context.annotation.Configuration import plus.maa.backend.controller.request.copilot.CopilotDTO -import plus.maa.backend.repository.entity.gamedata.* +import plus.maa.backend.repository.entity.gamedata.ArkActivity +import plus.maa.backend.repository.entity.gamedata.ArkCharacter +import plus.maa.backend.repository.entity.gamedata.ArkStage +import plus.maa.backend.repository.entity.gamedata.ArkTilePos import plus.maa.backend.repository.entity.gamedata.ArkTilePos.Tile +import plus.maa.backend.repository.entity.gamedata.ArkTower +import plus.maa.backend.repository.entity.gamedata.ArkZone import plus.maa.backend.service.model.RatingCache /** @@ -28,6 +33,6 @@ import plus.maa.backend.service.model.RatingCache CopilotDTO::class, RatingCache::class, PropertyNamingStrategies.SnakeCaseStrategy::class, - LowerCamelCaseStrategy::class + LowerCamelCaseStrategy::class, ) class NativeReflectionConfig diff --git a/src/main/kotlin/plus/maa/backend/config/SensitiveWordConfig.kt b/src/main/kotlin/plus/maa/backend/config/SensitiveWordConfig.kt index 36b4d247..86452392 100644 --- a/src/main/kotlin/plus/maa/backend/config/SensitiveWordConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/SensitiveWordConfig.kt @@ -10,8 +10,6 @@ import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader -private val log = KotlinLogging.logger { } - /** * 敏感词配置类

* @@ -21,9 +19,9 @@ private val log = KotlinLogging.logger { } @Configuration class SensitiveWordConfig( // 标准的 Spring 路径匹配语法,默认为 classpath:sensitive-word.txt - @Value("\${maa-copilot.sensitive-word.path:classpath:sensitive-word.txt}") - private val sensitiveWordPath: String + @Value("\${maa-copilot.sensitive-word.path:classpath:sensitive-word.txt}") private val sensitiveWordPath: String, ) { + private val log = KotlinLogging.logger {} /** * 敏感词库初始化

@@ -44,7 +42,7 @@ class SensitiveWordConfig( // 以行为单位载入敏感词 try { BufferedReader( - InputStreamReader(sensitiveWordResource.inputStream) + InputStreamReader(sensitiveWordResource.inputStream), ).use { bufferedReader -> var line: String? while ((bufferedReader.readLine().also { line = it }) != null) { diff --git a/src/main/kotlin/plus/maa/backend/config/ThreadPoolConfig.kt b/src/main/kotlin/plus/maa/backend/config/ThreadPoolConfig.kt index 99a04010..e88b8115 100644 --- a/src/main/kotlin/plus/maa/backend/config/ThreadPoolConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/ThreadPoolConfig.kt @@ -16,8 +16,8 @@ class ThreadPoolConfig { @Bean( name = [ TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME, - AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME - ] + AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME, + ], ) fun defaultTaskExecutor(builder: ThreadPoolTaskExecutorBuilder): ThreadPoolTaskExecutor = builder.build() diff --git a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimit.kt b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimit.kt index cb1af520..d8a26f29 100644 --- a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimit.kt +++ b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimit.kt @@ -12,10 +12,10 @@ import java.lang.annotation.Inherited AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, - AnnotationTarget.PROPERTY_SETTER + AnnotationTarget.PROPERTY_SETTER, ) @Retention( - AnnotationRetention.RUNTIME + AnnotationRetention.RUNTIME, ) annotation class AccessLimit( /** @@ -25,5 +25,5 @@ annotation class AccessLimit( /** * 指定时间 second,redis 数据过期时间 */ - val second: Int = 10 + val second: Int = 10, ) diff --git a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitConfig.kt b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitConfig.kt index 39d67add..a0ddeb0d 100644 --- a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitConfig.kt @@ -11,8 +11,7 @@ class AccessLimitConfig( private val stringRedisTemplate: StringRedisTemplate, private val objectMapper: ObjectMapper, ) : WebMvcConfigurer { - override fun addInterceptors(registry: InterceptorRegistry) { registry.addInterceptor(AccessLimitInterceptor(stringRedisTemplate, objectMapper)) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitInterceptor.kt b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitInterceptor.kt index 10e484a5..5af3dbd2 100644 --- a/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitInterceptor.kt +++ b/src/main/kotlin/plus/maa/backend/config/accesslimit/AccessLimitInterceptor.kt @@ -20,7 +20,6 @@ class AccessLimitInterceptor( private val stringRedisTemplate: StringRedisTemplate, private val objectMapper: ObjectMapper, ) : HandlerInterceptor { - private val log = KotlinLogging.logger { } @Throws(Exception::class) @@ -37,7 +36,7 @@ class AccessLimitInterceptor( key, (count + 1).toString(), ann.second.toLong(), - TimeUnit.SECONDS + TimeUnit.SECONDS, ) } else { // 请求过于频繁 diff --git a/src/main/kotlin/plus/maa/backend/config/doc/RequireJwt.kt b/src/main/kotlin/plus/maa/backend/config/doc/RequireJwt.kt index 1384f4c1..1ce394fa 100644 --- a/src/main/kotlin/plus/maa/backend/config/doc/RequireJwt.kt +++ b/src/main/kotlin/plus/maa/backend/config/doc/RequireJwt.kt @@ -11,10 +11,10 @@ import java.lang.annotation.Inherited AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CLASS, - AnnotationTarget.ANNOTATION_CLASS + AnnotationTarget.ANNOTATION_CLASS, ) @Retention( - AnnotationRetention.RUNTIME + AnnotationRetention.RUNTIME, ) @Inherited @SecurityRequirement(name = SpringDocConfig.SECURITY_SCHEME_JWT) diff --git a/src/main/kotlin/plus/maa/backend/config/doc/SpringDocConfig.kt b/src/main/kotlin/plus/maa/backend/config/doc/SpringDocConfig.kt index 5e21f73a..e11e392e 100644 --- a/src/main/kotlin/plus/maa/backend/config/doc/SpringDocConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/doc/SpringDocConfig.kt @@ -16,36 +16,50 @@ import plus.maa.backend.config.external.MaaCopilotProperties * @author AnselYuki */ @Configuration -class SpringDocConfig(properties: MaaCopilotProperties) { - private val _info = properties.info +class SpringDocConfig( + properties: MaaCopilotProperties, +) { + private val info = properties.info private val jwt = properties.jwt @Bean fun emergencyLogistics(): OpenAPI = OpenAPI().apply { - info(Info().apply { - title(_info.title) - description(_info.description) - version(_info.version) - license(License().apply { - name("GNU Affero General Public License v3.0") - url("https://www.gnu.org/licenses/agpl-3.0.html") - }) - }) - externalDocs(ExternalDocumentation().apply { - description("GitHub repo") - url("https://github.com/MaaAssistantArknights/MaaBackendCenter") - }) - components(Components().apply { - addSecuritySchemes(SECURITY_SCHEME_JWT, SecurityScheme().apply { - type(SecurityScheme.Type.HTTP) - scheme("bearer") - `in`(SecurityScheme.In.HEADER) - name(jwt.header) - val s = "JWT Authorization header using the Bearer scheme. Raw head example: " + - "\"${jwt.header}: Bearer {token}\"" - description(s) - }) - }) + info( + Info().apply { + title(this@SpringDocConfig.info.title) + description(this@SpringDocConfig.info.description) + version(this@SpringDocConfig.info.version) + license( + License().apply { + name("GNU Affero General Public License v3.0") + url("https://www.gnu.org/licenses/agpl-3.0.html") + }, + ) + }, + ) + externalDocs( + ExternalDocumentation().apply { + description("GitHub repo") + url("https://github.com/MaaAssistantArknights/MaaBackendCenter") + }, + ) + components( + Components().apply { + addSecuritySchemes( + SECURITY_SCHEME_JWT, + SecurityScheme().apply { + type(SecurityScheme.Type.HTTP) + scheme("bearer") + `in`(SecurityScheme.In.HEADER) + name(jwt.header) + val s = + "JWT Authorization header using the Bearer scheme. Raw head example: " + + "\"${jwt.header}: Bearer {token}\"" + description(s) + }, + ) + }, + ) } @Bean diff --git a/src/main/kotlin/plus/maa/backend/config/external/ArkLevelGit.kt b/src/main/kotlin/plus/maa/backend/config/external/ArkLevelGit.kt index 8ecabc50..c645e681 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/ArkLevelGit.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/ArkLevelGit.kt @@ -1,8 +1,7 @@ package plus.maa.backend.config.external - data class ArkLevelGit( - var repository: String = "https://github.com/MaaAssistantArknights/MaaAssistantArknights.git", - var localRepository: String = "./MaaAssistantArknights", - var jsonPath: String = "resource/Arknights-Tile-Pos/", + var repository: String = "https://github.com/MaaAssistantArknights/MaaAssistantArknights.git", + var localRepository: String = "./MaaAssistantArknights", + var jsonPath: String = "resource/Arknights-Tile-Pos/", ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Cache.kt b/src/main/kotlin/plus/maa/backend/config/external/Cache.kt index 99060b2b..1df7908f 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Cache.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Cache.kt @@ -1,6 +1,5 @@ package plus.maa.backend.config.external - -data class Cache ( - var defaultExpire: Long = 0 +data class Cache( + var defaultExpire: Long = 0, ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Copilot.kt b/src/main/kotlin/plus/maa/backend/config/external/Copilot.kt index 110702b5..3c4277f8 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Copilot.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Copilot.kt @@ -1,12 +1,11 @@ package plus.maa.backend.config.external - data class Copilot( - /** - * 作业评分总数少于指定值时显示评分不足 - * - * - * 默认值:50 - */ - var minValueShowNotEnoughRating: Int = 50 + /** + * 作业评分总数少于指定值时显示评分不足 + * + * + * 默认值:50 + */ + var minValueShowNotEnoughRating: Int = 50, ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/CopilotBackup.kt b/src/main/kotlin/plus/maa/backend/config/external/CopilotBackup.kt index c8acf580..0e69099d 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/CopilotBackup.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/CopilotBackup.kt @@ -1,29 +1,24 @@ package plus.maa.backend.config.external - data class CopilotBackup( - /** - * 是否禁用备份功能 - */ - var disabled: Boolean = false, - - /** - * 本地备份地址 - * */ - var dir: String = "/home/dove/copilotBak", - - /** - * 远程备份地址 - */ - var uri: String = "git@github.com:dragove/maa-copilot-store.git", - - /** - * git 用户名 - */ - var username: String = "dragove", - - /** - * git 邮箱 - */ - var email: String = "dragove@qq.com", + /** + * 是否禁用备份功能 + */ + var disabled: Boolean = false, + /** + * 本地备份地址 + * */ + var dir: String = "/home/dove/copilotBak", + /** + * 远程备份地址 + */ + var uri: String = "git@github.com:dragove/maa-copilot-store.git", + /** + * git 用户名 + */ + var username: String = "dragove", + /** + * git 邮箱 + */ + var email: String = "dragove@qq.com", ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Github.kt b/src/main/kotlin/plus/maa/backend/config/external/Github.kt index a5bfe359..b7389a78 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Github.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Github.kt @@ -1,9 +1,8 @@ package plus.maa.backend.config.external - data class Github( - /** - * GitHub api token - */ - var token: String = "github_pat_xxx" -) \ No newline at end of file + /** + * GitHub api token + */ + var token: String = "github_pat_xxx", +) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Info.kt b/src/main/kotlin/plus/maa/backend/config/external/Info.kt index 5aef2129..c4895bd1 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Info.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Info.kt @@ -1,10 +1,9 @@ package plus.maa.backend.config.external - data class Info( - var title: String = "MAA Copilot Center API", - var description: String = "MAA Copilot Backend Center", - var version: String = "v1.0.0", - var domain: String = "https://prts.maa.plus", - var frontendDomain: String = "https://prts.plus", + var title: String = "MAA Copilot Center API", + var description: String = "MAA Copilot Backend Center", + var version: String = "v1.0.0", + var domain: String = "https://prts.maa.plus", + var frontendDomain: String = "https://prts.plus", ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Jwt.kt b/src/main/kotlin/plus/maa/backend/config/external/Jwt.kt index dccdaef3..91fb990b 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Jwt.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Jwt.kt @@ -1,24 +1,24 @@ package plus.maa.backend.config.external data class Jwt( - /** - * Header name - */ - var header: String = "Authorization", - /** - * 默认的JwtToken过期时间,以秒为单位 - */ - var expire: Long = 21600, - /* - * 默认的 Refresh Token 过期时间,以秒为单位 - */ - var refreshExpire: Long = (30 * 24 * 60 * 60).toLong(), - /** - * JwtToken的加密密钥 - */ - var secret: String = "", - /** - * Jwt 最大同时登录设备数 - */ - var maxLogin: Int = 1, -) \ No newline at end of file + /** + * Header name + */ + var header: String = "Authorization", + /** + * 默认的JwtToken过期时间,以秒为单位 + */ + var expire: Long = 21600, + /* + * 默认的 Refresh Token 过期时间,以秒为单位 + */ + var refreshExpire: Long = (30 * 24 * 60 * 60).toLong(), + /** + * JwtToken的加密密钥 + */ + var secret: String = "", + /** + * Jwt 最大同时登录设备数 + */ + var maxLogin: Int = 1, +) diff --git a/src/main/kotlin/plus/maa/backend/config/external/MaaCopilotProperties.kt b/src/main/kotlin/plus/maa/backend/config/external/MaaCopilotProperties.kt index 797456b8..cc0eac76 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/MaaCopilotProperties.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/MaaCopilotProperties.kt @@ -7,36 +7,26 @@ import org.springframework.stereotype.Component @Component @ConfigurationProperties("maa-copilot") data class MaaCopilotProperties( - @NestedConfigurationProperty - var jwt: Jwt = Jwt(), - - @NestedConfigurationProperty - var github: Github = Github(), - - @NestedConfigurationProperty - var info: Info = Info(), - - @NestedConfigurationProperty - var vcode: Vcode = Vcode(), - - @NestedConfigurationProperty - var cache: Cache = Cache(), - - @NestedConfigurationProperty - var arkLevelGit: ArkLevelGit = ArkLevelGit(), - - @NestedConfigurationProperty - var taskCron: TaskCron = TaskCron(), - - @NestedConfigurationProperty - var backup: CopilotBackup = CopilotBackup(), - - @NestedConfigurationProperty - var mail: Mail = Mail(), - - @NestedConfigurationProperty - var sensitiveWord: SensitiveWord = SensitiveWord(), - - @NestedConfigurationProperty - var copilot: Copilot = Copilot() -) \ No newline at end of file + @NestedConfigurationProperty + var jwt: Jwt = Jwt(), + @NestedConfigurationProperty + var github: Github = Github(), + @NestedConfigurationProperty + var info: Info = Info(), + @NestedConfigurationProperty + var vcode: Vcode = Vcode(), + @NestedConfigurationProperty + var cache: Cache = Cache(), + @NestedConfigurationProperty + var arkLevelGit: ArkLevelGit = ArkLevelGit(), + @NestedConfigurationProperty + var taskCron: TaskCron = TaskCron(), + @NestedConfigurationProperty + var backup: CopilotBackup = CopilotBackup(), + @NestedConfigurationProperty + var mail: Mail = Mail(), + @NestedConfigurationProperty + var sensitiveWord: SensitiveWord = SensitiveWord(), + @NestedConfigurationProperty + var copilot: Copilot = Copilot(), +) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Mail.kt b/src/main/kotlin/plus/maa/backend/config/external/Mail.kt index 14d1c4bf..dda07fa2 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Mail.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Mail.kt @@ -1,13 +1,12 @@ package plus.maa.backend.config.external - data class Mail( - var host: String = "smtp.qq.com", - var port: Int = 465, - var from: String = "2842775752@qq.com", - var user: String = "2842775752", - var pass: String = "123456789", - var starttls: Boolean = true, - var ssl: Boolean = false, - var notification: Boolean = true, + var host: String = "smtp.qq.com", + var port: Int = 465, + var from: String = "2842775752@qq.com", + var user: String = "2842775752", + var pass: String = "123456789", + var starttls: Boolean = true, + var ssl: Boolean = false, + var notification: Boolean = true, ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/SensitiveWord.kt b/src/main/kotlin/plus/maa/backend/config/external/SensitiveWord.kt index 587a2206..7684fdc7 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/SensitiveWord.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/SensitiveWord.kt @@ -1,9 +1,8 @@ package plus.maa.backend.config.external - data class SensitiveWord( - /** - * 敏感词文件路径,默认为 `classpath:sensitive-word.txt` - */ - var path: String = "classpath:sensitive-word.txt" + /** + * 敏感词文件路径,默认为 `classpath:sensitive-word.txt` + */ + var path: String = "classpath:sensitive-word.txt", ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/TaskCron.kt b/src/main/kotlin/plus/maa/backend/config/external/TaskCron.kt index c301b45e..bd00b5fb 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/TaskCron.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/TaskCron.kt @@ -1,6 +1,6 @@ package plus.maa.backend.config.external data class TaskCron( - var arkLevel: String = "-", - var copilotUpdate: String = "-" + var arkLevel: String = "-", + var copilotUpdate: String = "-", ) diff --git a/src/main/kotlin/plus/maa/backend/config/external/Vcode.kt b/src/main/kotlin/plus/maa/backend/config/external/Vcode.kt index da90495b..f3e7bb7e 100644 --- a/src/main/kotlin/plus/maa/backend/config/external/Vcode.kt +++ b/src/main/kotlin/plus/maa/backend/config/external/Vcode.kt @@ -1,8 +1,8 @@ package plus.maa.backend.config.external data class Vcode( - /** - * 默认的验证码失效时间,以秒为单位 - */ - var expire: Long = 0 -) \ No newline at end of file + /** + * 默认的验证码失效时间,以秒为单位 + */ + var expire: Long = 0, +) diff --git a/src/main/kotlin/plus/maa/backend/config/security/AccessDeniedHandlerImpl.kt b/src/main/kotlin/plus/maa/backend/config/security/AccessDeniedHandlerImpl.kt index 3ce13d83..33d9fb19 100644 --- a/src/main/kotlin/plus/maa/backend/config/security/AccessDeniedHandlerImpl.kt +++ b/src/main/kotlin/plus/maa/backend/config/security/AccessDeniedHandlerImpl.kt @@ -17,11 +17,7 @@ import java.io.IOException @Component class AccessDeniedHandlerImpl : AccessDeniedHandler { @Throws(IOException::class) - override fun handle( - request: HttpServletRequest, - response: HttpServletResponse, - accessDeniedException: AccessDeniedException - ) { + override fun handle(request: HttpServletRequest, response: HttpServletResponse, accessDeniedException: AccessDeniedException) { val result = fail(HttpStatus.FORBIDDEN.value(), "权限不足") val json = ObjectMapper().writeValueAsString(result) renderString(response, json, HttpStatus.FORBIDDEN.value()) diff --git a/src/main/kotlin/plus/maa/backend/config/security/AuthenticationEntryPointImpl.kt b/src/main/kotlin/plus/maa/backend/config/security/AuthenticationEntryPointImpl.kt index 36b3ca8b..28cb5866 100644 --- a/src/main/kotlin/plus/maa/backend/config/security/AuthenticationEntryPointImpl.kt +++ b/src/main/kotlin/plus/maa/backend/config/security/AuthenticationEntryPointImpl.kt @@ -16,15 +16,10 @@ import java.io.IOException */ @Component class AuthenticationEntryPointImpl( - private val objectMapper: ObjectMapper + private val objectMapper: ObjectMapper, ) : AuthenticationEntryPoint { - @Throws(IOException::class) - override fun commence( - request: HttpServletRequest, - response: HttpServletResponse, - authException: AuthenticationException - ) { + override fun commence(request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException) { val result = fail(HttpStatus.UNAUTHORIZED.value(), authException.message) val json = objectMapper.writeValueAsString(result) renderString(response, json, HttpStatus.UNAUTHORIZED.value()) diff --git a/src/main/kotlin/plus/maa/backend/config/security/AuthenticationHelper.kt b/src/main/kotlin/plus/maa/backend/config/security/AuthenticationHelper.kt index e811665f..139ebbb6 100644 --- a/src/main/kotlin/plus/maa/backend/config/security/AuthenticationHelper.kt +++ b/src/main/kotlin/plus/maa/backend/config/security/AuthenticationHelper.kt @@ -11,7 +11,6 @@ import org.springframework.web.server.ResponseStatusException import plus.maa.backend.common.utils.IpUtil import plus.maa.backend.service.jwt.JwtAuthToken import plus.maa.backend.service.model.LoginUser -import java.util.* /** * Auth 助手,统一 auth 的设置和获取 @@ -34,9 +33,7 @@ class AuthenticationHelper { * @throws ResponseStatusException 用户未通过验证 */ @Throws(ResponseStatusException::class) - fun requireUserId(): String { - return obtainUserId() ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED) - } + fun requireUserId(): String = obtainUserId() ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED) /** * 获取用户 id diff --git a/src/main/kotlin/plus/maa/backend/config/security/JwtAuthenticationTokenFilter.kt b/src/main/kotlin/plus/maa/backend/config/security/JwtAuthenticationTokenFilter.kt index b5ef49ef..382d4b08 100644 --- a/src/main/kotlin/plus/maa/backend/config/security/JwtAuthenticationTokenFilter.kt +++ b/src/main/kotlin/plus/maa/backend/config/security/JwtAuthenticationTokenFilter.kt @@ -18,14 +18,10 @@ import java.io.IOException class JwtAuthenticationTokenFilter( private val helper: AuthenticationHelper, private val properties: MaaCopilotProperties, - private val jwtService: JwtService + private val jwtService: JwtService, ) : OncePerRequestFilter() { @Throws(IOException::class, ServletException::class) - override fun doFilterInternal( - request: HttpServletRequest, - response: HttpServletResponse, - filterChain: FilterChain - ) { + override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) { try { val token = extractToken(request) val authToken = jwtService.verifyAndParseAuthToken(token) diff --git a/src/main/kotlin/plus/maa/backend/config/security/SecurityConfig.kt b/src/main/kotlin/plus/maa/backend/config/security/SecurityConfig.kt index 84ec20b8..afae4809 100644 --- a/src/main/kotlin/plus/maa/backend/config/security/SecurityConfig.kt +++ b/src/main/kotlin/plus/maa/backend/config/security/SecurityConfig.kt @@ -22,9 +22,8 @@ class SecurityConfig( private val authenticationConfiguration: AuthenticationConfiguration, private val jwtAuthenticationTokenFilter: JwtAuthenticationTokenFilter, private val authenticationEntryPoint: AuthenticationEntryPointImpl, - private val accessDeniedHandler: AccessDeniedHandlerImpl + private val accessDeniedHandler: AccessDeniedHandlerImpl, ) { - @Bean fun passwordEncoder() = BCryptPasswordEncoder() @@ -35,34 +34,42 @@ class SecurityConfig( @Bean @Throws(Exception::class) fun filterChain(http: HttpSecurity): SecurityFilterChain { - //关闭CSRF,设置无状态连接 - http.csrf { obj: CsrfConfigurer -> obj.disable() } //不通过Session获取SecurityContext + // 关闭CSRF,设置无状态连接 + http + .csrf { obj: CsrfConfigurer -> obj.disable() } // 不通过Session获取SecurityContext .sessionManagement { sessionManagement: SessionManagementConfigurer -> sessionManagement.sessionCreationPolicy( - SessionCreationPolicy.STATELESS + SessionCreationPolicy.STATELESS, ) } - //允许匿名访问的接口,如果是测试想要方便点就把这段全注释掉 + // 允许匿名访问的接口,如果是测试想要方便点就把这段全注释掉 http.authorizeHttpRequests { authorize -> - authorize.requestMatchers(*URL_WHITELIST).anonymous() - .requestMatchers(*URL_PERMIT_ALL).permitAll() //权限 0 未激活 1 激活 等等.. (拥有权限1必然拥有权限0 拥有权限2必然拥有权限1、0) - //指定接口需要指定权限才能访问 如果不开启RBAC注释掉这一段即可 - .requestMatchers(*URL_AUTHENTICATION_1).hasAuthority("1") //此处用于管理员操作接口 - .requestMatchers(*URL_AUTHENTICATION_2).hasAuthority("2") - .anyRequest().authenticated() + authorize + .requestMatchers(*URL_WHITELIST) + .anonymous() + .requestMatchers(*URL_PERMIT_ALL) + .permitAll() // 权限 0 未激活 1 激活 等等.. (拥有权限1必然拥有权限0 拥有权限2必然拥有权限1、0) + // 指定接口需要指定权限才能访问 如果不开启RBAC注释掉这一段即可 + .requestMatchers(*URL_AUTHENTICATION_1) + .hasAuthority("1") // 此处用于管理员操作接口 + .requestMatchers(*URL_AUTHENTICATION_2) + .hasAuthority("2") + .anyRequest() + .authenticated() } - //添加过滤器 + // 添加过滤器 http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter::class.java) - //配置异常处理器,处理认证失败的JSON响应 + // 配置异常处理器,处理认证失败的JSON响应 http.exceptionHandling { exceptionHandling: ExceptionHandlingConfigurer -> - exceptionHandling.authenticationEntryPoint( - authenticationEntryPoint - ).accessDeniedHandler(accessDeniedHandler) + exceptionHandling + .authenticationEntryPoint( + authenticationEntryPoint, + ).accessDeniedHandler(accessDeniedHandler) } - //开启跨域请求 + // 开启跨域请求 http.cors(Customizer.withDefaults()) return http.build() } @@ -71,50 +78,54 @@ class SecurityConfig( /** * 添加放行接口在此处 */ - private val URL_WHITELIST = arrayOf( - "/user/login", - "/user/register", - "/user/sendRegistrationToken" - ) + private val URL_WHITELIST = + arrayOf( + "/user/login", + "/user/register", + "/user/sendRegistrationToken", + ) - private val URL_PERMIT_ALL = arrayOf( - "/", - "/error", - "/version", - "/user/activateAccount", - "/user/password/reset_request", - "/user/password/reset", - "/user/refresh", - "/swagger-ui.html", - "/v3/api-docs/**", - "/swagger-ui/**", - "/arknights/level", - "/copilot/query", - "/set/query", - "/set/get", - "/copilot/get/**", - "/copilot/rating", - "/comments/query", - "/file/upload", - "/comments/status", - "/copilot/status" - ) + private val URL_PERMIT_ALL = + arrayOf( + "/", + "/error", + "/version", + "/user/activateAccount", + "/user/password/reset_request", + "/user/password/reset", + "/user/refresh", + "/swagger-ui.html", + "/v3/api-docs/**", + "/swagger-ui/**", + "/arknights/level", + "/copilot/query", + "/set/query", + "/set/get", + "/copilot/get/**", + "/copilot/rating", + "/comments/query", + "/file/upload", + "/comments/status", + "/copilot/status", + ) - //添加需要权限1才能访问的接口 - private val URL_AUTHENTICATION_1 = arrayOf( - "/copilot/delete", - "/copilot/update", - "/copilot/upload", - "/comments/add", - "/comments/delete" - ) + // 添加需要权限1才能访问的接口 + private val URL_AUTHENTICATION_1 = + arrayOf( + "/copilot/delete", + "/copilot/update", + "/copilot/upload", + "/comments/add", + "/comments/delete", + ) - private val URL_AUTHENTICATION_2 = arrayOf( - "/file/download/**", - "/file/download/", - "/file/disable", - "/file/enable", - "/file/upload_ability" - ) + private val URL_AUTHENTICATION_2 = + arrayOf( + "/file/download/**", + "/file/download/", + "/file/disable", + "/file/enable", + "/file/upload_ability", + ) } } diff --git a/src/main/kotlin/plus/maa/backend/controller/ArkLevelController.kt b/src/main/kotlin/plus/maa/backend/controller/ArkLevelController.kt index 9854c9d3..80f4088f 100644 --- a/src/main/kotlin/plus/maa/backend/controller/ArkLevelController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/ArkLevelController.kt @@ -16,13 +16,10 @@ import plus.maa.backend.service.ArkLevelService @RestController @Tag(name = "ArkLevelController", description = "关卡数据管理接口") class ArkLevelController( - private val arkLevelService: ArkLevelService + private val arkLevelService: ArkLevelService, ) { - @GetMapping("/arknights/level") @ApiResponse(description = "关卡数据") @Operation(summary = "获取关卡数据") - fun getLevels(): MaaResult> { - return success(arkLevelService.arkLevelInfos) - } + fun getLevels(): MaaResult> = success(arkLevelService.arkLevelInfos) } diff --git a/src/main/kotlin/plus/maa/backend/controller/CommentsAreaController.kt b/src/main/kotlin/plus/maa/backend/controller/CommentsAreaController.kt index 1e696c27..096311e5 100644 --- a/src/main/kotlin/plus/maa/backend/controller/CommentsAreaController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/CommentsAreaController.kt @@ -6,12 +6,21 @@ import io.swagger.v3.oas.annotations.tags.Tag import jakarta.validation.Valid import jakarta.validation.constraints.NotBlank import org.springdoc.core.annotations.ParameterObject -import org.springframework.web.bind.annotation.* +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController import plus.maa.backend.common.annotation.JsonSchema import plus.maa.backend.common.annotation.SensitiveWordDetection import plus.maa.backend.config.doc.RequireJwt import plus.maa.backend.config.security.AuthenticationHelper -import plus.maa.backend.controller.request.comments.* +import plus.maa.backend.controller.request.comments.CommentsAddDTO +import plus.maa.backend.controller.request.comments.CommentsDeleteDTO +import plus.maa.backend.controller.request.comments.CommentsQueriesDTO +import plus.maa.backend.controller.request.comments.CommentsRatingDTO +import plus.maa.backend.controller.request.comments.CommentsToppingDTO import plus.maa.backend.controller.response.MaaResult import plus.maa.backend.controller.response.MaaResult.Companion.success import plus.maa.backend.controller.response.comments.CommentsAreaInfo @@ -26,7 +35,7 @@ import plus.maa.backend.service.CommentsAreaService @RequestMapping("/comments") class CommentsAreaController( private val commentsAreaService: CommentsAreaService, - private val authHelper: AuthenticationHelper + private val authHelper: AuthenticationHelper, ) { @SensitiveWordDetection("#comments.message") @PostMapping("/add") @@ -41,9 +50,8 @@ class CommentsAreaController( @GetMapping("/query") @Operation(summary = "分页查询评论") @ApiResponse(description = "评论区信息") - fun queriesCommentsArea(@ParameterObject parsed: @Valid CommentsQueriesDTO): MaaResult { - return success(commentsAreaService.queriesCommentsArea(parsed)) - } + fun queriesCommentsArea(@ParameterObject parsed: @Valid CommentsQueriesDTO): MaaResult = + success(commentsAreaService.queriesCommentsArea(parsed)) @PostMapping("/delete") @Operation(summary = "删除评论") diff --git a/src/main/kotlin/plus/maa/backend/controller/CopilotController.kt b/src/main/kotlin/plus/maa/backend/controller/CopilotController.kt index 2bc3d86b..2bae2ec4 100644 --- a/src/main/kotlin/plus/maa/backend/controller/CopilotController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/CopilotController.kt @@ -9,7 +9,13 @@ import jakarta.validation.Valid import jakarta.validation.constraints.NotBlank import org.springdoc.core.annotations.ParameterObject import org.springframework.http.HttpHeaders -import org.springframework.web.bind.annotation.* +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController import plus.maa.backend.common.annotation.JsonSchema import plus.maa.backend.common.annotation.SensitiveWordDetection import plus.maa.backend.config.doc.RequireJwt @@ -34,18 +40,18 @@ import plus.maa.backend.service.CopilotService class CopilotController( private val copilotService: CopilotService, private val helper: AuthenticationHelper, - private val response: HttpServletResponse + private val response: HttpServletResponse, ) { - @Operation(summary = "上传作业") @ApiResponse(description = "上传作业结果") @RequireJwt @JsonSchema - @SensitiveWordDetection("#request.content != null ? #objectMapper.readTree(#request.content).get('doc')?.toString() : null") + @SensitiveWordDetection( + "#request.content != null ? #objectMapper.readTree(#request.content).get('doc')?.toString() : null", + ) @PostMapping("/upload") - fun uploadCopilot(@RequestBody request: CopilotCUDRequest): MaaResult { - return success(copilotService.upload(helper.requireUserId(), request.content)) - } + fun uploadCopilot(@RequestBody request: CopilotCUDRequest): MaaResult = + success(copilotService.upload(helper.requireUserId(), request.content)) @Operation(summary = "删除作业") @ApiResponse(description = "删除作业结果") @@ -59,21 +65,16 @@ class CopilotController( @Operation(summary = "获取作业") @ApiResponse(description = "作业信息") @GetMapping("/get/{id}") - fun getCopilotById( - @Parameter(description = "作业id") @PathVariable("id") id: Long - ): MaaResult { + fun getCopilotById(@Parameter(description = "作业id") @PathVariable("id") id: Long): MaaResult { val userIdOrIpAddress = helper.obtainUserIdOrIpAddress() return copilotService.getCopilotById(userIdOrIpAddress, id)?.let { success(it) } ?: fail(404, "作业不存在") } - @Operation(summary = "分页查询作业,提供登录凭据时查询用户自己的作业") @ApiResponse(description = "作业信息") @GetMapping("/query") - fun queriesCopilot( - @ParameterObject parsed: @Valid CopilotQueriesRequest - ): MaaResult { + fun queriesCopilot(@ParameterObject parsed: @Valid CopilotQueriesRequest): MaaResult { // 三秒防抖,缓解前端重复请求问题 response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=3, must-revalidate") return success(copilotService.queriesCopilot(helper.obtainUserId(), parsed)) @@ -83,7 +84,9 @@ class CopilotController( @ApiResponse(description = "更新结果") @RequireJwt @JsonSchema - @SensitiveWordDetection("#copilotCUDRequest.content != null ? #objectMapper.readTree(#copilotCUDRequest.content).get('doc')?.toString() : null") + @SensitiveWordDetection( + "#copilotCUDRequest.content != null ? #objectMapper.readTree(#copilotCUDRequest.content).get('doc')?.toString() : null", + ) @PostMapping("/update") fun updateCopilot(@RequestBody copilotCUDRequest: CopilotCUDRequest): MaaResult { copilotService.update(helper.requireUserId(), copilotCUDRequest) diff --git a/src/main/kotlin/plus/maa/backend/controller/CopilotSetController.kt b/src/main/kotlin/plus/maa/backend/controller/CopilotSetController.kt index db318ddf..54184728 100644 --- a/src/main/kotlin/plus/maa/backend/controller/CopilotSetController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/CopilotSetController.kt @@ -5,7 +5,12 @@ import io.swagger.v3.oas.annotations.Parameter import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.tags.Tag import jakarta.validation.Valid -import org.springframework.web.bind.annotation.* +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController import plus.maa.backend.config.doc.RequireJwt import plus.maa.backend.config.security.AuthenticationHelper import plus.maa.backend.controller.request.CommonIdReq @@ -28,30 +33,24 @@ import plus.maa.backend.service.CopilotSetService @RestController class CopilotSetController( private val service: CopilotSetService, - private val helper: AuthenticationHelper + private val helper: AuthenticationHelper, ) { - @Operation(summary = "查询作业集列表") @ApiResponse(description = "作业集id") @PostMapping("/query") - fun querySets(@RequestBody req: @Valid CopilotSetQuery): MaaResult { - return success(service.query(req, helper.obtainUserId())) - } + fun querySets(@RequestBody req: @Valid CopilotSetQuery): MaaResult = + success(service.query(req, helper.obtainUserId())) @Operation(summary = "查询作业集列表") @ApiResponse(description = "作业集id") @GetMapping("/get") - fun getSet(@RequestParam @Parameter(description = "作业id") id: Long): MaaResult { - return success(service.get(id)) - } + fun getSet(@RequestParam @Parameter(description = "作业id") id: Long): MaaResult = success(service.get(id)) @Operation(summary = "创建作业集") @ApiResponse(description = "作业集id") @RequireJwt @PostMapping("/create") - fun createSet(@RequestBody req: @Valid CopilotSetCreateReq): MaaResult { - return success(service.create(req, helper.obtainUserId())) - } + fun createSet(@RequestBody req: @Valid CopilotSetCreateReq): MaaResult = success(service.create(req, helper.obtainUserId())) @Operation(summary = "添加作业集作业列表") @RequireJwt diff --git a/src/main/kotlin/plus/maa/backend/controller/SystemController.kt b/src/main/kotlin/plus/maa/backend/controller/SystemController.kt index cbc8a389..4b3f6fdf 100644 --- a/src/main/kotlin/plus/maa/backend/controller/SystemController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/SystemController.kt @@ -17,9 +17,8 @@ import plus.maa.backend.controller.response.MaaResult @RestController class SystemController( private val properties: MaaCopilotProperties, - private val gitProperties: GitProperties + private val gitProperties: GitProperties, ) { - /** * Tests if the server is ready. * @return 系统启动信息 @@ -30,7 +29,6 @@ class SystemController( return MaaResult.success("Maa Copilot Server is Running", null) } - /** * Gets the current version of the server. * @return 系统版本信息 @@ -48,4 +46,4 @@ class SystemController( val version: String, val git: GitProperties, ) -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/controller/UserController.kt b/src/main/kotlin/plus/maa/backend/controller/UserController.kt index a5ba5754..2d043ea6 100644 --- a/src/main/kotlin/plus/maa/backend/controller/UserController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/UserController.kt @@ -11,7 +11,14 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import plus.maa.backend.config.doc.RequireJwt import plus.maa.backend.config.security.AuthenticationHelper -import plus.maa.backend.controller.request.user.* +import plus.maa.backend.controller.request.user.LoginDTO +import plus.maa.backend.controller.request.user.PasswordResetDTO +import plus.maa.backend.controller.request.user.PasswordResetVCodeDTO +import plus.maa.backend.controller.request.user.PasswordUpdateDTO +import plus.maa.backend.controller.request.user.RefreshReq +import plus.maa.backend.controller.request.user.RegisterDTO +import plus.maa.backend.controller.request.user.SendRegistrationTokenDTO +import plus.maa.backend.controller.request.user.UserInfoUpdateDTO import plus.maa.backend.controller.response.MaaResult import plus.maa.backend.controller.response.MaaResult.Companion.success import plus.maa.backend.controller.response.user.MaaLoginRsp @@ -34,7 +41,6 @@ class UserController( private val emailService: EmailService, private val helper: AuthenticationHelper, ) { - /** * 更新当前用户的密码(根据原密码) * @@ -119,9 +125,7 @@ class UserController( @PostMapping("/register") @Operation(summary = "用户注册") @ApiResponse(description = "注册结果") - fun register(@RequestBody user: @Valid RegisterDTO): MaaResult { - return success(userService.register(user)) - } + fun register(@RequestBody user: @Valid RegisterDTO): MaaResult = success(userService.register(user)) /** * 获得注册时的验证码 @@ -143,7 +147,5 @@ class UserController( @PostMapping("/login") @Operation(summary = "用户登录") @ApiResponse(description = "登录结果") - fun login(@RequestBody user: @Valid LoginDTO): MaaResult { - return success("登陆成功", userService.login(user)) - } + fun login(@RequestBody user: @Valid LoginDTO): MaaResult = success("登陆成功", userService.login(user)) } diff --git a/src/main/kotlin/plus/maa/backend/controller/file/FileController.kt b/src/main/kotlin/plus/maa/backend/controller/file/FileController.kt index 801b218c..91d0d743 100644 --- a/src/main/kotlin/plus/maa/backend/controller/file/FileController.kt +++ b/src/main/kotlin/plus/maa/backend/controller/file/FileController.kt @@ -8,7 +8,12 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse import jakarta.servlet.http.HttpServletResponse import jakarta.validation.Valid import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.* +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestPart +import org.springframework.web.bind.annotation.RestController import org.springframework.web.multipart.MultipartFile import plus.maa.backend.config.accesslimit.AccessLimit import plus.maa.backend.config.doc.RequireJwt @@ -18,7 +23,6 @@ import plus.maa.backend.controller.response.MaaResult.Companion.fail import plus.maa.backend.controller.response.MaaResult.Companion.success import plus.maa.backend.service.FileService - /** * @author LoMu * Date 2023-03-31 16:41 @@ -27,7 +31,7 @@ import plus.maa.backend.service.FileService @RequestMapping("file") class FileController( private val fileService: FileService, - private val helper: AuthenticationHelper + private val helper: AuthenticationHelper, ) { /** * 支持匿名 @@ -42,7 +46,7 @@ class FileController( @RequestPart type: String?, @RequestPart version: String, @RequestPart(required = false) classification: String?, - @RequestPart(required = false) label: String + @RequestPart(required = false) label: String, ): MaaResult { fileService.uploadFile(file, type, version, classification, label, helper.obtainUserIdOrIpAddress()) return success("上传成功,数据已被接收") @@ -51,7 +55,7 @@ class FileController( @Operation(summary = "下载文件") @ApiResponse( responseCode = "200", - content = [Content(mediaType = "application/zip", schema = Schema(type = "string", format = "binary"))] + content = [Content(mediaType = "application/zip", schema = Schema(type = "string", format = "binary"))], ) @RequireJwt @AccessLimit @@ -60,7 +64,7 @@ class FileController( @Parameter(description = "日期 yyyy-MM-dd") date: String?, @Parameter(description = "在日期之前或之后[before,after]") beLocated: String, @Parameter(description = "对查询到的数据进行删除") delete: Boolean, - response: HttpServletResponse + response: HttpServletResponse, ) { fileService.downloadDateFile(date, beLocated, delete, response) } @@ -68,14 +72,11 @@ class FileController( @Operation(summary = "下载文件") @ApiResponse( responseCode = "200", - content = [Content(mediaType = "application/zip", schema = Schema(type = "string", format = "binary"))] + content = [Content(mediaType = "application/zip", schema = Schema(type = "string", format = "binary"))], ) @RequireJwt @PostMapping("/download") - fun downloadFile( - @RequestBody imageDownloadDTO: @Valid ImageDownloadDTO, - response: HttpServletResponse - ) { + fun downloadFile(@RequestBody imageDownloadDTO: @Valid ImageDownloadDTO, response: HttpServletResponse) { fileService.downloadFile(imageDownloadDTO, response) } @@ -90,9 +91,8 @@ class FileController( @GetMapping("/upload_ability") @RequireJwt @Operation(summary = "获取上传文件功能状态") - fun getUploadAbility(): MaaResult { - return success(UploadAbility(fileService.isUploadEnabled)) - } + fun getUploadAbility(): MaaResult = success(UploadAbility(fileService.isUploadEnabled)) + @Operation(summary = "关闭uploadfile接口") @RequireJwt @PostMapping("/disable") diff --git a/src/main/kotlin/plus/maa/backend/controller/file/ImageDownloadDTO.kt b/src/main/kotlin/plus/maa/backend/controller/file/ImageDownloadDTO.kt index 9a7dc258..7e8acb07 100644 --- a/src/main/kotlin/plus/maa/backend/controller/file/ImageDownloadDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/file/ImageDownloadDTO.kt @@ -12,5 +12,5 @@ data class ImageDownloadDTO( val classification: String? = null, val version: List? = null, val label: String? = null, - val delete: Boolean = false + val delete: Boolean = false, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/file/UploadAbility.kt b/src/main/kotlin/plus/maa/backend/controller/file/UploadAbility.kt index 80281dd9..16116309 100644 --- a/src/main/kotlin/plus/maa/backend/controller/file/UploadAbility.kt +++ b/src/main/kotlin/plus/maa/backend/controller/file/UploadAbility.kt @@ -7,5 +7,5 @@ class UploadAbility( * 是否开启上传功能 */ @field:NotNull - var enabled: Boolean + var enabled: Boolean, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/CommonIdReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/CommonIdReq.kt index 084b2359..d29fc894 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/CommonIdReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/CommonIdReq.kt @@ -8,5 +8,5 @@ import jakarta.validation.constraints.NotNull */ data class CommonIdReq( @field:NotNull(message = "id必填") - val id: T + val id: T, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsAddDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsAddDTO.kt index e853e18f..01354209 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsAddDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsAddDTO.kt @@ -25,5 +25,5 @@ data class CommentsAddDTO( /** * 是否接收通知 */ - val notification: Boolean = true + val notification: Boolean = true, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsDeleteDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsDeleteDTO.kt index 2c7d8667..f30887be 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsDeleteDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsDeleteDTO.kt @@ -8,5 +8,5 @@ import jakarta.validation.constraints.NotBlank */ data class CommentsDeleteDTO( @field:NotBlank(message = "评论id不可为空") - val commentId: String -) \ No newline at end of file + val commentId: String, +) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsQueriesDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsQueriesDTO.kt index 85b76510..ed82eebd 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsQueriesDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsQueriesDTO.kt @@ -15,5 +15,5 @@ data class CommentsQueriesDTO( val limit: Int = 10, val desc: Boolean = true, val orderBy: String? = null, - val justSeeId: String? = null + val justSeeId: String? = null, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsRatingDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsRatingDTO.kt index 54dbda36..de78d68a 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsRatingDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsRatingDTO.kt @@ -10,5 +10,5 @@ data class CommentsRatingDTO( @field:NotBlank(message = "评分id不可为空") val commentId: String, @field:NotBlank(message = "评分不能为空") - val rating: String + val rating: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsToppingDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsToppingDTO.kt index ccd33698..d54b1f01 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsToppingDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/comments/CommentsToppingDTO.kt @@ -6,9 +6,9 @@ import jakarta.validation.constraints.NotBlank * @author Lixuhuilll * Date 2023-08-17 11:20 */ -data class CommentsToppingDTO ( +data class CommentsToppingDTO( @field:NotBlank(message = "评论id不可为空") - val commentId: String, + val commentId: String, // 是否将指定评论置顶 - val topping: Boolean = true + val topping: Boolean = true, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotCUDRequest.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotCUDRequest.kt index a4d73a3f..738d5219 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotCUDRequest.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotCUDRequest.kt @@ -1,6 +1,6 @@ package plus.maa.backend.controller.request.copilot -data class CopilotCUDRequest ( +data class CopilotCUDRequest( val content: String? = null, - val id: Long? = null + val id: Long? = null, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotDTO.kt index 0cf4d665..fc670c9a 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotDTO.kt @@ -3,34 +3,26 @@ package plus.maa.backend.controller.request.copilot import jakarta.validation.constraints.NotBlank import plus.maa.backend.repository.entity.Copilot - /** * @author LoMu * Date 2023-01-10 19:50 */ -data class CopilotDTO ( - //关卡名 +data class CopilotDTO( + // 关卡名 @field:NotBlank(message = "关卡名不能为空") var stageName: String, - - //难度 + // 难度 val difficulty: Int = 0, - - //版本号(文档中说明:最低要求 maa 版本号,必选。保留字段) + // 版本号(文档中说明:最低要求 maa 版本号,必选。保留字段) @field:NotBlank(message = "最低要求 maa 版本不可为空") - val minimumRequired: String, - - //指定干员 + val minimumRequired: String, + // 指定干员 val opers: List? = null, - - //群组 + // 群组 val groups: List? = null, - // 战斗中的操作 val actions: List? = null, - - //描述 + // 描述 val doc: Copilot.Doc? = null, - - val notification: Boolean = false + val notification: Boolean = false, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotQueriesRequest.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotQueriesRequest.kt index 4c6b3d5e..23b47b2f 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotQueriesRequest.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotQueriesRequest.kt @@ -9,7 +9,8 @@ import org.springframework.web.bind.annotation.BindParam */ data class CopilotQueriesRequest( val page: Int = 0, - val limit: @Max(value = 50, message = "单页大小不得超过50") Int = 10, + @Max(value = 50, message = "单页大小不得超过50") + val limit: Int = 10, @BindParam("level_keyword") var levelKeyword: String? = null, val operator: String? = null, val content: String? = null, diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotRatingReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotRatingReq.kt index a241bcec..ee58d209 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotRatingReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilot/CopilotRatingReq.kt @@ -10,5 +10,5 @@ data class CopilotRatingReq( @NotBlank(message = "评分作业id不能为空") val id: Long, @NotBlank(message = "评分不能为空") - val rating: String + val rating: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetCreateReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetCreateReq.kt index d5348866..47ce9091 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetCreateReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetCreateReq.kt @@ -16,18 +16,16 @@ data class CopilotSetCreateReq( @Schema(title = "作业集名称") @field:NotBlank(message = "作业集名称不能为空") val name: String, - @Schema(title = "作业集额外描述") val description: String = "", - @Schema(title = "初始关联作业列表") - @field:NotNull(message = "作业id列表字段不能为null") @Size( + @field:NotNull(message = "作业id列表字段不能为null") + @Size( max = 1000, - message = "作业集作业列表最大只能为1000" + message = "作业集作业列表最大只能为1000", ) override val copilotIds: MutableList, - @Schema(title = "作业集公开状态", enumAsRef = true) @field:NotNull(message = "作业集公开状态不能为null") - val status: CopilotSetStatus + val status: CopilotSetStatus, ) : CopilotSetType diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetModCopilotsReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetModCopilotsReq.kt index 1d3b3199..72fb5123 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetModCopilotsReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetModCopilotsReq.kt @@ -13,8 +13,7 @@ data class CopilotSetModCopilotsReq( @Schema(title = "作业集id") @field:NotNull(message = "作业集id必填") val id: Long, - @Schema(title = "添加/删除收藏的作业id列表") @field:NotEmpty(message = "添加/删除作业id列表不可为空") - val copilotIds: MutableList + val copilotIds: MutableList, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetQuery.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetQuery.kt index 36aea2cb..ae6a0ce9 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetQuery.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetQuery.kt @@ -10,22 +10,18 @@ import jakarta.validation.constraints.PositiveOrZero * create on 2024-01-06 */ @Schema(title = "作业集列表查询接口参数") -data class CopilotSetQuery ( +data class CopilotSetQuery( @Schema(title = "页码") - val page: @Positive(message = "页码必须为大于0的数字") Int = 1, - + @Positive(message = "页码必须为大于0的数字") + val page: Int = 1, @Schema(title = "单页数据量") - val limit: @PositiveOrZero(message = "单页数据量必须为大于等于0的数字") @Max( - value = 50, - message = "单页大小不得超过50" - ) Int = 10, - + @PositiveOrZero(message = "单页数据量必须为大于等于0的数字") + @Max(value = 50, message = "单页大小不得超过50") + val limit: Int = 10, @Schema(title = "查询关键词") val keyword: String? = null, - @Schema(title = "创建者id") val creatorId: String? = null, - @Schema(title = "需要包含的作业id列表") - val copilotIds: List? = null + val copilotIds: List? = null, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetUpdateReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetUpdateReq.kt index c38ba2fa..99a313ff 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetUpdateReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/copilotset/CopilotSetUpdateReq.kt @@ -13,15 +13,12 @@ import plus.maa.backend.service.model.CopilotSetStatus data class CopilotSetUpdateReq( @field:NotNull(message = "作业集id不能为空") val id: Long, - @Schema(title = "作业集名称") @field:NotBlank(message = "作业集名称不能为空") val name: String, - @Schema(title = "作业集额外描述") val description: String = "", - @Schema(title = "作业集公开状态", enumAsRef = true) @field:NotNull(message = "作业集公开状态不能为null") - val status: CopilotSetStatus + val status: CopilotSetStatus, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/LoginDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/LoginDTO.kt index f81f7fe6..d068f34e 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/LoginDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/LoginDTO.kt @@ -11,5 +11,5 @@ data class LoginDTO( @field:Email(message = "邮箱格式错误") val email: String, @field:NotBlank(message = "请输入用户密码") - val password: String + val password: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetDTO.kt index 6b113ba0..06f2dbe0 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetDTO.kt @@ -13,16 +13,14 @@ data class PasswordResetDTO( @field:NotBlank(message = "邮箱格式错误") @field:Email(message = "邮箱格式错误") val email: String, - /** * 验证码 */ @field:NotBlank(message = "请输入验证码") val activeCode: String, - /** * 修改后的密码 */ @field:NotBlank(message = "请输入用户密码") - val password: String + val password: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetVCodeDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetVCodeDTO.kt index c573f315..eeb5dfa7 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetVCodeDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordResetVCodeDTO.kt @@ -12,5 +12,5 @@ data class PasswordResetVCodeDTO( */ @field:NotBlank(message = "邮箱格式错误") @field:Email(message = "邮箱格式错误") - val email: String + val email: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordUpdateDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordUpdateDTO.kt index 824ba8b0..36d4233e 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordUpdateDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/PasswordUpdateDTO.kt @@ -11,5 +11,5 @@ data class PasswordUpdateDTO( val originalPassword: String, @field:NotBlank(message = "密码长度必须在8-32位之间") @field:Length(min = 8, max = 32, message = "密码长度必须在8-32位之间") - val newPassword: String + val newPassword: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/RefreshReq.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/RefreshReq.kt index 9a48f7b4..6417da85 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/RefreshReq.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/RefreshReq.kt @@ -1,5 +1,5 @@ package plus.maa.backend.controller.request.user data class RefreshReq( - val refreshToken: String + val refreshToken: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/RegisterDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/RegisterDTO.kt index 69e1ceaa..9979be97 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/RegisterDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/RegisterDTO.kt @@ -18,5 +18,5 @@ data class RegisterDTO( @field:Length(min = 8, max = 32, message = "密码长度必须在8-32位之间") val password: String, @field:NotBlank(message = "请输入验证码") - val registrationToken: String + val registrationToken: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/SendRegistrationTokenDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/SendRegistrationTokenDTO.kt index 2e5d5e85..3ee5535a 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/SendRegistrationTokenDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/SendRegistrationTokenDTO.kt @@ -6,5 +6,5 @@ import jakarta.validation.constraints.NotBlank data class SendRegistrationTokenDTO( @field:NotBlank(message = "邮箱格式错误") @field:Email(message = "邮箱格式错误") - val email: String + val email: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/request/user/UserInfoUpdateDTO.kt b/src/main/kotlin/plus/maa/backend/controller/request/user/UserInfoUpdateDTO.kt index 8fcf21a6..a920a809 100644 --- a/src/main/kotlin/plus/maa/backend/controller/request/user/UserInfoUpdateDTO.kt +++ b/src/main/kotlin/plus/maa/backend/controller/request/user/UserInfoUpdateDTO.kt @@ -9,5 +9,5 @@ import org.hibernate.validator.constraints.Length data class UserInfoUpdateDTO( @field:NotBlank(message = "用户名长度应在4-24位之间") @field:Length(min = 4, max = 24, message = "用户名长度应在4-24位之间") - val userName: String + val userName: String, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/MaaResult.kt b/src/main/kotlin/plus/maa/backend/controller/response/MaaResult.kt index ea3f8356..e71a7d22 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/MaaResult.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/MaaResult.kt @@ -6,23 +6,18 @@ import com.fasterxml.jackson.annotation.JsonInclude * @author AnselYuki */ @JsonInclude(JsonInclude.Include.NON_NULL) -data class MaaResult(val statusCode: Int, val message: String?, val data: T?) { +data class MaaResult( + val statusCode: Int, + val message: String?, + val data: T?, +) { companion object { - fun success(data: T): MaaResult { - return success(null, data) - } + fun success(data: T): MaaResult = success(null, data) - fun success(): MaaResult { - return success(null, Unit) - } + fun success(): MaaResult = success(null, Unit) - fun success(msg: String?, data: T?): MaaResult { - return MaaResult(200, msg, data) - } - - fun fail(code: Int, msg: String?): MaaResult { - return MaaResult(code, msg, null) - } + fun success(msg: String?, data: T?): MaaResult = MaaResult(200, msg, data) + fun fail(code: Int, msg: String?): MaaResult = MaaResult(code, msg, null) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/controller/response/MaaResultException.kt b/src/main/kotlin/plus/maa/backend/controller/response/MaaResultException.kt index 2e69ed93..89bb4f16 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/MaaResultException.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/MaaResultException.kt @@ -8,10 +8,8 @@ import plus.maa.backend.common.MaaStatusCode */ class MaaResultException( val code: Int, - val msg: String? + val msg: String?, ) : RuntimeException() { - constructor(statusCode: MaaStatusCode) : this(statusCode.code, statusCode.message) constructor(msg: String) : this(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg) - } diff --git a/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsAreaInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsAreaInfo.kt index 6e107488..31fd7ed6 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsAreaInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsAreaInfo.kt @@ -4,7 +4,7 @@ package plus.maa.backend.controller.response.comments * @author LoMu * Date 2023-02-19 11:47 */ -data class CommentsAreaInfo ( +data class CommentsAreaInfo( val hasNext: Boolean, /** * Total number of pages @@ -14,5 +14,5 @@ data class CommentsAreaInfo ( * Total number of elements */ val total: Long, - val data: List + val data: List, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsInfo.kt index b7e3fb66..43b406a8 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/comments/CommentsInfo.kt @@ -10,8 +10,7 @@ data class CommentsInfo( val commentId: String, val uploader: String, val uploaderId: String, - - //评论内容, + // 评论内容, val message: String, val uploadTime: LocalDateTime, val like: Long = 0, diff --git a/src/main/kotlin/plus/maa/backend/controller/response/comments/SubCommentsInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/comments/SubCommentsInfo.kt index 3ac2838f..63b001be 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/comments/SubCommentsInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/comments/SubCommentsInfo.kt @@ -10,12 +10,12 @@ data class SubCommentsInfo( val commentId: String, val uploader: String, val uploaderId: String, - //评论内容, + // 评论内容, val message: String, val uploadTime: LocalDateTime, val like: Long = 0, val dislike: Long = 0, val fromCommentId: String, val mainCommentId: String, - val deleted: Boolean = false + val deleted: Boolean = false, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilot/ArkLevelInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilot/ArkLevelInfo.kt index bcbb2412..7939f534 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilot/ArkLevelInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilot/ArkLevelInfo.kt @@ -13,5 +13,5 @@ data class ArkLevelInfo( val catThree: String, val name: String, val width: Int = 0, - val height: Int = 0 -) : Serializable \ No newline at end of file + val height: Int = 0, +) : Serializable diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotInfo.kt index fd7dd302..9522babd 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotInfo.kt @@ -3,14 +3,12 @@ package plus.maa.backend.controller.response.copilot import java.io.Serializable import java.time.LocalDateTime -data class CopilotInfo ( +data class CopilotInfo( val id: Long, - val uploadTime: LocalDateTime, val uploaderId: String, val uploader: String, - - //用于前端显示的格式化后的干员信息 [干员名]::[技能] + // 用于前端显示的格式化后的干员信息 [干员名]::[技能] val views: Long = 0, val hotScore: Double = 0.0, var available: Boolean = false, @@ -21,5 +19,5 @@ data class CopilotInfo ( val commentsCount: Long = 0, val content: String, val like: Long = 0, - val dislike: Long = 0 -): Serializable + val dislike: Long = 0, +) : Serializable diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotPageInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotPageInfo.kt index 713212ec..3f89d188 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotPageInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilot/CopilotPageInfo.kt @@ -13,6 +13,5 @@ data class CopilotPageInfo( val hasNext: Boolean, val page: Int, val total: Long, - val data: List + val data: List, ) : Serializable - diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetListRes.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetListRes.kt index 0297083a..ceda835e 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetListRes.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetListRes.kt @@ -9,31 +9,23 @@ import java.time.LocalDateTime * create on 2024-01-06 */ @Schema(title = "作业集响应(列表)") -data class CopilotSetListRes ( +data class CopilotSetListRes( @Schema(title = "作业集id") val id: Long, - @Schema(title = "作业集名称") val name: String, - @Schema(title = "额外描述") val description: String, - @Schema(title = "上传者id") val creatorId: String, - @Schema(title = "上传者昵称") val creator: String, - @Schema(title = "作业状态", enumAsRef = true) val status: CopilotSetStatus, - @Schema(title = "创建时间") val createTime: LocalDateTime, - @Schema(title = "更新时间") val updateTime: LocalDateTime, - @Schema(title = "作业id列表") - val copilotIds: List + val copilotIds: List, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetPageRes.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetPageRes.kt index 5a2a9f22..cafee401 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetPageRes.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetPageRes.kt @@ -7,16 +7,13 @@ import io.swagger.v3.oas.annotations.media.Schema * create on 2024-01-06 */ @Schema(title = "作业集分页返回数据") -data class CopilotSetPageRes ( +data class CopilotSetPageRes( @Schema(title = "是否有下一页") val hasNext: Boolean = false, - @Schema(title = "总页数") val page: Int = 0, - @Schema(title = "总数据量") val total: Long = 0, - @Schema(title = "作业集列表") - val data: MutableList + val data: MutableList, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetRes.kt b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetRes.kt index 95cb0713..dea02857 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetRes.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/copilotset/CopilotSetRes.kt @@ -12,28 +12,20 @@ import java.time.LocalDateTime data class CopilotSetRes( @Schema(title = "作业集id") val id: Long, - @Schema(title = "作业集名称") val name: String, - @Schema(title = "额外描述") val description: String, - @Schema(title = "作业id列表") val copilotIds: List, - @Schema(title = "上传者id") val creatorId: String, - @Schema(title = "上传者昵称") val creator: String, - @Schema(title = "创建时间") val createTime: LocalDateTime, - @Schema(title = "更新时间") val updateTime: LocalDateTime, - @Schema(title = "作业状态", enumAsRef = true) - val status: CopilotSetStatus + val status: CopilotSetStatus, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/user/MaaLoginRsp.kt b/src/main/kotlin/plus/maa/backend/controller/response/user/MaaLoginRsp.kt index 9e98b05f..e3f99399 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/user/MaaLoginRsp.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/user/MaaLoginRsp.kt @@ -9,5 +9,5 @@ data class MaaLoginRsp( val refreshToken: String, val refreshTokenValidBefore: Instant, val refreshTokenValidAfter: Instant, - val userInfo: MaaUserInfo + val userInfo: MaaUserInfo, ) diff --git a/src/main/kotlin/plus/maa/backend/controller/response/user/MaaUserInfo.kt b/src/main/kotlin/plus/maa/backend/controller/response/user/MaaUserInfo.kt index decbb2ea..5344d463 100644 --- a/src/main/kotlin/plus/maa/backend/controller/response/user/MaaUserInfo.kt +++ b/src/main/kotlin/plus/maa/backend/controller/response/user/MaaUserInfo.kt @@ -8,7 +8,7 @@ import plus.maa.backend.repository.entity.MaaUser data class MaaUserInfo( val id: String, val userName: String, - val activated: Boolean = false + val activated: Boolean = false, ) { constructor(user: MaaUser) : this(user.userId!!, user.userName, user.status == 1) } diff --git a/src/main/kotlin/plus/maa/backend/filter/ContentLengthRepairFilter.kt b/src/main/kotlin/plus/maa/backend/filter/ContentLengthRepairFilter.kt index dd9d9858..ddb6cd48 100644 --- a/src/main/kotlin/plus/maa/backend/filter/ContentLengthRepairFilter.kt +++ b/src/main/kotlin/plus/maa/backend/filter/ContentLengthRepairFilter.kt @@ -22,11 +22,7 @@ import java.io.InputStream @ConditionalOnProperty(name = ["server.compression.enabled"], havingValue = "true") class ContentLengthRepairFilter : ShallowEtagHeaderFilter() { @Throws(ServletException::class, IOException::class) - override fun doFilterInternal( - request: HttpServletRequest, - response: HttpServletResponse, - filterChain: FilterChain - ) { + override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) { if (response is ContentCachingResponseWrapper) { // 不对已包装过的响应体做处理 filterChain.doFilter(request, response) @@ -39,6 +35,6 @@ class ContentLengthRepairFilter : ShallowEtagHeaderFilter() { request: HttpServletRequest, response: HttpServletResponse, responseStatusCode: Int, - inputStream: InputStream + inputStream: InputStream, ) = false } diff --git a/src/main/kotlin/plus/maa/backend/filter/MaaEtagHeaderFilterRegistrationBean.kt b/src/main/kotlin/plus/maa/backend/filter/MaaEtagHeaderFilterRegistrationBean.kt index fb26e1d0..ff794475 100644 --- a/src/main/kotlin/plus/maa/backend/filter/MaaEtagHeaderFilterRegistrationBean.kt +++ b/src/main/kotlin/plus/maa/backend/filter/MaaEtagHeaderFilterRegistrationBean.kt @@ -17,14 +17,6 @@ import java.io.InputStream */ @Component class MaaEtagHeaderFilterRegistrationBean : FilterRegistrationBean() { - /** - * 配置需要使用 Etag 机制的 URI,采用 Servlet 的 URI 匹配语法 - */ - private val ETAG_URI = setOf( - "/arknights/level", - "/copilot/query" - ) - @PostConstruct fun init() { filter = MaaEtagHeaderFilter() @@ -38,8 +30,10 @@ class MaaEtagHeaderFilterRegistrationBean : FilterRegistrationBean() { } override fun isEligibleForEtag( - request: HttpServletRequest, response: HttpServletResponse, - responseStatusCode: Int, inputStream: InputStream + request: HttpServletRequest, + response: HttpServletResponse, + responseStatusCode: Int, + inputStream: InputStream, ): Boolean { if (super.isEligibleForEtag(request, response, responseStatusCode, inputStream)) { // 使用 ETag 机制的 URI,若其响应中不存在缓存控制头,则配置默认值 @@ -57,4 +51,15 @@ class MaaEtagHeaderFilterRegistrationBean : FilterRegistrationBean() { private const val CACHE_HEAD = "private, no-cache, max-age=0, must-revalidate" } } + + companion object { + /** + * 配置需要使用 Etag 机制的 URI,采用 Servlet 的 URI 匹配语法 + */ + private val ETAG_URI = + setOf( + "/arknights/level", + "/copilot/query", + ) + } } diff --git a/src/main/kotlin/plus/maa/backend/handler/GlobalExceptionHandler.kt b/src/main/kotlin/plus/maa/backend/handler/GlobalExceptionHandler.kt index 664958b9..c9bc3056 100644 --- a/src/main/kotlin/plus/maa/backend/handler/GlobalExceptionHandler.kt +++ b/src/main/kotlin/plus/maa/backend/handler/GlobalExceptionHandler.kt @@ -18,7 +18,7 @@ import plus.maa.backend.controller.response.MaaResult import plus.maa.backend.controller.response.MaaResult.Companion.fail import plus.maa.backend.controller.response.MaaResultException -private val log = KotlinLogging.logger { } +private val log = KotlinLogging.logger { } /** * @author john180 @@ -30,12 +30,9 @@ class GlobalExceptionHandler { * @author FAll * @description 请求参数缺失 * @date 2022/12/23 12:00 - */ + */ @ExceptionHandler(MissingServletRequestParameterException::class) - fun missingServletRequestParameterException( - e: MissingServletRequestParameterException, - request: HttpServletRequest - ): MaaResult { + fun missingServletRequestParameterException(e: MissingServletRequestParameterException, request: HttpServletRequest): MaaResult { logWarn(request) log.warn(e) { "请求参数缺失" } return fail(400, String.format("请求参数缺失:%s", e.parameterName)) @@ -46,12 +43,9 @@ class GlobalExceptionHandler { * @author FAll * @description 参数类型不匹配 * @date 2022/12/23 12:01 - */ + */ @ExceptionHandler(MethodArgumentTypeMismatchException::class) - fun methodArgumentTypeMismatchException( - e: MethodArgumentTypeMismatchException, - request: HttpServletRequest - ): MaaResult { + fun methodArgumentTypeMismatchException(e: MethodArgumentTypeMismatchException, request: HttpServletRequest): MaaResult { logWarn(request) log.warn(e) { "参数类型不匹配" } return fail(400, String.format("参数类型不匹配:%s", e.message)) @@ -62,7 +56,7 @@ class GlobalExceptionHandler { * @author FAll * @description 参数校验错误 * @date 2022/12/23 12:02 - */ + */ @ExceptionHandler(MethodArgumentNotValidException::class) fun methodArgumentNotValidException(e: MethodArgumentNotValidException): MaaResult { val fieldError = e.bindingResult.fieldError @@ -77,7 +71,7 @@ class GlobalExceptionHandler { * @author FAll * @description 请求地址不存在 * @date 2022/12/23 12:03 - */ + */ @ExceptionHandler(NoHandlerFoundException::class) fun noHandlerFoundExceptionHandler(e: NoHandlerFoundException): MaaResult { log.warn(e) { "请求地址不存在" } @@ -89,11 +83,11 @@ class GlobalExceptionHandler { * @author FAll * @description * @date 2022/12/23 12:04 - */ + */ @ExceptionHandler(HttpRequestMethodNotSupportedException::class) fun httpRequestMethodNotSupportedExceptionHandler( e: HttpRequestMethodNotSupportedException, - request: HttpServletRequest + request: HttpServletRequest, ): MaaResult { logWarn(request) log.warn(e) { "请求方式错误" } @@ -113,7 +107,7 @@ class GlobalExceptionHandler { * @author cbc * @description * @date 2022/12/26 12:00 - */ + */ @ExceptionHandler(MaaResultException::class) fun maaResultExceptionHandler(e: MaaResultException): MaaResult { return fail(e.code, e.msg) @@ -146,10 +140,7 @@ class GlobalExceptionHandler { */ @ResponseBody @ExceptionHandler(value = [Exception::class]) - fun defaultExceptionHandler( - e: Exception, - request: HttpServletRequest - ): MaaResult<*> { + fun defaultExceptionHandler(e: Exception, request: HttpServletRequest): MaaResult<*> { logError(request) log.error(e) { "Exception: " } return fail(500, "服务器内部错误") diff --git a/src/main/kotlin/plus/maa/backend/repository/ArkLevelRepository.kt b/src/main/kotlin/plus/maa/backend/repository/ArkLevelRepository.kt index 7fc8b6ab..e528320c 100644 --- a/src/main/kotlin/plus/maa/backend/repository/ArkLevelRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/ArkLevelRepository.kt @@ -25,7 +25,7 @@ interface ArkLevelRepository : MongoRepository { ] } - """ + """, ) fun findByLevelIdFuzzy(levelId: String): List @@ -44,8 +44,7 @@ interface ArkLevelRepository : MongoRepository { ] } - """ + """, ) fun queryLevelByKeyword(keyword: String): List - } diff --git a/src/main/kotlin/plus/maa/backend/repository/CommentsAreaRepository.kt b/src/main/kotlin/plus/maa/backend/repository/CommentsAreaRepository.kt index 9857195a..fd9c3531 100644 --- a/src/main/kotlin/plus/maa/backend/repository/CommentsAreaRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/CommentsAreaRepository.kt @@ -18,7 +18,7 @@ interface CommentsAreaRepository : MongoRepository { copilotId: Long, delete: Boolean, exists: Boolean, - pageable: Pageable + pageable: Pageable, ): Page fun findByCopilotIdAndUploaderIdAndDeleteAndMainCommentIdExists( @@ -26,7 +26,7 @@ interface CommentsAreaRepository : MongoRepository { uploaderId: String, delete: Boolean, exists: Boolean, - pageable: Pageable + pageable: Pageable, ): Page fun findByCopilotIdInAndDelete(copilotIds: Collection, delete: Boolean): List diff --git a/src/main/kotlin/plus/maa/backend/repository/CopilotSetRepository.kt b/src/main/kotlin/plus/maa/backend/repository/CopilotSetRepository.kt index 6a70242c..5fe4a4d3 100644 --- a/src/main/kotlin/plus/maa/backend/repository/CopilotSetRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/CopilotSetRepository.kt @@ -20,7 +20,7 @@ interface CopilotSetRepository : MongoRepository { ] } - """ + """, ) fun findByKeyword(keyword: String, pageable: Pageable): Page } diff --git a/src/main/kotlin/plus/maa/backend/repository/GithubRepository.kt b/src/main/kotlin/plus/maa/backend/repository/GithubRepository.kt index d1924f21..0eec50c9 100644 --- a/src/main/kotlin/plus/maa/backend/repository/GithubRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/GithubRepository.kt @@ -22,8 +22,5 @@ interface GithubRepository { fun getCommits(@RequestHeader("Authorization") token: String): List @GetExchange(value = "/repos/MaaAssistantArknights/MaaAssistantArknights/contents/{path}") - fun getContents( - @RequestHeader("Authorization") token: String, - @PathVariable("path") path: String - ): List + fun getContents(@RequestHeader("Authorization") token: String, @PathVariable("path") path: String): List } diff --git a/src/main/kotlin/plus/maa/backend/repository/RatingRepository.kt b/src/main/kotlin/plus/maa/backend/repository/RatingRepository.kt index a46fa0e8..ba48f978 100644 --- a/src/main/kotlin/plus/maa/backend/repository/RatingRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/RatingRepository.kt @@ -11,6 +11,4 @@ import plus.maa.backend.repository.entity.Rating @Repository interface RatingRepository : MongoRepository { fun findByTypeAndKeyAndUserId(type: Rating.KeyType, key: String, userId: String): Rating? - } - diff --git a/src/main/kotlin/plus/maa/backend/repository/RedisCache.kt b/src/main/kotlin/plus/maa/backend/repository/RedisCache.kt index d0baa3b9..3a354606 100644 --- a/src/main/kotlin/plus/maa/backend/repository/RedisCache.kt +++ b/src/main/kotlin/plus/maa/backend/repository/RedisCache.kt @@ -28,11 +28,9 @@ private val log = KotlinLogging.logger { } */ @Component class RedisCache( - @Value("\${maa-copilot.cache.default-expire}") - private val expire: Int, - private val redisTemplate: StringRedisTemplate + @Value("\${maa-copilot.cache.default-expire}") private val expire: Int, + private val redisTemplate: StringRedisTemplate, ) { - // 添加 JSR310 模块,以便顺利序列化 LocalDateTime 等类型 private val writeMapper: ObjectMapper = jacksonObjectMapper() .registerModules(JavaTimeModule()) @@ -49,8 +47,10 @@ class RedisCache( private val incZSetRedisScript: RedisScript = RedisScript.of(ClassPathResource("redis-lua/incZSet.lua")) // 比较与输入的键值对是否相同,相同则删除 - private val removeKVIfEqualsScript: RedisScript = - RedisScript.of(ClassPathResource("redis-lua/removeKVIfEquals.lua"), Boolean::class.java) + private val removeKVIfEqualsScript: RedisScript = RedisScript.of( + ClassPathResource("redis-lua/removeKVIfEquals.lua"), + Boolean::class.java, + ) fun setData(key: String, value: T) { setCache(key, value, 0, TimeUnit.SECONDS) @@ -78,7 +78,7 @@ class RedisCache( * * @param key 缓存的 key * @param value 被缓存的值 - * @return 是否 set + * @return 是否 set */ fun setCacheIfAbsent(key: String, value: T): Boolean { return setCacheIfAbsent(key, value, expire.toLong()) @@ -90,7 +90,7 @@ class RedisCache( * @param key 缓存的 key * @param value 被缓存的值 * @param timeout 过期时间 - * @return 是否 set + * @return 是否 set */ fun setCacheIfAbsent(key: String, value: T, timeout: Long): Boolean { return setCacheIfAbsent(key, value, timeout, TimeUnit.SECONDS) @@ -103,7 +103,7 @@ class RedisCache( * @param value 被缓存的值 * @param timeout 过期时间 * @param timeUnit 过期时间的单位 - * @return 是否 set + * @return 是否 set */ fun setCacheIfAbsent(key: String, value: T, timeout: Long, timeUnit: TimeUnit): Boolean { val json = getJson(value) ?: return false @@ -137,7 +137,6 @@ class RedisCache( } } - /** * ZSet 中元素的 score += incScore,如果元素不存在则插入

* 会维持 ZSet 的相对大小(size <= 实际大小 <= size + 50)以及过期时间

@@ -156,7 +155,7 @@ class RedisCache( member, incScore.toString(), size.toString(), - timeout.toString() + timeout.toString(), ) } @@ -184,33 +183,33 @@ class RedisCache( return getCache(key, valueType, null, expire.toLong(), TimeUnit.SECONDS) } - fun getCache(key: String, valueType: Class, onMiss: (()->T)?): T? { + fun getCache(key: String, valueType: Class, onMiss: (() -> T)?): T? { return getCache(key, valueType, onMiss, expire.toLong(), TimeUnit.SECONDS) } - fun getCache(key: String, valueType: Class, onMiss: (()->T)?, timeout: Long): T? { + fun getCache(key: String, valueType: Class, onMiss: (() -> T)?, timeout: Long): T? { return getCache(key, valueType, onMiss, timeout, TimeUnit.SECONDS) } - fun getCache(key: String, valueType: Class, onMiss: (()->T)?, timeout: Long, timeUnit: TimeUnit): T? { + fun getCache(key: String, valueType: Class, onMiss: (() -> T)?, timeout: Long, timeUnit: TimeUnit): T? { try { var json = redisTemplate.opsForValue()[key] if (StringUtils.isEmpty(json)) { - if (onMiss == null){ + if (onMiss == null) { return null } - //上锁 - synchronized(RedisCache::class.java) { - //再次查询缓存,目的是判断是否前面的线程已经set过了 - json = redisTemplate.opsForValue()[key] - //第二次校验缓存是否存在 - if (StringUtils.isEmpty(json)) { - val result = onMiss() - //数据库中不存在 - setCache(key, result, timeout, timeUnit) - return result - } + // 上锁 + synchronized(RedisCache::class.java) { + // 再次查询缓存,目的是判断是否前面的线程已经set过了 + json = redisTemplate.opsForValue()[key] + // 第二次校验缓存是否存在 + if (StringUtils.isEmpty(json)) { + val result = onMiss() + // 数据库中不存在 + setCache(key, result, timeout, timeUnit) + return result } + } } return readMapper.readValue(json, valueType) } catch (e: Exception) { @@ -219,22 +218,15 @@ class RedisCache( } } - fun updateCache(key: String, valueType: Class, defaultValue: T, onUpdate: (T)->T) { + fun updateCache(key: String, valueType: Class, defaultValue: T, onUpdate: (T) -> T) { updateCache(key, valueType, defaultValue, onUpdate, expire.toLong(), TimeUnit.SECONDS) } - fun updateCache(key: String, valueType: Class?, defaultValue: T, onUpdate: (T)->T, timeout: Long) { + fun updateCache(key: String, valueType: Class?, defaultValue: T, onUpdate: (T) -> T, timeout: Long) { updateCache(key, valueType, defaultValue, onUpdate, timeout, TimeUnit.SECONDS) } - fun updateCache( - key: String, - valueType: Class?, - defaultValue: T, - onUpdate: (T)->T, - timeout: Long, - timeUnit: TimeUnit - ) { + fun updateCache(key: String, valueType: Class?, defaultValue: T, onUpdate: (T) -> T, timeout: Long, timeUnit: TimeUnit) { var result: T try { synchronized(RedisCache::class.java) { @@ -273,7 +265,9 @@ class RedisCache( // Redisson、Jedis、Lettuce val cause = e.cause if (cause == null || !StringUtils.containsAny( - cause.message, "unknown command", "not support" + cause.message, + "unknown command", + "not support", ) ) { throw e @@ -284,7 +278,9 @@ class RedisCache( } catch (e: RedisSystemException) { val cause = e.cause if (cause == null || !StringUtils.containsAny( - cause.message, "unknown command", "not support" + cause.message, + "unknown command", + "not support", ) ) { throw e @@ -362,7 +358,6 @@ class RedisCache( } } - private fun getJson(value: T): String? { val json: String try { diff --git a/src/main/kotlin/plus/maa/backend/repository/UserRepository.kt b/src/main/kotlin/plus/maa/backend/repository/UserRepository.kt index 5325dff8..33728867 100644 --- a/src/main/kotlin/plus/maa/backend/repository/UserRepository.kt +++ b/src/main/kotlin/plus/maa/backend/repository/UserRepository.kt @@ -16,10 +16,6 @@ interface UserRepository : MongoRepository { fun findByEmail(email: String): MaaUser? fun findByUserId(userId: String): MaaUser? - -} - -fun UserRepository.findByUsersId(userId: List): Map { - return findAllById(userId).associateBy { it.userId!! } } +fun UserRepository.findByUsersId(userId: List): Map = findAllById(userId).associateBy { it.userId!! } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/ArkLevel.kt b/src/main/kotlin/plus/maa/backend/repository/entity/ArkLevel.kt index 9e841118..7c2f3544 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/ArkLevel.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/ArkLevel.kt @@ -11,37 +11,28 @@ import java.time.LocalDateTime * @author john180 */ @Document("maa_level") -data class ArkLevel ( +data class ArkLevel( @Id val id: String? = null, val levelId: String? = null, - @Indexed val stageId: String? = null, - - //文件版本, 用于判断是否需要更新 + // 文件版本, 用于判断是否需要更新 val sha: String = "", - - //地图类型, 例: 主线、活动、危机合约 + // 地图类型, 例: 主线、活动、危机合约 var catOne: String? = null, - - //所属章节, 例: 怒号光明、寻昼行动 + // 所属章节, 例: 怒号光明、寻昼行动 var catTwo: String? = null, - - //地图ID, 例: 7-18、FC-1 + // 地图ID, 例: 7-18、FC-1 var catThree: String? = null, - - //地图名, 例: 冬逝、爱国者之死 + // 地图名, 例: 冬逝、爱国者之死 val name: String? = null, val width: Int = 0, val height: Int = 0, - // 只是服务器认为的当前版本地图是否开放 var isOpen: Boolean? = null, - // 非实际意义上的活动地图关闭时间,只是服务器认为的关闭时间 - var closeTime: LocalDateTime? = null - + var closeTime: LocalDateTime? = null, ) { companion object { // 暂时这么做,有机会用和类型分别处理成功、失败以及解析器未实现的情况 diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/CollectionMeta.kt b/src/main/kotlin/plus/maa/backend/repository/entity/CollectionMeta.kt index cc491cdf..2f001076 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/CollectionMeta.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/CollectionMeta.kt @@ -9,5 +9,8 @@ import java.io.Serializable * @author dragove * created on 2023-12-27 */ -data class CollectionMeta(val idGetter: (T) -> Long, val incIdField: String, val entityClass: Class) : - Serializable +data class CollectionMeta( + val idGetter: (T) -> Long, + val incIdField: String, + val entityClass: Class, +) : Serializable diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/CommentsArea.kt b/src/main/kotlin/plus/maa/backend/repository/entity/CommentsArea.kt index 303e769c..2f8904fe 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/CommentsArea.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/CommentsArea.kt @@ -14,36 +14,22 @@ import java.time.LocalDateTime class CommentsArea( @Id var id: String? = null, - @Indexed val copilotId: Long, - // 答复某个评论 val fromCommentId: String? = null, - val uploaderId: String, - // 评论内容 var message: String, - var likeCount: Long = 0, - var dislikeCount: Long = 0, - val uploadTime: LocalDateTime = LocalDateTime.now(), - // 是否将该评论置顶 var topping: Boolean = false, - var delete: Boolean = false, - var deleteTime: LocalDateTime? = null, - // 其主评论id(如果自身为主评论则为null) val mainCommentId: String? = null, - // 邮件通知 - var notification: Boolean = false + var notification: Boolean = false, ) : Serializable - - diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/Copilot.kt b/src/main/kotlin/plus/maa/backend/repository/entity/Copilot.kt index a86bc637..2f41defc 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/Copilot.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/Copilot.kt @@ -19,120 +19,88 @@ import java.time.LocalDateTime class Copilot( @Id var id: String? = null, - // 自增数字ID @Indexed(unique = true) var copilotId: Long? = null, - // 关卡名 @Indexed var stageName: String? = null, - // 上传者id var uploaderId: String? = null, - // 查看次数 var views: Long = 0L, - - //评级 + // 评级 var ratingLevel: Int = 0, - - //评级比率 十分之一代表半星 + // 评级比率 十分之一代表半星 var ratingRatio: Double = 0.0, - var likeCount: Long = 0, - var dislikeCount: Long = 0, - // 热度 var hotScore: Double = 0.0, - // 难度 var difficulty: Int = 0, - // 版本号(文档中说明:最低要求 maa 版本号,必选。保留字段) var minimumRequired: String? = null, - // 指定干员 var opers: List? = null, - // 群组 var groups: List? = null, - // 战斗中的操作 var actions: List? = null, - // 描述 var doc: Doc?, - var firstUploadTime: LocalDateTime? = null, var uploadTime: LocalDateTime? = null, - // 原始数据 var content: String? = null, - @JsonIgnore var delete: Boolean = false, - @JsonIgnore var deleteTime: LocalDateTime? = null, - @JsonIgnore - var notification: Boolean? = null + var notification: Boolean? = null, ) : Serializable { - @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) - data class OperationGroup ( + data class OperationGroup( // 干员名 var name: String? = null, - // 技能序号。可选,默认 1 var skill: Int = 1, - // 技能用法。可选,默认 0 - var skillUsage: Int = 0 - - ): Serializable + var skillUsage: Int = 0, + ) : Serializable @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) - data class Operators ( + data class Operators( // 干员名 var name: String? = null, - // 技能序号。可选,默认 1 var skill: Int = 1, - // 技能用法。可选,默认 0 var skillUsage: Int = 0, - var requirements: Requirements = Requirements() - ): Serializable { - + var requirements: Requirements = Requirements(), + ) : Serializable { @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) - data class Requirements ( + data class Requirements( // 精英化等级。可选,默认为 0, 不要求精英化等级 var elite: Int = 0, - // 干员等级。可选,默认为 0 var level: Int = 0, - // 技能等级。可选,默认为 0 var skillLevel: Int = 0, - // 模组编号。可选,默认为 0 var module: Int = 0, - // 潜能要求。可选,默认为 0 - var potentiality: Int = 0 - ): Serializable + var potentiality: Int = 0, + ) : Serializable } @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) data class Groups( // 群组名 var name: String? = null, - val opers: List? = null, - var operators: List? = null + var operators: List? = null, ) : Serializable @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) @@ -142,33 +110,24 @@ class Copilot( var kills: Int? = 0, var costs: Int? = 0, var costChanges: Int? = 0, - // 默认 -1 var cooling: Int? = -1, - var name: String? = null, - // 部署干员的位置。 var location: Array?, - // 部署干员的干员朝向 中英文皆可 var direction: String? = "None", - // 修改技能用法。当 type 为 "技能用法" 时必选 var skillUsage: Int? = 0, - // 前置延时 var preDelay: Int? = 0, - // 后置延时 var postDelay: Int? = 0, - // maa:保留字段,暂未实现 var timeout: Int? = 0, - // 描述 var doc: String? = "", - var docColor: String? = "Gray" + var docColor: String? = "Gray", ) : Serializable @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) @@ -176,14 +135,16 @@ class Copilot( var title: String, var titleColor: String? = "Gray", var details: String? = "", - var detailsColor: String? = "Gray" + var detailsColor: String? = "Gray", ) : Serializable companion object { @Transient - val META: CollectionMeta = CollectionMeta( - { obj: Copilot -> obj.copilotId!! }, - "copilotId", Copilot::class.java - ) + val META: CollectionMeta = + CollectionMeta( + { obj: Copilot -> obj.copilotId!! }, + "copilotId", + Copilot::class.java, + ) } } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/CopilotSet.kt b/src/main/kotlin/plus/maa/backend/repository/entity/CopilotSet.kt index 8980d296..dc1d49a4 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/CopilotSet.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/CopilotSet.kt @@ -20,59 +20,47 @@ data class CopilotSet( /** * 作业集id */ - @field:Id - val id: Long = 0, - + @field:Id val id: Long = 0, /** * 作业集名称 */ var name: String, - /** * 额外描述 */ var description: String, - /** * 作业id列表 * 使用 list 保证有序 * 作业添加时应当保证唯一 */ override var copilotIds: MutableList, - /** * 上传者id */ val creatorId: String, - /** * 创建时间 */ val createTime: LocalDateTime, - /** * 更新时间 */ var updateTime: LocalDateTime, - /** * 作业状态 * [plus.maa.backend.service.model.CopilotSetStatus] */ var status: CopilotSetStatus, - - @field:JsonIgnore - var delete: Boolean = false, - - @field:JsonIgnore - var deleteTime: LocalDateTime? = null - + @field:JsonIgnore var delete: Boolean = false, + @field:JsonIgnore var deleteTime: LocalDateTime? = null, ) : Serializable, CopilotSetType { companion object { @field:Transient val meta = CollectionMeta( { obj: CopilotSet -> obj.id }, - "id", CopilotSet::class.java + "id", + CopilotSet::class.java, ) } } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/MaaUser.kt b/src/main/kotlin/plus/maa/backend/repository/entity/MaaUser.kt index cda7b5f2..88a55a13 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/MaaUser.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/MaaUser.kt @@ -16,12 +16,11 @@ data class MaaUser( @Id val userId: String? = null, var userName: String, - @Indexed(unique = true) val email: String, var password: String, var status: Int = 0, - var refreshJwtIds: MutableList = ArrayList() + var refreshJwtIds: MutableList = ArrayList(), ) : Serializable { companion object { @@ -29,7 +28,7 @@ data class MaaUser( val UNKNOWN: MaaUser = MaaUser( userName = "未知用户:(", email = "unknown@unkown.unkown", - password = "unknown" + password = "unknown", ) } } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/Rating.kt b/src/main/kotlin/plus/maa/backend/repository/entity/Rating.kt index 2e977f84..c3a9fa6f 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/Rating.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/Rating.kt @@ -8,24 +8,39 @@ import plus.maa.backend.service.model.RatingType import java.time.LocalDateTime /** - * @author lixuhuilll + * [type], [key], [userId] 组成复合索引,一个用户对一个对象只能有一种评级 + * * Date 2023-08-20 11:20 + * @author lixuhuilll */ @Document(collection = "maa_rating") // 复合索引 @CompoundIndexes(CompoundIndex(name = "idx_rating", def = "{'type': 1, 'key': 1, 'userId': 1}", unique = true)) data class Rating( @Id val id: String? = null, - - // 下面三个字段组成复合索引,一个用户对一个对象只能有一种评级 - val type: KeyType, // 评级的类型,如作业(copilot)、评论(comment) - val key: String, // 被评级对象的唯一标识,如作业id、评论id - val userId: String, // 评级的用户id - - var rating: RatingType, // 评级,如 "Like"、"Dislike"、"None" - var rateTime: LocalDateTime // 评级时间 + /** + * 评级的类型,如作业(copilot)、评论(comment) + */ + val type: KeyType, + /** + * 被评级对象的唯一标识,如作业id、评论id + */ + val key: String, + /** + * 评级的用户id + */ + val userId: String, + /** + * 评级,如 "Like"、"Dislike"、"None" + */ + var rating: RatingType, + /** + * 评级时间 + */ + var rateTime: LocalDateTime, ) { enum class KeyType { - COPILOT, COMMENT + COPILOT, + COMMENT, } } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkActivity.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkActivity.kt index 1f65c8b0..ecdbb3f3 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkActivity.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkActivity.kt @@ -1,7 +1,6 @@ package plus.maa.backend.repository.entity.gamedata - data class ArkActivity( val id: String, - val name: String + val name: String, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCharacter.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCharacter.kt index 8457fdd9..11f5ae0f 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCharacter.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCharacter.kt @@ -1,9 +1,9 @@ package plus.maa.backend.repository.entity.gamedata -data class ArkCharacter ( +data class ArkCharacter( val name: String, val profession: String, - val rarity: Int + val rarity: Int, ) { var id: String? = null } diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCrisisV2Info.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCrisisV2Info.kt index 429634d6..b3e55a2a 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCrisisV2Info.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkCrisisV2Info.kt @@ -1,10 +1,9 @@ package plus.maa.backend.repository.entity.gamedata -data class ArkCrisisV2Info ( +data class ArkCrisisV2Info( val seasonId: String, val name: String, - // 时间戳,单位:秒 val startTs: Long, - val endTs: Long + val endTs: Long, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkStage.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkStage.kt index 4d29f519..8af60b95 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkStage.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkStage.kt @@ -6,19 +6,16 @@ data class ArkStage( * 例: Activities/ACT5D0/level_act5d0_ex08 */ val levelId: String?, - /** * 例: act14d7_zone2 */ val zoneId: String, - /** * 例: act5d0_ex08 */ val stageId: String, - /** * 例: CB-EX8 */ - val code: String -) \ No newline at end of file + val code: String, +) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkTower.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkTower.kt index 4842e555..4e3bc725 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkTower.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkTower.kt @@ -3,5 +3,5 @@ package plus.maa.backend.repository.entity.gamedata data class ArkTower( val id: String, val name: String, - val subName: String + val subName: String, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkZone.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkZone.kt index a58c0848..3d4b0855 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkZone.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/ArkZone.kt @@ -5,14 +5,12 @@ data class ArkZone( * 例: main_1 */ val zoneID: String, - /** * 例: 第一章 */ val zoneNameFirst: String?, - /** * 例: 黑暗时代·下 */ - val zoneNameSecond: String? + val zoneNameSecond: String?, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/MaaArkStage.kt b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/MaaArkStage.kt index 2519a615..3318c8ea 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/MaaArkStage.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/gamedata/MaaArkStage.kt @@ -13,9 +13,8 @@ data class MaaArkStage( * 例: CB-EX8 */ val code: String, - /** * 例: act5d0_ex08 */ - val stageId: String? + val stageId: String?, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubCommit.kt b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubCommit.kt index 10110ddf..b8ff6341 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubCommit.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubCommit.kt @@ -4,5 +4,5 @@ package plus.maa.backend.repository.entity.github * @author john180 */ data class GithubCommit( - val sha: String + val sha: String, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubContent.kt b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubContent.kt index b0ace716..f10518ea 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubContent.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubContent.kt @@ -7,25 +7,19 @@ package plus.maa.backend.repository.entity.github data class GithubContent( // 文件名 val name: String, - // 路径 val path: String, val sha: String, - // 文件大小(Byte) val size: Long, - // 路径类型 file-文件 dir-目录 val type: String, - // 下载地址 val downloadUrl: String?, - // 访问地址 val htmlUrl: String, - // 对应commit地址 - val gitUrl: String + val gitUrl: String, ) { val isFile: Boolean /** diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTree.kt b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTree.kt index 97595811..b020144a 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTree.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTree.kt @@ -3,10 +3,10 @@ package plus.maa.backend.repository.entity.github /** * @author john180 */ -data class GithubTree ( +data class GithubTree( val path: String, val mode: String, val type: String, val sha: String, - val url: String? + val url: String?, ) diff --git a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTrees.kt b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTrees.kt index 2b3047df..acbee1ae 100644 --- a/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTrees.kt +++ b/src/main/kotlin/plus/maa/backend/repository/entity/github/GithubTrees.kt @@ -3,7 +3,7 @@ package plus.maa.backend.repository.entity.github /** * @author john180 */ -class GithubTrees ( +class GithubTrees( val sha: String, val url: String, val tree: List, diff --git a/src/main/kotlin/plus/maa/backend/service/ArkGameDataService.kt b/src/main/kotlin/plus/maa/backend/service/ArkGameDataService.kt index 1de9285b..314faaaf 100644 --- a/src/main/kotlin/plus/maa/backend/service/ArkGameDataService.kt +++ b/src/main/kotlin/plus/maa/backend/service/ArkGameDataService.kt @@ -8,8 +8,13 @@ import okhttp3.OkHttpClient import okhttp3.Request import org.springframework.stereotype.Service import plus.maa.backend.common.utils.ArkLevelUtil -import plus.maa.backend.repository.entity.gamedata.* -import java.util.* +import plus.maa.backend.repository.entity.gamedata.ArkActivity +import plus.maa.backend.repository.entity.gamedata.ArkCharacter +import plus.maa.backend.repository.entity.gamedata.ArkCrisisV2Info +import plus.maa.backend.repository.entity.gamedata.ArkStage +import plus.maa.backend.repository.entity.gamedata.ArkTower +import plus.maa.backend.repository.entity.gamedata.ArkZone +import java.util.Locale import java.util.concurrent.ConcurrentHashMap private val log = KotlinLogging.logger {} @@ -18,8 +23,9 @@ private val log = KotlinLogging.logger {} * @author john180 */ @Service -class ArkGameDataService(private val okHttpClient: OkHttpClient) { - +class ArkGameDataService( + private val okHttpClient: OkHttpClient, +) { companion object { private const val ARK_STAGE = "https://raw.githubusercontent.com/yuanyan3060/ArknightsGameResource/main/gamedata/excel/stage_table.json" @@ -35,8 +41,7 @@ class ArkGameDataService(private val okHttpClient: OkHttpClient) { "https://raw.githubusercontent.com/yuanyan3060/ArknightsGameResource/main/gamedata/excel/crisis_v2_table.json" } - private final val mapper = jacksonObjectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + private final val mapper = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) private val stageMap = ConcurrentHashMap() private val levelStageMap = ConcurrentHashMap() private val zoneMap = ConcurrentHashMap() @@ -46,12 +51,7 @@ class ArkGameDataService(private val okHttpClient: OkHttpClient) { private val arkCrisisV2InfoMap = ConcurrentHashMap() fun syncGameData(): Boolean { - return syncStage() && - syncZone() && - syncActivity() && - syncCharacter() && - syncTower() && - syncCrisisV2Info() + return syncStage() && syncZone() && syncActivity() && syncCharacter() && syncTower() && syncCrisisV2Info() } fun findStage(levelId: String, code: String, stageId: String): ArkStage? { @@ -77,7 +77,6 @@ class ArkGameDataService(private val okHttpClient: OkHttpClient) { fun findTower(zoneId: String) = arkTowerMap[zoneId] - fun findCharacter(characterId: String): ArkCharacter? { val ids = characterId.split("_") return arkCharacterMap[ids[ids.size - 1]] @@ -249,8 +248,7 @@ class ArkGameDataService(private val okHttpClient: OkHttpClient) { } val node = mapper.reader().readTree(body.string()) val crisisV2InfoNode = node.get("seasonInfoDataMap") - val crisisV2InfoMap = - mapper.convertValue(crisisV2InfoNode, object : TypeReference>() {}) + val crisisV2InfoMap = mapper.convertValue(crisisV2InfoNode, object : TypeReference>() {}) val temp = ConcurrentHashMap() crisisV2InfoMap.forEach { (k, v) -> temp[ArkLevelUtil.getKeyInfoById(k)] = v } arkCrisisV2InfoMap.clear() diff --git a/src/main/kotlin/plus/maa/backend/service/ArkLevelParserService.kt b/src/main/kotlin/plus/maa/backend/service/ArkLevelParserService.kt index 40eeeb1b..47bd955e 100644 --- a/src/main/kotlin/plus/maa/backend/service/ArkLevelParserService.kt +++ b/src/main/kotlin/plus/maa/backend/service/ArkLevelParserService.kt @@ -15,7 +15,6 @@ private val log = KotlinLogging.logger { } */ @Service class ArkLevelParserService(private val parsers: List) { - /** * 具体地图信息生成规则见 * [GameDataParser](https://github.com/MaaAssistantArknights/MaaCopilotServer/blob/main/src/MaaCopilotServer.GameData/GameDataParser.cs) @@ -44,7 +43,7 @@ class ArkLevelParserService(private val parsers: List) { } val parser = parsers.firstOrNull { it.supportType(type) } if (parser == null) { - //类型存在但无对应Parser直接跳过 + // 类型存在但无对应Parser直接跳过 return ArkLevel.EMPTY } return parser.parseLevel(level, tilePos) diff --git a/src/main/kotlin/plus/maa/backend/service/ArkLevelService.kt b/src/main/kotlin/plus/maa/backend/service/ArkLevelService.kt index 48294434..ee67fc0c 100644 --- a/src/main/kotlin/plus/maa/backend/service/ArkLevelService.kt +++ b/src/main/kotlin/plus/maa/backend/service/ArkLevelService.kt @@ -3,7 +3,11 @@ package plus.maa.backend.service import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import io.github.oshai.kotlinlogging.KotlinLogging -import okhttp3.* +import okhttp3.Call +import okhttp3.Callback +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response import org.springframework.beans.factory.annotation.Value import org.springframework.cache.annotation.Cacheable import org.springframework.data.domain.Pageable @@ -29,7 +33,6 @@ import java.nio.charset.StandardCharsets import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId -import java.util.* import java.util.concurrent.atomic.AtomicInteger private val log = KotlinLogging.logger { } @@ -43,19 +46,15 @@ class ArkLevelService( /** * GitHub api调用token 从 [tokens](https://github.com/settings/tokens) 获取 */ - @Value("\${maa-copilot.github.token:}") - private val githubToken: String, + @Value("\${maa-copilot.github.token:}") private val githubToken: String, /** * maa 主仓库,一般不变 */ - @Value("\${maa-copilot.github.repo:MaaAssistantArknights/MaaAssistantArknights/dev}") - private val maaRepoAndBranch: String, + @Value("\${maa-copilot.github.repo:MaaAssistantArknights/MaaAssistantArknights/dev}") private val maaRepoAndBranch: String, /** * 地图数据所在路径 */ - @Value("\${maa-copilot.github.repo.tile.path:resource/Arknights-Tile-Pos}") - private val tilePosPath: String, - + @Value("\${maa-copilot.github.repo.tile.path:resource/Arknights-Tile-Pos}") private val tilePosPath: String, private val githubRepo: GithubRepository, private val redisCache: RedisCache, private val arkLevelRepo: ArkLevelRepository, @@ -63,20 +62,16 @@ class ArkLevelService( private val gameDataService: ArkGameDataService, private val mapper: ObjectMapper, private val okHttpClient: OkHttpClient, - private val arkLevelConverter: ArkLevelConverter + private val arkLevelConverter: ArkLevelConverter, ) { private val bypassFileNames = listOf("overview.json") @get:Cacheable("arkLevelInfos") val arkLevelInfos: List - get() = arkLevelRepo.findAll() - .map { arkLevel -> arkLevelConverter.convert(arkLevel) } - .toList() + get() = arkLevelRepo.findAll().map { arkLevel -> arkLevelConverter.convert(arkLevel) }.toList() @Cacheable("arkLevel") - fun findByLevelIdFuzzy(levelId: String): ArkLevel? { - return arkLevelRepo.findByLevelIdFuzzy(levelId).firstOrNull() - } + fun findByLevelIdFuzzy(levelId: String): ArkLevel? = arkLevelRepo.findByLevelIdFuzzy(levelId).firstOrNull() fun queryLevelInfosByKeyword(keyword: String): List { val levels = arkLevelRepo.queryLevelByKeyword(keyword).toList() @@ -89,24 +84,24 @@ class ArkLevelService( @Async fun runSyncLevelDataTask() { log.info { "[LEVEL]开始同步地图数据" } - //获取地图文件夹最新的commit, 用于判断是否需要更新 + // 获取地图文件夹最新的commit, 用于判断是否需要更新 val commits = githubRepo.getCommits(githubToken) if (commits.isEmpty()) { log.info { "[LEVEL]获取地图数据最新commit失败" } return } - //与缓存的commit比较,如果相同则不更新 + // 与缓存的commit比较,如果相同则不更新 val commit = commits[0] val lastCommit = redisCache.cacheLevelCommit if (lastCommit != null && lastCommit == commit.sha) { log.info { "[LEVEL]地图数据已是最新" } return } - //获取根目录文件列表 + // 获取根目录文件列表 var trees: GithubTrees? val files = tilePosPath.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().toList() trees = githubRepo.getTrees(githubToken, commit.sha) - //根据路径获取文件列表 + // 根据路径获取文件列表 for (file in files) { if (trees == null || trees.tree.isEmpty()) { log.info { "[LEVEL]地图数据获取失败" } @@ -123,35 +118,30 @@ class ArkLevelService( log.info { "[LEVEL]地图数据获取失败, 未找到文件夹$tilePosPath" } return } - //根据后缀筛选地图文件列表 - val levelTrees = trees.tree - .filter { t: GithubTree -> t.type == "blob" && t.path.endsWith(".json") } - .toMutableList() + // 根据后缀筛选地图文件列表 + val levelTrees = trees.tree.filter { t: GithubTree -> t.type == "blob" && t.path.endsWith(".json") }.toMutableList() log.info { "[LEVEL]已发现${levelTrees.size}份地图数据" } - //根据sha筛选无需更新的地图 + // 根据sha筛选无需更新的地图 val shaList = arkLevelRepo.findAllShaBy().map { obj: ArkLevelSha -> obj.sha }.toList() levelTrees.removeIf { t: GithubTree -> shaList.contains(t.sha) } // 排除overview文件、肉鸽、训练关卡和 Guide? 不知道是啥 levelTrees.removeIf { t: GithubTree -> - t.path == "overview.json" || - t.path.contains("roguelike") || - t.path.startsWith("tr_") || - t.path.startsWith("guide_") + t.path == "overview.json" || t.path.contains("roguelike") || t.path.startsWith("tr_") || t.path.startsWith("guide_") } levelTrees.removeIf { t: GithubTree -> t.path.contains("roguelike") } log.info { "[LEVEL]${levelTrees.size}份地图数据需要更新" } if (levelTrees.isEmpty()) { return } - //同步GameData仓库数据 + // 同步GameData仓库数据 if (!gameDataService.syncGameData()) { log.error { "[LEVEL]GameData仓库数据同步失败" } return } val task = DownloadTask(total = levelTrees.size, finishCallback = { t: DownloadTask -> - //仅在全部下载任务成功后更新commit缓存 + // 仅在全部下载任务成功后更新commit缓存 if (t.isAllSuccess) { redisCache.cacheLevelCommit = commit.sha } @@ -184,60 +174,56 @@ class ArkLevelService( if (stages.downloadUrl == null) { return } - okHttpClient - .newCall(Request.Builder().url(stages.downloadUrl).build()) - .execute().use { response -> - val body = response.body?.byteStream() - if (!response.isSuccessful || body == null) { - log.error { "[ACTIVITIES-OPEN-STATUS]活动地图开放状态下载失败" } - return - } - val stagesList = mapper.readValue(body, object : TypeReference>() {}) - - val keyInfos = stagesList - .map { it.stageId } // 提取地图系列的唯一标识 - .map { id: String? -> ArkLevelUtil.getKeyInfoById(id) } - .toSet() - - // 修改活动地图 - val catOne = ArkLevelType.ACTIVITIES.display - // 分页修改 - var pageable = Pageable.ofSize(1000) - var arkLevelPage = arkLevelRepo.findAllByCatOne(catOne, pageable) - - // 获取当前时间 - val nowTime = LocalDateTime.now() - - while (arkLevelPage.hasContent()) { - arkLevelPage.forEach { arkLevel: ArkLevel -> - // 只考虑地图系列的唯一标识 - if (keyInfos.contains(ArkLevelUtil.getKeyInfoById(arkLevel.stageId))) { - arkLevel.isOpen = true - // 如果一个旧地图重新开放,关闭时间也需要另算 - arkLevel.closeTime = null - } else if (arkLevel.isOpen != null) { - // 数据可能存在部分缺失,因此地图此前必须被匹配过,才会认为其关闭 - arkLevel.isOpen = false - // 不能每天都变更关闭时间 - if (arkLevel.closeTime == null) { - arkLevel.closeTime = nowTime - } + okHttpClient.newCall(Request.Builder().url(stages.downloadUrl).build()).execute().use { response -> + val body = response.body?.byteStream() + if (!response.isSuccessful || body == null) { + log.error { "[ACTIVITIES-OPEN-STATUS]活动地图开放状态下载失败" } + return + } + val stagesList = mapper.readValue(body, object : TypeReference>() {}) + + val keyInfos = stagesList.map { it.stageId } // 提取地图系列的唯一标识 + .map { id: String? -> ArkLevelUtil.getKeyInfoById(id) }.toSet() + + // 修改活动地图 + val catOne = ArkLevelType.ACTIVITIES.display + // 分页修改 + var pageable = Pageable.ofSize(1000) + var arkLevelPage = arkLevelRepo.findAllByCatOne(catOne, pageable) + + // 获取当前时间 + val nowTime = LocalDateTime.now() + + while (arkLevelPage.hasContent()) { + arkLevelPage.forEach { arkLevel: ArkLevel -> + // 只考虑地图系列的唯一标识 + if (keyInfos.contains(ArkLevelUtil.getKeyInfoById(arkLevel.stageId))) { + arkLevel.isOpen = true + // 如果一个旧地图重新开放,关闭时间也需要另算 + arkLevel.closeTime = null + } else if (arkLevel.isOpen != null) { + // 数据可能存在部分缺失,因此地图此前必须被匹配过,才会认为其关闭 + arkLevel.isOpen = false + // 不能每天都变更关闭时间 + if (arkLevel.closeTime == null) { + arkLevel.closeTime = nowTime } } + } - arkLevelRepo.saveAll(arkLevelPage) + arkLevelRepo.saveAll(arkLevelPage) - if (!arkLevelPage.hasNext()) { - // 没有下一页了,跳出循环 - break - } - pageable = arkLevelPage.nextPageable() - arkLevelPage = arkLevelRepo.findAllByCatOne(catOne, pageable) + if (!arkLevelPage.hasNext()) { + // 没有下一页了,跳出循环 + break } - - redisCache.setData("level:stages:sha", stages.sha) - log.info { "[ACTIVITIES-OPEN-STATUS]活动地图开放状态更新完成" } + pageable = arkLevelPage.nextPageable() + arkLevelPage = arkLevelRepo.findAllByCatOne(catOne, pageable) } + + redisCache.setData("level:stages:sha", stages.sha) + log.info { "[ACTIVITIES-OPEN-STATUS]活动地图开放状态更新完成" } + } } catch (e: Exception) { log.error(e) { "[ACTIVITIES-OPEN-STATUS]活动地图开放状态更新失败" } } @@ -296,36 +282,38 @@ class ArkLevelService( return } val url = String.format("https://raw.githubusercontent.com/%s/%s/%s", maaRepoAndBranch, tilePosPath, fileName) - okHttpClient.newCall(Request.Builder().url(url).build()).enqueue(object : Callback { - override fun onFailure(call: Call, e: IOException) { - log.error(e) { "[LEVEL]下载地图数据失败:" + tree.path } - } + okHttpClient.newCall(Request.Builder().url(url).build()).enqueue( + object : Callback { + override fun onFailure(call: Call, e: IOException) { + log.error(e) { "[LEVEL]下载地图数据失败:" + tree.path } + } - @Throws(IOException::class) - override fun onResponse(call: Call, response: Response) { - response.body.use { rspBody -> - if (!response.isSuccessful || rspBody == null) { - task.fail() - log.error { "[LEVEL]下载地图数据失败:" + tree.path } - return - } - val tilePos = mapper.readValue(rspBody.string(), ArkTilePos::class.java) - val level = parserService.parseLevel(tilePos, tree.sha) - if (level == null) { - task.fail() - log.info { "[LEVEL]地图数据解析失败:" + tree.path } - return - } else if (level === ArkLevel.EMPTY) { - task.pass() - return - } - arkLevelRepo.save(level) + @Throws(IOException::class) + override fun onResponse(call: Call, response: Response) { + response.body.use { rspBody -> + if (!response.isSuccessful || rspBody == null) { + task.fail() + log.error { "[LEVEL]下载地图数据失败:" + tree.path } + return + } + val tilePos = mapper.readValue(rspBody.string(), ArkTilePos::class.java) + val level = parserService.parseLevel(tilePos, tree.sha) + if (level == null) { + task.fail() + log.info { "[LEVEL]地图数据解析失败:" + tree.path } + return + } else if (level === ArkLevel.EMPTY) { + task.pass() + return + } + arkLevelRepo.save(level) - task.success() - log.info { "[LEVEL]下载地图数据 ${tilePos.name} 成功, 进度${task.current}/${task.total}, 用时:${task.duration}s" } + task.success() + log.info { "[LEVEL]下载地图数据 ${tilePos.name} 成功, 进度${task.current}/${task.total}, 用时:${task.duration}s" } + } } - } - }) + }, + ) } private class DownloadTask( @@ -334,7 +322,7 @@ class ArkLevelService( private val fail: AtomicInteger = AtomicInteger(0), private val pass: AtomicInteger = AtomicInteger(0), val total: Int = 0, - private val finishCallback: ((DownloadTask) -> Unit) + private val finishCallback: ((DownloadTask) -> Unit), ) { fun success() { success.incrementAndGet() diff --git a/src/main/kotlin/plus/maa/backend/service/CommentsAreaService.kt b/src/main/kotlin/plus/maa/backend/service/CommentsAreaService.kt index 8b75568c..2391c0a4 100644 --- a/src/main/kotlin/plus/maa/backend/service/CommentsAreaService.kt +++ b/src/main/kotlin/plus/maa/backend/service/CommentsAreaService.kt @@ -59,7 +59,7 @@ class CommentsAreaService( fromCommentId = parentComment?.id, mainCommentId = parentComment?.run { mainCommentId ?: id }, message = commentsAddDTO.message, - notification = commentsAddDTO.notification + notification = commentsAddDTO.notification, ) commentsAreaRepository.insert(comment) } @@ -110,14 +110,14 @@ class CommentsAreaService( val rating = ratingRepository.findByTypeAndKeyAndUserId( Rating.KeyType.COMMENT, commentId, - userId + userId, ) ?: Rating( null, Rating.KeyType.COMMENT, commentId, userId, RatingType.NONE, - LocalDateTime.now() + LocalDateTime.now(), ) val prevType = rating.rating @@ -170,7 +170,7 @@ class CommentsAreaService( "hot" -> "likeCount" "id" -> "uploadTime" else -> request.orderBy ?: "likeCount" - } + }, ) val page = (request.page - 1).coerceAtLeast(0) val limit = if (request.limit > 0) request.limit else 10 @@ -183,30 +183,30 @@ class CommentsAreaService( request.justSeeId, delete = false, exists = false, - pageable = pageable + pageable = pageable, ) } else { commentsAreaRepository.findByCopilotIdAndDeleteAndMainCommentIdExists( request.copilotId, delete = false, exists = false, - pageable = pageable + pageable = pageable, ) } val mainCommentIds = mainCommentsPage.map(CommentsArea::id).filterNotNull() - //获取子评论 + // 获取子评论 val subCommentsList = commentsAreaRepository.findByMainCommentIdIn(mainCommentIds).onEach { - //将已删除评论内容替换为空 + // 将已删除评论内容替换为空 if (it.delete) it.message = "" } - //获取所有评论用户 + // 获取所有评论用户 val allUserIds = (mainCommentsPage + subCommentsList).map(CommentsArea::uploaderId).distinct() val users = userRepository.findAllById(allUserIds).associateBy(MaaUser::userId) val subCommentGroups = subCommentsList.groupBy(CommentsArea::mainCommentId) - //转换主评论数据并填充用户名 + // 转换主评论数据并填充用户名 val commentsInfos = mainCommentsPage.toList().map { mainComment -> val subCommentsInfos = (subCommentGroups[mainComment.id] ?: emptyList()).map { c -> buildSubCommentsInfo(c, users[c.uploaderId] ?: MaaUser.UNKNOWN) @@ -218,7 +218,7 @@ class CommentsAreaService( hasNext = mainCommentsPage.hasNext(), page = mainCommentsPage.totalPages, total = mainCommentsPage.totalElements, - data = commentsInfos + data = commentsInfos, ) } @@ -235,7 +235,7 @@ class CommentsAreaService( dislike = c.dislikeCount, fromCommentId = c.fromCommentId!!, mainCommentId = c.mainCommentId!!, - deleted = c.delete + deleted = c.delete, ) private fun buildMainCommentsInfo(c: CommentsArea, user: MaaUser, subList: List) = CommentsInfo( @@ -247,7 +247,7 @@ class CommentsAreaService( like = c.likeCount, dislike = c.dislikeCount, topping = c.topping, - subCommentsInfos = subList + subCommentsInfos = subList, ) fun notificationStatus(userId: String, id: String, status: Boolean) { diff --git a/src/main/kotlin/plus/maa/backend/service/CopilotService.kt b/src/main/kotlin/plus/maa/backend/service/CopilotService.kt index 65d0f263..7ca6ddc9 100644 --- a/src/main/kotlin/plus/maa/backend/service/CopilotService.kt +++ b/src/main/kotlin/plus/maa/backend/service/CopilotService.kt @@ -26,17 +26,22 @@ import plus.maa.backend.controller.response.MaaResultException import plus.maa.backend.controller.response.copilot.ArkLevelInfo import plus.maa.backend.controller.response.copilot.CopilotInfo import plus.maa.backend.controller.response.copilot.CopilotPageInfo -import plus.maa.backend.repository.* +import plus.maa.backend.repository.CommentsAreaRepository +import plus.maa.backend.repository.CopilotRepository +import plus.maa.backend.repository.RatingRepository +import plus.maa.backend.repository.RedisCache +import plus.maa.backend.repository.UserRepository import plus.maa.backend.repository.entity.Copilot import plus.maa.backend.repository.entity.Copilot.OperationGroup import plus.maa.backend.repository.entity.Rating +import plus.maa.backend.repository.findByUsersId import plus.maa.backend.service.model.RatingCache import plus.maa.backend.service.model.RatingType import java.math.BigDecimal import java.math.RoundingMode import java.time.LocalDateTime import java.time.temporal.ChronoUnit -import java.util.* +import java.util.Objects import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference @@ -64,9 +69,8 @@ class CopilotService( private val userRepository: UserRepository, private val commentsAreaRepository: CommentsAreaRepository, private val properties: MaaCopilotProperties, - private val copilotConverter: CopilotConverter + private val copilotConverter: CopilotConverter, ) { - /** * 并修正前端的冗余部分 * @@ -121,11 +125,7 @@ class CopilotService( } } - - private fun caseInsensitive(s: String): Pattern { - return Pattern.compile(s, Pattern.CASE_INSENSITIVE) - } - + private fun caseInsensitive(s: String): Pattern = Pattern.compile(s, Pattern.CASE_INSENSITIVE) /** * 上传新的作业 @@ -138,7 +138,10 @@ class CopilotService( // 将其转换为数据库存储对象 val copilot = copilotConverter.toCopilot( copilotDTO, - idComponent.getId(Copilot.META), loginUserId, LocalDateTime.now(), content + idComponent.getId(Copilot.META), + loginUserId, + LocalDateTime.now(), + content, ) copilotRepository.insert(copilot) return copilot.copilotId!! @@ -152,10 +155,8 @@ class CopilotService( Assert.state(copilot.uploaderId == loginUserId, "您无法修改不属于您的作业") copilot.delete = true copilotRepository.save(copilot) - /* - * 删除作业时,如果被删除的项在 Redis 首页缓存中存在,则清空对应的首页缓存 - * 新增作业就不必,因为新作业显然不会那么快就登上热度榜和浏览量榜 - */ + // 删除作业时,如果被删除的项在 Redis 首页缓存中存在,则清空对应的首页缓存 + // 新增作业就不必,因为新作业显然不会那么快就登上热度榜和浏览量榜 for ((key1) in HOME_PAGE_CACHE_CONFIG) { val key = String.format("home:%s:copilotIds", key1) val pattern = String.format("home:%s:*", key1) @@ -175,9 +176,7 @@ class CopilotService( return copilotOptional?.let { copilot: Copilot -> // 60分钟内限制同一个用户对访问量的增加 val cache = redisCache.getCache("views:$userIdOrIpAddress", RatingCache::class.java) - if (Objects.isNull(cache) || Objects.isNull(cache!!.copilotIds) || - !cache.copilotIds.contains(id) - ) { + if (Objects.isNull(cache) || Objects.isNull(cache!!.copilotIds) || !cache.copilotIds.contains(id)) { val query = Query.query(Criteria.where("copilotId").`is`(id)) val update = Update() // 增加一次views @@ -187,11 +186,15 @@ class CopilotService( redisCache.setCache("views:$userIdOrIpAddress", RatingCache(Sets.newHashSet(id))) } else { redisCache.updateCache( - "views:$userIdOrIpAddress", RatingCache::class.java, cache, + "views:$userIdOrIpAddress", + RatingCache::class.java, + cache, { updateCache: RatingCache? -> updateCache!!.copilotIds.add(id) updateCache - }, 60, TimeUnit.MINUTES + }, + 60, + TimeUnit.MINUTES, ) } } @@ -200,11 +203,14 @@ class CopilotService( // 新评分系统 val ratingType = ratingRepository.findByTypeAndKeyAndUserId( Rating.KeyType.COPILOT, - copilot.copilotId.toString(), userIdOrIpAddress + copilot.copilotId.toString(), + userIdOrIpAddress, )?.rating formatCopilot( - copilot, ratingType, maaUser!!.userName, - commentsAreaRepository.countByCopilotIdAndDelete(copilot.copilotId!!, false) + copilot, + ratingType, + maaUser!!.userName, + commentsAreaRepository.countByCopilotIdAndDelete(copilot.copilotId!!, false), ) } } @@ -222,7 +228,10 @@ class CopilotService( val cacheKey = AtomicReference() val setKey = AtomicReference() // 只缓存默认状态下热度和访问量排序的结果,并且最多只缓存前三页 - if (request.page <= 3 && request.document == null && request.levelKeyword == null && request.uploaderId == null && request.operator == null && + if (request.page <= 3 && + request.document == null && + request.levelKeyword == null && + request.uploaderId == null && request.operator == null && request.copilotIds.isNullOrEmpty() ) { request.orderBy?.takeIf { orderBy -> orderBy.isNotBlank() } @@ -243,7 +252,7 @@ class CopilotService( "id" -> "copilotId" else -> request.orderBy } - } ?: "copilotId" + } ?: "copilotId", ) // 判断是否有值 无值则为默认 val page = if (request.page > 0) request.page else 1 @@ -260,8 +269,7 @@ class CopilotService( andQueries.add(Criteria.where("delete").`is`(false)) - - //关卡名、关卡类型、关卡编号 + // 关卡名、关卡类型、关卡编号 if (!request.levelKeyword.isNullOrBlank()) { val keyword = request.levelKeyword!! val levelInfo = levelService.queryLevelInfosByKeyword(keyword) @@ -270,8 +278,8 @@ class CopilotService( } else { andQueries.add( Criteria.where("stageName").`in`( - levelInfo.map { obj: ArkLevelInfo -> obj.stageId }.toSet() - ) + levelInfo.map { obj: ArkLevelInfo -> obj.stageId }.toSet(), + ), ) } } @@ -281,14 +289,13 @@ class CopilotService( andQueries.add(Criteria.where("copilotId").`in`(request.copilotIds!!)) } - //标题、描述、神秘代码 + // 标题、描述、神秘代码 if (!request.document.isNullOrBlank()) { orQueries.add(Criteria.where("doc.title").regex(caseInsensitive(request.document))) orQueries.add(Criteria.where("doc.details").regex(caseInsensitive(request.document))) } - - //包含或排除干员 + // 包含或排除干员 var oper = request.operator if (!oper.isNullOrBlank()) { oper = oper.replace("[“\"”]".toRegex(), "") @@ -305,7 +312,7 @@ class CopilotService( } } - //查看自己 + // 查看自己 if (StringUtils.isNotBlank(request.uploaderId)) { if ("me" == request.uploaderId) { if (!ObjectUtils.isEmpty(userId)) { @@ -338,17 +345,18 @@ class CopilotService( it.copilotId!! }.toSet() val maaUsers = userRepository.findByUsersId(copilots.map { it.uploaderId!! }.toList()) - val commentsCount = commentsAreaRepository.findByCopilotIdInAndDelete(copilotIds, false) - .groupBy { it.copilotId } - .mapValues { it.value.size.toLong() } + val commentsCount = commentsAreaRepository.findByCopilotIdInAndDelete(copilotIds, false).groupBy { + it.copilotId + }.mapValues { it.value.size.toLong() } // 新版评分系统 // 反正目前首页和搜索不会直接展示当前用户有没有点赞,干脆直接不查,要用户点进作业才显示自己是否点赞 val infos = copilots.map { copilot -> formatCopilot( - copilot, null, + copilot, + null, maaUsers[copilot.uploaderId]!!.userName, - commentsCount[copilot.copilotId] + commentsCount[copilot.copilotId], ) }.toList() @@ -404,7 +412,7 @@ class CopilotService( val ratingOptional = ratingRepository.findByTypeAndKeyAndUserId( Rating.KeyType.COPILOT, request.id.toString(), - userIdOrIpAddress + userIdOrIpAddress, ) // 如果评分存在则更新评分 if (ratingOptional != null) { @@ -432,7 +440,7 @@ class CopilotService( request.id.toString(), userIdOrIpAddress, RatingType.fromRatingType(rating), - LocalDateTime.now() + LocalDateTime.now(), ) ratingRepository.insert(newRating) @@ -443,9 +451,7 @@ class CopilotService( // 获取只包含评分的作业 var query = Query.query( - Criteria - .where("copilotId").`is`(request.id) - .and("delete").`is`(false) + Criteria.where("copilotId").`is`(request.id).and("delete").`is`(false), ) // 排除 _id,防止误 save 该不完整作业后原有数据丢失 query.fields().include("likeCount", "dislikeCount").exclude("_id") @@ -464,9 +470,7 @@ class CopilotService( val ratingLevel = bigDecimal.setScale(1, RoundingMode.HALF_UP).toDouble() // 更新数据 query = Query.query( - Criteria - .where("copilotId").`is`(request.id) - .and("delete").`is`(false) + Criteria.where("copilotId").`is`(request.id).and("delete").`is`(false), ) val update = Update() update["likeCount"] = likeCount @@ -479,7 +483,9 @@ class CopilotService( redisCache.incZSet( "rate:hot:copilotIds", request.id.toString(), - 1.0, 100, (3600 * 3).toLong() + 1.0, + 100, + (3600 * 3).toLong(), ) } @@ -487,13 +493,12 @@ class CopilotService( * 将数据库内容转换为前端所需格式

* 新版评分系统 */ - private fun formatCopilot( - copilot: Copilot, ratingType: RatingType?, userName: String, - commentsCount: Long? - ): CopilotInfo { + private fun formatCopilot(copilot: Copilot, ratingType: RatingType?, userName: String, commentsCount: Long?): CopilotInfo { val info = copilotConverter.toCopilotInfo( - copilot, userName, copilot.copilotId!!, - commentsCount + copilot, + userName, + copilot.copilotId!!, + commentsCount, ) info.ratingRatio = copilot.ratingRatio @@ -502,8 +507,7 @@ class CopilotService( info.ratingType = ratingType.display } // 评分数少于一定数量 - info.notEnoughRating = - copilot.likeCount + copilot.dislikeCount <= properties.copilot.minValueShowNotEnoughRating + info.notEnoughRating = copilot.likeCount + copilot.dislikeCount <= properties.copilot.minValueShowNotEnoughRating info.available = true @@ -526,11 +530,11 @@ class CopilotService( 首页分页查询缓存配置 格式为:需要缓存的 orderBy 类型(也就是榜单类型) -> 缓存时间 (Map.of()返回的是不可变对象,无需担心线程安全问题) - */ - private val HOME_PAGE_CACHE_CONFIG: Map = java.util.Map.of( - "hot", 3600 * 24L, - "views", 3600L, - "id", 300L + */ + private val HOME_PAGE_CACHE_CONFIG: Map = mapOf( + "hot" to 3600 * 24L, + "views" to 3600L, + "id" to 300L, ) @JvmStatic @@ -551,10 +555,9 @@ class CopilotService( base *= greatRate } // 上一周好评率 * (上一周评分数 / 10) * (浏览数 / 10) / 过去的周数 - val s = (greatRate * (copilot.views / 10.0) - * max((ups + downs) / 10.0, 1.0)) / pastedWeeks + val s = (greatRate * (copilot.views / 10.0) * max((ups + downs) / 10.0, 1.0)) / pastedWeeks val order = ln(max(s, 1.0)) return order + s / 1000.0 + base } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt b/src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt index b644929e..7e76595d 100644 --- a/src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt +++ b/src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt @@ -38,9 +38,8 @@ class CopilotSetService( private val converter: CopilotSetConverter, private val repository: CopilotSetRepository, private val userRepository: UserRepository, - private val mongoTemplate: MongoTemplate + private val mongoTemplate: MongoTemplate, ) { - private val defaultSort: Sort = Sort.by("id").descending() /** @@ -61,8 +60,7 @@ class CopilotSetService( * 往作业集中加入作业id列表 */ fun addCopilotIds(req: CopilotSetModCopilotsReq, userId: String) { - val copilotSet = repository.findById(req.id) - .orElseThrow { IllegalArgumentException("作业集不存在") } + val copilotSet = repository.findById(req.id).orElseThrow { IllegalArgumentException("作业集不存在") } Assert.state(copilotSet.creatorId == userId, "您不是该作业集的创建者,无权修改该作业集") copilotSet.copilotIds.addAll(req.copilotIds) copilotSet.copilotIds = copilotSet.distinctIdsAndCheck() @@ -73,8 +71,7 @@ class CopilotSetService( * 往作业集中删除作业id列表 */ fun removeCopilotIds(req: CopilotSetModCopilotsReq, userId: String) { - val copilotSet = repository.findById(req.id) - .orElseThrow { IllegalArgumentException("作业集不存在") } + val copilotSet = repository.findById(req.id).orElseThrow { IllegalArgumentException("作业集不存在") } Assert.state(copilotSet.creatorId == userId, "您不是该作业集的创建者,无权修改该作业集") val removeIds: Set = HashSet(req.copilotIds) copilotSet.copilotIds.removeIf { o: Long -> removeIds.contains(o) } @@ -85,8 +82,7 @@ class CopilotSetService( * 更新作业集信息 */ fun update(req: CopilotSetUpdateReq, userId: String) { - val copilotSet = repository.findById(req.id) - .orElseThrow { IllegalArgumentException("作业集不存在") } + val copilotSet = repository.findById(req.id).orElseThrow { IllegalArgumentException("作业集不存在") } Assert.state(copilotSet.creatorId == userId, "您不是该作业集的创建者,无权修改该作业集") copilotSet.name = req.name copilotSet.description = req.description @@ -102,8 +98,7 @@ class CopilotSetService( */ fun delete(id: Long, userId: String) { log.info { "delete copilot set for id: $id, userId: $userId" } - val copilotSet = repository.findById(id) - .orElseThrow { IllegalArgumentException("作业集不存在") } + val copilotSet = repository.findById(id).orElseThrow { IllegalArgumentException("作业集不存在") } Assert.state(copilotSet.creatorId == userId, "您不是该作业集的创建者,无权删除该作业集") copilotSet.delete = true copilotSet.deleteTime = LocalDateTime.now() @@ -133,22 +128,18 @@ class CopilotSetService( andList.add( Criteria().orOperator( Criteria.where("name").regex(pattern), - Criteria.where("description").regex(pattern) - ) + Criteria.where("description").regex(pattern), + ), ) } val query = Query.query(Criteria().andOperator(andList)).with(pageRequest) - val copilotSets = - PageableExecutionUtils.getPage(mongoTemplate.find(query, CopilotSet::class.java), pageRequest) { - mongoTemplate.count( - query.limit(-1).skip(-1), - CopilotSet::class.java - ) - } - val userIds = copilotSets - .map { obj: CopilotSet -> obj.creatorId } - .distinct() - .toList() + val copilotSets = PageableExecutionUtils.getPage(mongoTemplate.find(query, CopilotSet::class.java), pageRequest) { + mongoTemplate.count( + query.limit(-1).skip(-1), + CopilotSet::class.java, + ) + } + val userIds = copilotSets.map { obj: CopilotSet -> obj.creatorId }.distinct().toList() val userById = userRepository.findByUsersId(userIds) return CopilotSetPageRes( copilotSets.hasNext(), @@ -157,14 +148,12 @@ class CopilotSetService( copilotSets.map { cs: CopilotSet -> val user = userById.getOrDefault(cs.creatorId, MaaUser.UNKNOWN) converter.convert(cs, user.userName) - }.toList() + }.toList(), ) } - fun get(id: Long): CopilotSetRes { - return repository.findById(id).map { copilotSet: CopilotSet -> - val userName = (userRepository.findByUserId(copilotSet.creatorId) ?: MaaUser.UNKNOWN).userName - converter.convertDetail(copilotSet, userName) - }.orElseThrow { IllegalArgumentException("作业不存在") } - } + fun get(id: Long): CopilotSetRes = repository.findById(id).map { copilotSet: CopilotSet -> + val userName = (userRepository.findByUserId(copilotSet.creatorId) ?: MaaUser.UNKNOWN).userName + converter.convertDetail(copilotSet, userName) + }.orElseThrow { IllegalArgumentException("作业不存在") } } diff --git a/src/main/kotlin/plus/maa/backend/service/EmailService.kt b/src/main/kotlin/plus/maa/backend/service/EmailService.kt index 00b35988..fe1d4d4a 100644 --- a/src/main/kotlin/plus/maa/backend/service/EmailService.kt +++ b/src/main/kotlin/plus/maa/backend/service/EmailService.kt @@ -14,7 +14,7 @@ import plus.maa.backend.controller.response.MaaResultException import plus.maa.backend.repository.RedisCache import java.time.LocalDateTime import java.time.format.DateTimeFormatter -import java.util.* +import java.util.Locale /** * @author LoMu @@ -27,7 +27,7 @@ class EmailService( private val flagNoSend: Boolean = false, private val redisCache: RedisCache, @Resource(name = "emailTaskExecutor") - private val emailTaskExecutor: AsyncTaskExecutor + private val emailTaskExecutor: AsyncTaskExecutor, ) { private val log = KotlinLogging.logger { } private val mail = maaCopilotProperties.mail @@ -95,13 +95,13 @@ class EmailService( targetMessage: String, replierName: String, message: String, - timeStr: String = LocalDateTime.now().format(timeFormatter) + timeStr: String = LocalDateTime.now().format(timeFormatter), ) = emailTaskExecutor.execute { if (!maaCopilotProperties.mail.notification) return@execute val limit = 25 val title = targetMessage.run { if (length > limit) take(limit - 4) + "...." else this } - val subject = "收到新回复 来自用户@${replierName} Re: $title" + val subject = "收到新回复 来自用户@$replierName Re: $title" val dataModel = mapOf( "content" to "mail-comment-notification.ftlh", diff --git a/src/main/kotlin/plus/maa/backend/service/FileService.kt b/src/main/kotlin/plus/maa/backend/service/FileService.kt index e473fe13..f035c64c 100644 --- a/src/main/kotlin/plus/maa/backend/service/FileService.kt +++ b/src/main/kotlin/plus/maa/backend/service/FileService.kt @@ -18,13 +18,14 @@ import plus.maa.backend.repository.RedisCache import java.io.IOException import java.text.ParseException import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale +import java.util.UUID import java.util.concurrent.TimeUnit import java.util.regex.Pattern import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream - /** * @author LoMu * Date 2023-04-16 23:21 @@ -32,25 +33,17 @@ import java.util.zip.ZipOutputStream @Service class FileService( private val gridFsOperations: GridFsOperations, - private val redisCache: RedisCache + private val redisCache: RedisCache, ) { - - fun uploadFile( - file: MultipartFile, - type: String?, - version: String, - classification: String?, - label: String?, - ip: String? - ) { - //redis持久化 + fun uploadFile(file: MultipartFile, type: String?, version: String, classification: String?, label: String?, ip: String?) { + // redis持久化 var realVersion = version if (redisCache.getCache("NotEnable:UploadFile", String::class.java) != null) { throw MaaResultException(403, "closed uploadfile") } - //文件小于1024Bytes不接收 + // 文件小于1024Bytes不接收 if (file.size < 1024) { throw MultipartException("Minimum upload size exceeded") } @@ -86,7 +79,6 @@ class FileService( } } - fun downloadDateFile(date: String?, beLocated: String, delete: Boolean, response: HttpServletResponse) { val formatter = SimpleDateFormat("yyyy-MM-dd") val query: Query @@ -117,26 +109,24 @@ class FileService( } } - fun downloadFile(imageDownloadDTO: ImageDownloadDTO, response: HttpServletResponse) { val query = Query() val criteriaSet: MutableSet = HashSet() - - //图片类型 + // 图片类型 criteriaSet.add( - GridFsCriteria.whereMetaData("type").regex(Pattern.compile(imageDownloadDTO.type, Pattern.CASE_INSENSITIVE)) + GridFsCriteria.whereMetaData("type").regex(Pattern.compile(imageDownloadDTO.type, Pattern.CASE_INSENSITIVE)), ) - //指定下载某个类型的图片 + // 指定下载某个类型的图片 if (!imageDownloadDTO.classification.isNullOrBlank()) { criteriaSet.add( GridFsCriteria.whereMetaData("classification") - .regex(Pattern.compile(imageDownloadDTO.classification, Pattern.CASE_INSENSITIVE)) + .regex(Pattern.compile(imageDownloadDTO.classification, Pattern.CASE_INSENSITIVE)), ) } - //指定版本或指定范围版本 + // 指定版本或指定范围版本 if (!imageDownloadDTO.version.isNullOrEmpty()) { val version = imageDownloadDTO.version @@ -147,8 +137,7 @@ class FileService( antecedentVersion = split[1] } criteriaSet.add( - GridFsCriteria.whereMetaData("version").`is`(version[0]).and("antecedentVersion") - .`is`(antecedentVersion) + GridFsCriteria.whereMetaData("version").`is`(version[0]).and("antecedentVersion").`is`(antecedentVersion), ) } else if (version.size == 2) { criteriaSet.add(GridFsCriteria.whereMetaData("version").gte(version[0]).lte(version[1])) @@ -157,15 +146,13 @@ class FileService( if (!imageDownloadDTO.label.isNullOrBlank()) { criteriaSet.add( - GridFsCriteria.whereMetaData("label") - .regex(Pattern.compile(imageDownloadDTO.label, Pattern.CASE_INSENSITIVE)) + GridFsCriteria.whereMetaData("label").regex(Pattern.compile(imageDownloadDTO.label, Pattern.CASE_INSENSITIVE)), ) } val criteria = Criteria().andOperator(criteriaSet) query.addCriteria(criteria) - val gridFSFiles = gridFsOperations.find(query) response.addHeader("Content-Disposition", "attachment;filename=" + "Maa-" + imageDownloadDTO.type + ".zip") @@ -187,12 +174,11 @@ class FileService( return "已启用" } + /** + * 上传功能状态 + */ var isUploadEnabled: Boolean get() = redisCache.getCache("NotEnable:UploadFile", String::class.java) == null - /** - * 设置上传功能状态 - * @param enabled 是否开启 - */ set(enabled) { // Fixme: redis recovery solution should be added, or change to another storage if (enabled) { @@ -202,14 +188,13 @@ class FileService( } } - private fun gzip(response: HttpServletResponse, files: GridFSFindIterable) { try { ZipOutputStream(response.outputStream).use { zipOutputStream -> for (file in files) { val zipEntry = ZipEntry(file.filename) gridFsOperations.getResource(file).inputStream.use { inputStream -> - //添加压缩文件 + // 添加压缩文件 zipOutputStream.putNextEntry(zipEntry) val bytes = ByteArray(1024) diff --git a/src/main/kotlin/plus/maa/backend/service/UserDetailServiceImpl.kt b/src/main/kotlin/plus/maa/backend/service/UserDetailServiceImpl.kt index 3890afd7..aa407e2d 100644 --- a/src/main/kotlin/plus/maa/backend/service/UserDetailServiceImpl.kt +++ b/src/main/kotlin/plus/maa/backend/service/UserDetailServiceImpl.kt @@ -14,8 +14,9 @@ import plus.maa.backend.service.model.LoginUser * @author AnselYuki */ @Service -class UserDetailServiceImpl(private val userRepository: UserRepository) : UserDetailsService { - +class UserDetailServiceImpl( + private val userRepository: UserRepository, +) : UserDetailsService { /** * 查询用户信息 * @@ -28,7 +29,7 @@ class UserDetailServiceImpl(private val userRepository: UserRepository) : UserDe val user = userRepository.findByEmail(email) ?: throw UsernameNotFoundException("用户不存在") val permissions = collectAuthoritiesFor(user) - //数据封装成UserDetails返回 + // 数据封装成UserDetails返回 return LoginUser(user, permissions) } diff --git a/src/main/kotlin/plus/maa/backend/service/UserService.kt b/src/main/kotlin/plus/maa/backend/service/UserService.kt index afb9f294..9fee2064 100644 --- a/src/main/kotlin/plus/maa/backend/service/UserService.kt +++ b/src/main/kotlin/plus/maa/backend/service/UserService.kt @@ -6,7 +6,11 @@ import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import plus.maa.backend.common.MaaStatusCode import plus.maa.backend.config.external.MaaCopilotProperties -import plus.maa.backend.controller.request.user.* +import plus.maa.backend.controller.request.user.LoginDTO +import plus.maa.backend.controller.request.user.PasswordResetDTO +import plus.maa.backend.controller.request.user.RegisterDTO +import plus.maa.backend.controller.request.user.SendRegistrationTokenDTO +import plus.maa.backend.controller.request.user.UserInfoUpdateDTO import plus.maa.backend.controller.response.MaaResultException import plus.maa.backend.controller.response.user.MaaLoginRsp import plus.maa.backend.controller.response.user.MaaUserInfo @@ -15,7 +19,7 @@ import plus.maa.backend.repository.entity.MaaUser import plus.maa.backend.service.jwt.JwtExpiredException import plus.maa.backend.service.jwt.JwtInvalidException import plus.maa.backend.service.jwt.JwtService -import java.util.* +import java.util.UUID /** * @author AnselYuki @@ -27,9 +31,8 @@ class UserService( private val passwordEncoder: PasswordEncoder, private val userDetailService: UserDetailServiceImpl, private val jwtService: JwtService, - private val properties: MaaCopilotProperties + private val properties: MaaCopilotProperties, ) { - /** * 登录方法 * @@ -63,7 +66,7 @@ class UserService( refreshToken.value, refreshToken.expiresAt, refreshToken.notBefore, - MaaUserInfo(user) + MaaUserInfo(user), ) } @@ -73,11 +76,7 @@ class UserService( * @param userId 当前用户 * @param rawPassword 新密码 */ - fun modifyPassword( - userId: String, rawPassword: String, - originPassword: String? = null, - verifyOriginPassword: Boolean = true - ) { + fun modifyPassword(userId: String, rawPassword: String, originPassword: String? = null, verifyOriginPassword: Boolean = true) { val maaUser = userRepository.findByIdOrNull(userId) ?: return if (verifyOriginPassword) { check(!originPassword.isNullOrEmpty()) { @@ -163,7 +162,7 @@ class UserService( refreshToken.value, refreshToken.expiresAt, refreshToken.notBefore, - MaaUserInfo(user) + MaaUserInfo(user), ) } catch (e: JwtInvalidException) { throw MaaResultException(401, e.message) diff --git a/src/main/kotlin/plus/maa/backend/service/jwt/JwtAuthToken.kt b/src/main/kotlin/plus/maa/backend/service/jwt/JwtAuthToken.kt index ad47fbc7..37b2f306 100644 --- a/src/main/kotlin/plus/maa/backend/service/jwt/JwtAuthToken.kt +++ b/src/main/kotlin/plus/maa/backend/service/jwt/JwtAuthToken.kt @@ -29,17 +29,15 @@ class JwtAuthToken : JwtToken, Authentication { exp: Instant, nbf: Instant, authorities: Collection, - key: ByteArray + key: ByteArray, ) : super(sub, jti, iat, exp, nbf, TYPE, key) { this.authorities = authorities } - override fun getAuthorities(): Collection { val authorityStrings = jwt.payloads.getStr(CLAIM_AUTHORITIES) - return StringUtils.commaDelimitedListToSet(authorityStrings).stream() + return StringUtils.commaDelimitedListToSet(authorityStrings) .map { role: String? -> SimpleGrantedAuthority(role) } - .toList() } fun setAuthorities(authorities: Collection) { @@ -52,34 +50,24 @@ class JwtAuthToken : JwtToken, Authentication { * @return credentials,采用 jwt 的 id * @inheritDoc */ - override fun getCredentials(): Any { - return jwtId!! - } + override fun getCredentials(): Any = jwtId!! - override fun getDetails(): Any? { - return null - } + override fun getDetails(): Any? = null /** * @return principal,采用 jwt 的 subject * @inheritDoc */ - override fun getPrincipal(): Any { - return subject - } + override fun getPrincipal(): Any = subject - override fun isAuthenticated(): Boolean { - return this.authenticated - } + override fun isAuthenticated(): Boolean = this.authenticated @Throws(IllegalArgumentException::class) override fun setAuthenticated(isAuthenticated: Boolean) { this.authenticated = isAuthenticated } - override fun getName(): String { - return subject - } + override fun getName(): String = subject companion object { /** diff --git a/src/main/kotlin/plus/maa/backend/service/jwt/JwtRefreshToken.kt b/src/main/kotlin/plus/maa/backend/service/jwt/JwtRefreshToken.kt index c85c817c..e761b251 100644 --- a/src/main/kotlin/plus/maa/backend/service/jwt/JwtRefreshToken.kt +++ b/src/main/kotlin/plus/maa/backend/service/jwt/JwtRefreshToken.kt @@ -18,7 +18,7 @@ class JwtRefreshToken : JwtToken { iat: Instant, exp: Instant, nbf: Instant, - key: ByteArray + key: ByteArray, ) : super(sub, jti, iat, exp, nbf, TYPE, key) companion object { diff --git a/src/main/kotlin/plus/maa/backend/service/jwt/JwtToken.kt b/src/main/kotlin/plus/maa/backend/service/jwt/JwtToken.kt index f87a5910..a744cc39 100644 --- a/src/main/kotlin/plus/maa/backend/service/jwt/JwtToken.kt +++ b/src/main/kotlin/plus/maa/backend/service/jwt/JwtToken.kt @@ -5,7 +5,6 @@ import cn.hutool.jwt.JWT import cn.hutool.jwt.JWTUtil import cn.hutool.jwt.RegisteredPayload import java.time.Instant -import java.util.* /** * 对 [JWT] 的包装增强,某些 payload 被标记为 MUST @@ -22,12 +21,14 @@ open class JwtToken { this.payload = jwt.payloads // jwtId is nullable - if (requiredType != type - || payload.getStr(RegisteredPayload.SUBJECT) == null - || payload.getLong(RegisteredPayload.ISSUED_AT) == null - || payload.getLong(RegisteredPayload.EXPIRES_AT) == null - || payload.getLong(RegisteredPayload.NOT_BEFORE) == null - ) throw JwtInvalidException() + if (requiredType != type || + payload.getStr(RegisteredPayload.SUBJECT) == null || + payload.getLong(RegisteredPayload.ISSUED_AT) == null || + payload.getLong(RegisteredPayload.EXPIRES_AT) == null || + payload.getLong(RegisteredPayload.NOT_BEFORE) == null + ) { + throw JwtInvalidException() + } } constructor( @@ -37,7 +38,7 @@ open class JwtToken { exp: Instant, nbf: Instant, typ: String?, - key: ByteArray + key: ByteArray, ) { jwt = JWT.create() jwt.setPayload(RegisteredPayload.SUBJECT, sub) diff --git a/src/main/kotlin/plus/maa/backend/service/model/ArkLevelType.kt b/src/main/kotlin/plus/maa/backend/service/model/ArkLevelType.kt index 7e972309..c1e7ec17 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/ArkLevelType.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/ArkLevelType.kt @@ -1,8 +1,10 @@ package plus.maa.backend.service.model -import java.util.* +import java.util.Locale -enum class ArkLevelType(val display: String) { +enum class ArkLevelType( + val display: String, +) { MAINLINE("主题曲"), WEEKLY("资源收集"), ACTIVITIES("活动关卡"), @@ -10,17 +12,16 @@ enum class ArkLevelType(val display: String) { MEMORY("悖论模拟"), RUNE("危机合约"), LEGION("保全派驻"), - ROGUELIKE("集成战略"), //实际不进行解析 - TRAINING("训练关卡"), //实际不进行解析 - UNKNOWN("未知类型"); + ROGUELIKE("集成战略"), // 实际不进行解析 + TRAINING("训练关卡"), // 实际不进行解析 + UNKNOWN("未知类型"), ; companion object { fun fromLevelId(levelId: String?): ArkLevelType { if (levelId.isNullOrBlank()) { return UNKNOWN } - val ids = levelId.lowercase(Locale.getDefault()).split("/".toRegex()).dropLastWhile { it.isEmpty() } - .toTypedArray() + val ids = levelId.lowercase(Locale.getDefault()).split("/").dropLastWhile { it.isEmpty() }.toTypedArray() val type = if ((ids[0] == "obt")) ids[1] else ids[0] return when (type) { "main", "hard" -> MAINLINE diff --git a/src/main/kotlin/plus/maa/backend/service/model/LoginUser.kt b/src/main/kotlin/plus/maa/backend/service/model/LoginUser.kt index 7e782dea..07f69b1e 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/LoginUser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/LoginUser.kt @@ -10,16 +10,13 @@ import plus.maa.backend.repository.entity.MaaUser */ class LoginUser( private val maaUser: MaaUser, - private val authorities: Collection) : UserDetails { + private val authorities: Collection, +) : UserDetails { @JsonIgnore - override fun getAuthorities(): Collection { - return authorities - } + override fun getAuthorities(): Collection = authorities @JsonIgnore - override fun getPassword(): String { - return maaUser.password - } + override fun getPassword(): String = maaUser.password val userId: String? get() = maaUser.userId @@ -31,32 +28,22 @@ class LoginUser( * @return 用户邮箱 */ @JsonIgnore - override fun getUsername(): String { - return maaUser.email - } + override fun getUsername(): String = maaUser.email @get:JsonIgnore val email: String get() = maaUser.email - override fun isAccountNonExpired(): Boolean { - return true - } + override fun isAccountNonExpired(): Boolean = true - override fun isAccountNonLocked(): Boolean { - return true - } + override fun isAccountNonLocked(): Boolean = true - override fun isCredentialsNonExpired(): Boolean { - return true - } + override fun isCredentialsNonExpired(): Boolean = true /** * 默认用户为0(禁用),1为启用 * * @return 账户启用状态 */ - override fun isEnabled(): Boolean { - return true - } + override fun isEnabled(): Boolean = true } diff --git a/src/main/kotlin/plus/maa/backend/service/model/RatingCache.kt b/src/main/kotlin/plus/maa/backend/service/model/RatingCache.kt index 6af878e3..da4c6f80 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/RatingCache.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/RatingCache.kt @@ -5,5 +5,5 @@ package plus.maa.backend.service.model * Date 2023-01-28 11:37 */ data class RatingCache( - val copilotIds: MutableSet + val copilotIds: MutableSet, ) diff --git a/src/main/kotlin/plus/maa/backend/service/model/RatingCount.kt b/src/main/kotlin/plus/maa/backend/service/model/RatingCount.kt index 5362df7c..080fef50 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/RatingCount.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/RatingCount.kt @@ -2,5 +2,5 @@ package plus.maa.backend.service.model data class RatingCount( val key: String, - val count: Long = 0 + val count: Long = 0, ) diff --git a/src/main/kotlin/plus/maa/backend/service/model/RatingType.kt b/src/main/kotlin/plus/maa/backend/service/model/RatingType.kt index 65855719..0c44c851 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/RatingType.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/RatingType.kt @@ -7,7 +7,8 @@ package plus.maa.backend.service.model enum class RatingType(val display: Int) { LIKE(1), DISLIKE(2), - NONE(0); + NONE(0), + ; fun countLike() = if (this == LIKE) 1L else 0L @@ -20,14 +21,10 @@ enum class RatingType(val display: Int) { * @param type rating * @return type */ - fun fromRatingType(type: String?): RatingType { - return when (type) { - "Like" -> LIKE - "Dislike" -> DISLIKE - else -> NONE - } + fun fromRatingType(type: String?): RatingType = when (type) { + "Like" -> LIKE + "Dislike" -> DISLIKE + else -> NONE } } } - - diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/ActivityParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/ActivityParser.kt index 22eb9db9..4413d727 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/ActivityParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/ActivityParser.kt @@ -6,7 +6,6 @@ import plus.maa.backend.repository.entity.gamedata.ArkTilePos import plus.maa.backend.service.ArkGameDataService import plus.maa.backend.service.model.ArkLevelType - /** * @author john180 * @@ -18,9 +17,8 @@ import plus.maa.backend.service.model.ArkLevelType */ @Component class ActivityParser( - private val dataService: ArkGameDataService + private val dataService: ArkGameDataService, ) : ArkLevelParser { - override fun supportType(type: ArkLevelType): Boolean { return ArkLevelType.ACTIVITIES == type } diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/LegionParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/LegionParser.kt index afd8d71a..e72ffa70 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/LegionParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/LegionParser.kt @@ -20,9 +20,8 @@ private val log = KotlinLogging.logger { } */ @Component class LegionParser( - private val dataService: ArkGameDataService + private val dataService: ArkGameDataService, ) : ArkLevelParser { - override fun supportType(type: ArkLevelType): Boolean { return ArkLevelType.LEGION == type } diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/MainlineParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/MainlineParser.kt index 1f1472d1..4be97ff8 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/MainlineParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/MainlineParser.kt @@ -7,7 +7,7 @@ import plus.maa.backend.repository.entity.gamedata.ArkTilePos import plus.maa.backend.repository.entity.gamedata.ArkZone import plus.maa.backend.service.ArkGameDataService import plus.maa.backend.service.model.ArkLevelType -import java.util.* +import java.util.Locale /** * @author john180 @@ -21,18 +21,19 @@ import java.util.* */ @Component class MainlineParser( - private val dataService: ArkGameDataService + private val dataService: ArkGameDataService, ) : ArkLevelParser { - - override fun supportType(type: ArkLevelType): Boolean { - return ArkLevelType.MAINLINE == type - } + override fun supportType(type: ArkLevelType): Boolean = ArkLevelType.MAINLINE == type override fun parseLevel(level: ArkLevel, tilePos: ArkTilePos): ArkLevel? { level.catOne = ArkLevelType.MAINLINE.display val chapterLevelId = - level.levelId!!.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[2] // level_main_10-02 + level + .levelId!! + .split("/".toRegex()) + .dropLastWhile { it.isEmpty() } + .toTypedArray()[2] // level_main_10-02 val chapterStrSplit = chapterLevelId.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // level main 10-02 val diff = parseDifficulty(chapterStrSplit[1]) // easy、main @@ -53,12 +54,10 @@ class MainlineParser( return level } - private fun parseDifficulty(diff: String): String { - return when (diff.lowercase(Locale.getDefault())) { - "easy" -> "简单" - "tough" -> "磨难" - else -> "标准" - } + private fun parseDifficulty(diff: String): String = when (diff.lowercase(Locale.getDefault())) { + "easy" -> "简单" + "tough" -> "磨难" + else -> "标准" } private fun parseZoneName(zone: ArkZone): String { diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/MemoryParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/MemoryParser.kt index df191a8c..37da5126 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/MemoryParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/MemoryParser.kt @@ -6,7 +6,7 @@ import plus.maa.backend.repository.entity.ArkLevel import plus.maa.backend.repository.entity.gamedata.ArkTilePos import plus.maa.backend.service.ArkGameDataService import plus.maa.backend.service.model.ArkLevelType -import java.util.* +import java.util.Locale private val log = KotlinLogging.logger { } @@ -21,23 +21,24 @@ private val log = KotlinLogging.logger { } */ @Component class MemoryParser( - val dataService: ArkGameDataService + val dataService: ArkGameDataService, ) : ArkLevelParser { - - override fun supportType(type: ArkLevelType): Boolean { - return ArkLevelType.MEMORY == type - } + override fun supportType(type: ArkLevelType): Boolean = ArkLevelType.MEMORY == type override fun parseLevel(level: ArkLevel, tilePos: ArkTilePos): ArkLevel? { level.catOne = ArkLevelType.MEMORY.display val chIdSplit = - level.stageId!!.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() //mem_aurora_1 + level + .stageId!! + .split("_".toRegex()) + .dropLastWhile { it.isEmpty() } + .toTypedArray() // mem_aurora_1 if (chIdSplit.size != 3) { log.error { "[PARSER]悖论模拟关卡stageId异常: ${level.stageId}, level: ${level.levelId}" } return null } - val chId = chIdSplit[1] //aurora + val chId = chIdSplit[1] // aurora val character = dataService.findCharacter(chId) if (character == null) { log.error { "[PARSER]悖论模拟关卡未找到角色信息: ${level.stageId}, level: ${level.levelId}" } @@ -50,17 +51,15 @@ class MemoryParser( return level } - private fun parseProfession(professionId: String): String { - return when (professionId.lowercase(Locale.getDefault())) { - "medic" -> "医疗" - "special" -> "特种" - "warrior" -> "近卫" - "sniper" -> "狙击" - "tank" -> "重装" - "caster" -> "术师" - "pioneer" -> "先锋" - "support" -> "辅助" - else -> "未知" - } + private fun parseProfession(professionId: String): String = when (professionId.lowercase(Locale.getDefault())) { + "medic" -> "医疗" + "special" -> "特种" + "warrior" -> "近卫" + "sniper" -> "狙击" + "tank" -> "重装" + "caster" -> "术师" + "pioneer" -> "先锋" + "support" -> "辅助" + else -> "未知" } } diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/RuneParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/RuneParser.kt index ce281d49..98cfdb6e 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/RuneParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/RuneParser.kt @@ -8,9 +8,8 @@ import plus.maa.backend.service.model.ArkLevelType @Component class RuneParser( - private val dataService: ArkGameDataService + private val dataService: ArkGameDataService, ) : ArkLevelParser { - override fun supportType(type: ArkLevelType): Boolean { return ArkLevelType.RUNE == type } diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/UnknownParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/UnknownParser.kt index 840df945..73a8849e 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/UnknownParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/UnknownParser.kt @@ -4,17 +4,17 @@ import org.springframework.stereotype.Component import plus.maa.backend.repository.entity.ArkLevel import plus.maa.backend.repository.entity.gamedata.ArkTilePos import plus.maa.backend.service.model.ArkLevelType -import java.util.* +import java.util.Locale @Component class UnknownParser : ArkLevelParser { - override fun supportType(type: ArkLevelType): Boolean { - return ArkLevelType.UNKNOWN == type - } + override fun supportType(type: ArkLevelType): Boolean = ArkLevelType.UNKNOWN == type override fun parseLevel(level: ArkLevel, tilePos: ArkTilePos): ArkLevel? { - val ids = level.levelId!!.lowercase(Locale.getDefault()) - .split("/".toRegex()).dropLastWhile { it.isEmpty() } + val ids = level.levelId!! + .lowercase(Locale.getDefault()) + .split("/".toRegex()) + .dropLastWhile { it.isEmpty() } .toTypedArray() val type = if ((ids[0] == "obt")) ids[1] else ids[0] diff --git a/src/main/kotlin/plus/maa/backend/service/model/parser/WeeklyParser.kt b/src/main/kotlin/plus/maa/backend/service/model/parser/WeeklyParser.kt index ab818bf9..6d261f8e 100644 --- a/src/main/kotlin/plus/maa/backend/service/model/parser/WeeklyParser.kt +++ b/src/main/kotlin/plus/maa/backend/service/model/parser/WeeklyParser.kt @@ -18,9 +18,8 @@ import plus.maa.backend.service.model.ArkLevelType */ @Component class WeeklyParser( - private val dataService: ArkGameDataService + private val dataService: ArkGameDataService, ) : ArkLevelParser { - override fun supportType(type: ArkLevelType): Boolean { return ArkLevelType.WEEKLY == type } diff --git a/src/main/kotlin/plus/maa/backend/task/ArkLevelSyncTask.kt b/src/main/kotlin/plus/maa/backend/task/ArkLevelSyncTask.kt index d064fcdd..5776e409 100644 --- a/src/main/kotlin/plus/maa/backend/task/ArkLevelSyncTask.kt +++ b/src/main/kotlin/plus/maa/backend/task/ArkLevelSyncTask.kt @@ -6,9 +6,8 @@ import plus.maa.backend.service.ArkLevelService @Component class ArkLevelSyncTask( - private val arkLevelService: ArkLevelService + private val arkLevelService: ArkLevelService, ) { - /** * 地图数据同步定时任务,每10分钟执行一次 * 应用启动时自动同步一次 diff --git a/src/main/kotlin/plus/maa/backend/task/CopilotBackupTask.kt b/src/main/kotlin/plus/maa/backend/task/CopilotBackupTask.kt index 89daf2bb..139f947d 100644 --- a/src/main/kotlin/plus/maa/backend/task/CopilotBackupTask.kt +++ b/src/main/kotlin/plus/maa/backend/task/CopilotBackupTask.kt @@ -20,9 +20,9 @@ import java.io.File import java.io.IOException import java.nio.file.Files import java.time.LocalDate -import java.util.* +import java.util.Objects -private val log = KotlinLogging.logger { } +private val log = KotlinLogging.logger { } /** * CopilotBackupTask @@ -33,7 +33,6 @@ class CopilotBackupTask( private val copilotRepository: CopilotRepository, private val levelService: ArkLevelService, ) { - private lateinit var git: Git /** @@ -58,17 +57,13 @@ class CopilotBackupTask( Files.list(repoDir.toPath()).use { fileList -> git = if (fileList.findFirst().isEmpty) { // 不存在文件则初始化 - Git.cloneRepository() - .setURI(backup.uri) - .setDirectory(repoDir) - .setTransportConfigCallback(sshCallback) - .call() + Git.cloneRepository().setURI(backup.uri).setDirectory(repoDir).setTransportConfigCallback(sshCallback).call() } else { Git.open(repoDir) } } } catch (e: IOException) { - log.error { "init copilot backup repo failed, repoDir: $repoDir, $e"} + log.error { "init copilot backup repo failed, repoDir: $repoDir, $e" } } catch (e: GitAPIException) { log.error { "init copilot backup repo failed, repoDir: $repoDir, $e" } } @@ -90,14 +85,18 @@ class CopilotBackupTask( val baseDirectory = git.repository.workTree val copilots = copilotRepository.findAll() - copilots.forEach{ copilot: Copilot -> + copilots.forEach { copilot: Copilot -> val level = levelService.findByLevelIdFuzzy(copilot.stageName!!) ?: return@forEach // 暂时使用 copilotId 作为文件名 val filePath = File( java.lang.String.join( - File.separator, baseDirectory.path, level.catOne, - level.catTwo, level.catThree, copilot.copilotId.toString() + ".json" - ) + File.separator, + baseDirectory.path, + level.catOne, + level.catTwo, + level.catThree, + copilot.copilotId.toString() + ".json", + ), ) val content = copilot.content ?: return@forEach if (copilot.delete) { diff --git a/src/main/kotlin/plus/maa/backend/task/CopilotScoreRefreshTask.kt b/src/main/kotlin/plus/maa/backend/task/CopilotScoreRefreshTask.kt index 90107608..3ed5183a 100644 --- a/src/main/kotlin/plus/maa/backend/task/CopilotScoreRefreshTask.kt +++ b/src/main/kotlin/plus/maa/backend/task/CopilotScoreRefreshTask.kt @@ -27,7 +27,7 @@ class CopilotScoreRefreshTask( private val arkLevelService: ArkLevelService, private val redisCache: RedisCache, private val copilotRepository: CopilotRepository, - private val mongoTemplate: MongoTemplate + private val mongoTemplate: MongoTemplate, ) { /** * 热度值刷入任务,每日四点三十执行(实际可能会更晚,因为需要等待之前启动的定时任务完成) @@ -68,7 +68,7 @@ class CopilotScoreRefreshTask( } val copilots = copilotRepository.findByCopilotIdInAndDeleteIsFalse( - copilotIdSTRs.map { s: String? -> s!!.toLong() } + copilotIdSTRs.map { s: String? -> s!!.toLong() }, ) if (copilots.isEmpty()) { return @@ -97,10 +97,10 @@ class CopilotScoreRefreshTask( // 判断关卡是否开放 val level = arkLevelService.findByLevelIdFuzzy(copilot.stageName!!) // 关卡已关闭,且作业在关闭前上传 - if (level?.closeTime != null - && copilot.firstUploadTime != null - && false == level.isOpen - && copilot.firstUploadTime!!.isBefore(level.closeTime) + if (level?.closeTime != null && + copilot.firstUploadTime != null && + false == level.isOpen && + copilot.firstUploadTime!!.isBefore(level.closeTime) ) { // 非开放关卡打入冷宫 @@ -119,11 +119,10 @@ class CopilotScoreRefreshTask( .where("type").`is`(Rating.KeyType.COPILOT) .and("key").`in`(keys) .and("rating").`is`(rating) - .and("rateTime").gte(startTime) + .and("rateTime").gte(startTime), ), - Aggregation.group("key").count().`as`("count") - .first("key").`as`("key"), - Aggregation.project("key", "count") + Aggregation.group("key").count().`as`("count").first("key").`as`("key"), + Aggregation.project("key", "count"), ).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build()) // 放弃内存优化,使用磁盘优化,免得内存炸了 return mongoTemplate.aggregate(aggregation, Rating::class.java, RatingCount::class.java).mappedResults }