From 5ca049f588623d7edc5acd3d3433d31ab3d0bcdc Mon Sep 17 00:00:00 2001 From: usbharu <64310155+usbharu@users.noreply.github.com> Date: Sat, 29 Apr 2023 23:57:25 +0900 Subject: [PATCH 1/4] =?UTF-8?q?chore:=20Lint=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 9 +++++ detekt.yml | 99 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 detekt.yml diff --git a/build.gradle.kts b/build.gradle.kts index 3bc19e7c..5cdda4d7 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,6 +9,7 @@ plugins { kotlin("jvm") version "1.8.21" id("io.ktor.plugin") version "2.3.0" id("org.graalvm.buildtools.native") version "0.9.21" + id("io.gitlab.arturbosch.detekt") version "1.22.0" // id("org.jetbrains.kotlin.plugin.serialization") version "1.8.10" } @@ -88,6 +89,7 @@ dependencies { testImplementation("org.slf4j:slf4j-simple:2.0.7") + detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.22.0") } jib { @@ -129,3 +131,10 @@ graalvmNative { } } } + +detekt { + parallel = true + config = files("detekt.yml") + buildUponDefaultConfig = true + basePath = rootDir.absolutePath +} diff --git a/detekt.yml b/detekt.yml new file mode 100644 index 00000000..faeab0d6 --- /dev/null +++ b/detekt.yml @@ -0,0 +1,99 @@ +style: + ClassOrdering: + active: true + + MandatoryBracesIfStatements: + active: true + + MandatoryBracesLoops: + active: true + + MultilineLambdaItParameter: + active: true + + UseEmptyCounterpart: + active: true + +complexity: + CognitiveComplexMethod: + active: true + + ComplexCondition: + active: true + + ComplexInterface: + active: true + + LabeledExpression: + active: true + + NamedArguments: + active: true + + NestedBlockDepth: + active: true + + NestedScopeFunctions: + active: true + + ReplaceSafeCallChainWithRun: + active: true + + StringLiteralDuplication: + active: true + +exceptions: + ExceptionRaisedInUnexpectedLocation: + active: true + + NotImplementedDeclaration: + active: true + + ObjectExtendsThrowable: + active: true + + ThrowingExceptionInMain: + active: true + + ThrowingExceptionsWithoutMessageOrCause: + active: true + + ThrowingNewInstanceOfSameException: + active: true + + TooGenericExceptionCaught: + active: true + + TooGenericExceptionThrown: + active: true + +formatting: + Indentation: + indentSize: 4 + +naming: + FunctionMaxLength: + active: true + + FunctionMinLength: + active: true + + LambdaParameterNaming: + active: true + +performance: + UnnecessaryPartOfBinaryExpression: + active: true + + UnnecessaryTemporaryInstantiation: + active: true + +potential-bugs: + CastToNullableType: + active: true + + DontDowncastCollectionTypes: + active: true + + ElseCaseInsteadOfExhaustiveWhen: + active: true From fcabce738055395202e66d7990f1fc7113b83bb5 Mon Sep 17 00:00:00 2001 From: usbharu <64310155+usbharu@users.noreply.github.com> Date: Sun, 30 Apr 2023 01:25:54 +0900 Subject: [PATCH 2/4] =?UTF-8?q?style:=20=E3=82=B9=E3=82=BF=E3=82=A4?= =?UTF-8?q?=E3=83=AB=E3=82=92=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 1 + detekt.yml | 45 +++++++- .../kotlin/dev/usbharu/hideout/Application.kt | 15 ++- .../usbharu/hideout/domain/model/ap/Accept.kt | 8 +- .../usbharu/hideout/domain/model/ap/Create.kt | 6 +- .../usbharu/hideout/domain/model/ap/Follow.kt | 4 +- .../usbharu/hideout/domain/model/ap/Image.kt | 2 - .../usbharu/hideout/domain/model/ap/JsonLd.kt | 16 +-- .../usbharu/hideout/domain/model/ap/Key.kt | 4 +- .../usbharu/hideout/domain/model/ap/Note.kt | 7 +- .../usbharu/hideout/domain/model/ap/Object.kt | 29 ++--- .../usbharu/hideout/domain/model/ap/Person.kt | 6 +- .../model/api/{Status.kt => StatusForPost.kt} | 0 .../model/hideout/dto/RemoteUserCreateDto.kt | 16 +-- .../domain/model/hideout/dto/UserCreateDto.kt | 8 +- .../usbharu/hideout/plugins/ActivityPub.kt | 52 ++++----- .../dev/usbharu/hideout/plugins/Routing.kt | 1 - .../dev/usbharu/hideout/plugins/Security.kt | 8 +- .../hideout/repository/IPostRepository.kt | 6 +- .../hideout/repository/IUserRepository.kt | 9 +- .../hideout/repository/PostRepositoryImpl.kt | 24 +++-- .../hideout/repository/UserRepository.kt | 37 +++---- .../hideout/routing/RegisterRouting.kt | 1 - .../routing/activitypub/InboxRouting.kt | 90 ++++++++-------- .../routing/activitypub/OutboxRouting.kt | 30 +++--- .../routing/activitypub/UserRouting.kt | 4 +- .../hideout/routing/api/v1/Statuses.kt | 1 - .../routing/wellknown/WebfingerRouting.kt | 4 +- .../usbharu/hideout/service/IPostService.kt | 2 +- .../hideout/service/IUserAuthService.kt | 3 +- .../hideout/service/IdGenerateService.kt | 2 +- .../service/SnowflakeIdGenerateService.kt | 27 +++-- .../TwitterSnowflakeIdGenerateService.kt | 1 + .../activitypub/ActivityPubFollowService.kt | 4 +- .../ActivityPubFollowServiceImpl.kt | 2 +- .../activitypub/ActivityPubNoteService.kt | 4 +- .../activitypub/ActivityPubNoteServiceImpl.kt | 1 - .../service/activitypub/ActivityPubService.kt | 2 +- .../activitypub/ActivityPubServiceImpl.kt | 6 +- .../activitypub/ActivityPubUserService.kt | 2 +- .../activitypub/ActivityPubUserServiceImpl.kt | 16 ++- .../hideout/service/impl/IUserService.kt | 1 + .../hideout/service/impl/PostService.kt | 9 +- .../hideout/service/impl/UserAuthService.kt | 16 +-- .../hideout/service/impl/UserService.kt | 43 +++----- .../service/job/JobQueueParentService.kt | 2 +- .../service/job/JobQueueWorkerService.kt | 6 +- .../service/job/KJobJobQueueParentService.kt | 4 +- .../service/job/KJobJobQueueWorkerService.kt | 9 +- .../signature/HttpSignatureVerifyService.kt | 2 +- .../HttpSignatureVerifyServiceImpl.kt | 22 ++-- .../dev/usbharu/hideout/util/HttpUtil.kt | 22 ++-- .../kjob/exposed/ExposedJobRepository.kt | 35 ++++-- .../dev/usbharu/kjob/exposed/ExposedKJob.kt | 35 +++--- .../kjob/exposed/ExposedLockRepository.kt | 2 +- .../META-INF/native-image/jni-config.json | 60 +++++------ .../predefined-classes-config.json | 13 ++- .../META-INF/native-image/proxy-config.json | 3 +- .../META-INF/native-image/reflect-config.json | 66 ------------ .../native-image/resource-config.json | 101 +++++++++--------- .../native-image/serialization-config.json | 17 ++- src/main/resources/logback.xml | 26 ++--- src/test/kotlin/dev/usbharu/hideout/Empty.kt | 2 +- .../hideout/ap/ContextDeserializerTest.kt | 3 +- .../hideout/ap/ContextSerializerTest.kt | 2 +- .../hideout/plugins/ActivityPubKtTest.kt | 2 +- .../usbharu/hideout/plugins/KtorKeyMapTest.kt | 2 +- .../hideout/repository/UserRepositoryTest.kt | 6 +- .../routing/activitypub/InboxRoutingKtTest.kt | 29 +++-- .../hideout/service/impl/UserServiceTest.kt | 12 +-- src/test/kotlin/utils/DBResetInterceptor.kt | 2 +- 71 files changed, 506 insertions(+), 554 deletions(-) rename src/main/kotlin/dev/usbharu/hideout/domain/model/api/{Status.kt => StatusForPost.kt} (100%) diff --git a/build.gradle.kts b/build.gradle.kts index 5cdda4d7..25d07a41 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -137,4 +137,5 @@ detekt { config = files("detekt.yml") buildUponDefaultConfig = true basePath = rootDir.absolutePath + autoCorrect = true } diff --git a/detekt.yml b/detekt.yml index faeab0d6..f8c0fb04 100644 --- a/detekt.yml +++ b/detekt.yml @@ -9,11 +9,26 @@ style: active: true MultilineLambdaItParameter: - active: true + active: false UseEmptyCounterpart: active: true + ExpressionBodySyntax: + active: true + + WildcardImport: + active: false + + ReturnCount: + active: false + + MagicNumber: + ignorePropertyDeclaration: true + + ForbiddenComment: + active: false + complexity: CognitiveComplexMethod: active: true @@ -23,12 +38,15 @@ complexity: ComplexInterface: active: true + threshold: 30 LabeledExpression: - active: true + active: false NamedArguments: active: true + ignoreArgumentsMatchingNames: true + threshold: 5 NestedBlockDepth: active: true @@ -40,7 +58,16 @@ complexity: active: true StringLiteralDuplication: - active: true + active: false + + LongParameterList: + constructorThreshold: 10 + + TooManyFunctions: + ignoreDeprecated: true + ignoreOverridden: true + ignorePrivate: true + exceptions: ExceptionRaisedInUnexpectedLocation: @@ -71,6 +98,9 @@ formatting: Indentation: indentSize: 4 + NoWildcardImports: + active: false + naming: FunctionMaxLength: active: true @@ -81,6 +111,15 @@ naming: LambdaParameterNaming: active: true + ConstructorParameterNaming: + excludes: + - "**/domain/model/ap/*" + ignoreOverridden: true + + VariableNaming: + excludes: + - "**/domain/model/ap/*" + performance: UnnecessaryPartOfBinaryExpression: active: true diff --git a/src/main/kotlin/dev/usbharu/hideout/Application.kt b/src/main/kotlin/dev/usbharu/hideout/Application.kt index 3fe5d5a1..de723c6b 100644 --- a/src/main/kotlin/dev/usbharu/hideout/Application.kt +++ b/src/main/kotlin/dev/usbharu/hideout/Application.kt @@ -42,9 +42,9 @@ val Application.property: Application.(propertyName: String) -> String environment.config.property(it).getString() } -@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused. +// application.conf references the main function. This annotation prevents the IDE from marking it as unused. +@Suppress("unused") fun Application.parent() { - Config.configData = ConfigData( url = property("hideout.url"), objectMapper = jacksonObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) @@ -62,12 +62,12 @@ fun Application.parent() { ) } - single { UserRepository(get(),get()) } + single { UserRepository(get(), get()) } single { UserAuthService(get()) } single { HttpSignatureVerifyServiceImpl(get()) } single { val kJobJobQueueService = KJobJobQueueParentService(get()) - kJobJobQueueService.init(listOf()) + kJobJobQueueService.init(emptyList()) kJobJobQueueService } single { @@ -83,15 +83,14 @@ fun Application.parent() { } single { ActivityPubFollowServiceImpl(get(), get(), get(), get()) } single { ActivityPubServiceImpl(get(), get()) } - single { UserService(get(),get()) } + single { UserService(get(), get()) } single { ActivityPubUserServiceImpl(get(), get()) } single { ActivityPubNoteServiceImpl(get(), get(), get()) } single { PostService(get(), get()) } single { PostRepositoryImpl(get(), get()) } - single {TwitterSnowflakeIdGenerateService} + single { TwitterSnowflakeIdGenerateService } } - configureKoin(module) configureHTTP() configureStaticRouting() @@ -120,7 +119,7 @@ fun Application.worker() { activityPubService.processActivity(this, it) } } - kJob.register(DeliverPostJob){ + kJob.register(DeliverPostJob) { execute { activityPubService.processActivity(this, it) } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Accept.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Accept.kt index b2274eb6..e71cbcbc 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Accept.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Accept.kt @@ -9,7 +9,7 @@ open class Accept : Object { name: String, `object`: Object?, actor: String? - ) : super(add(type, "Accept"), name,actor) { + ) : super(add(type, "Accept"), name, actor) { this.`object` = `object` } @@ -29,9 +29,5 @@ open class Accept : Object { return result } - override fun toString(): String { - return "Accept(`object`=$`object`, actor=$actor) ${super.toString()}" - } - - + override fun toString(): String = "Accept(`object`=$`object`, actor=$actor) ${super.toString()}" } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Create.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Create.kt index 540e57aa..c187a0c7 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Create.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Create.kt @@ -33,9 +33,5 @@ open class Create : Object { return result } - override fun toString(): String { - return "Create(`object`=$`object`) ${super.toString()}" - } - - + override fun toString(): String = "Create(`object`=$`object`) ${super.toString()}" } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Follow.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Follow.kt index cf6d1303..7977721d 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Follow.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Follow.kt @@ -9,9 +9,7 @@ open class Follow : Object { name: String, `object`: String?, actor: String? - ) : super(add(type, "Follow"), name,actor) { + ) : super(add(type, "Follow"), name, actor) { this.`object` = `object` } - - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Image.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Image.kt index 5763366b..a53c6b99 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Image.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Image.kt @@ -28,6 +28,4 @@ open class Image : Object { result = 31 * result + (url?.hashCode() ?: 0) return result } - - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/JsonLd.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/JsonLd.kt index f6c4c73a..193b3f60 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/JsonLd.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/JsonLd.kt @@ -34,15 +34,9 @@ open class JsonLd { return context == other.context } - override fun hashCode(): Int { - return context.hashCode() - } - - override fun toString(): String { - return "JsonLd(context=$context)" - } - + override fun hashCode(): Int = context.hashCode() + override fun toString(): String = "JsonLd(context=$context)" } class ContextDeserializer : JsonDeserializer() { @@ -60,10 +54,7 @@ class ContextDeserializer : JsonDeserializer() { class ContextSerializer : JsonSerializer>() { - - override fun isEmpty(value: List?): Boolean { - return value.isNullOrEmpty() - } + override fun isEmpty(value: List?): Boolean = value.isNullOrEmpty() override fun serialize(value: List?, gen: JsonGenerator?, serializers: SerializerProvider?) { if (value.isNullOrEmpty()) { @@ -80,5 +71,4 @@ class ContextSerializer : JsonSerializer>() { gen?.writeEndArray() } } - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Key.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Key.kt index 935a531b..850bacb8 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Key.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Key.kt @@ -11,7 +11,7 @@ open class Key : Object { id: String?, owner: String?, publicKeyPem: String? - ) : super(add(type, "Key"), name,id) { + ) : super(add(type, "Key"), name, id) { this.owner = owner this.publicKeyPem = publicKeyPem } @@ -33,6 +33,4 @@ open class Key : Object { result = 31 * result + (publicKeyPem?.hashCode() ?: 0) return result } - - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Note.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Note.kt index e62fccc2..97277e53 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Note.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Note.kt @@ -48,9 +48,6 @@ open class Note : Object { return result } - override fun toString(): String { - return "Note(id=$id, attributedTo=$attributedTo, content=$content, published=$published, to=$to) ${super.toString()}" - } - - + override fun toString(): String = + "Note(id=$id, attributedTo=$attributedTo, content=$content, published=$published, to=$to) ${super.toString()}" } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Object.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Object.kt index c66e7224..ae52c978 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Object.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Object.kt @@ -10,27 +10,16 @@ open class Object : JsonLd { private var type: List = emptyList() var name: String? = null var actor: String? = null - var id:String? = null + var id: String? = null protected constructor() - constructor(type: List, name: String? = null,actor:String? = null,id:String? = null) : super() { + constructor(type: List, name: String? = null, actor: String? = null, id: String? = null) : super() { this.type = type this.name = name this.actor = actor this.id = id } - companion object { - @JvmStatic - protected fun add(list: List, type: String): List { - val toMutableList = list.toMutableList() - toMutableList.add(type) - return toMutableList.distinct() - } - } - - - override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Object) return false @@ -49,11 +38,16 @@ open class Object : JsonLd { return result } - override fun toString(): String { - return "Object(type=$type, name=$name, actor=$actor) ${super.toString()}" + override fun toString(): String = "Object(type=$type, name=$name, actor=$actor) ${super.toString()}" + + companion object { + @JvmStatic + protected fun add(list: List, type: String): List { + val toMutableList = list.toMutableList() + toMutableList.add(type) + return toMutableList.distinct() + } } - - } class TypeSerializer : JsonSerializer>() { @@ -69,5 +63,4 @@ class TypeSerializer : JsonSerializer>() { gen?.writeEndArray() } } - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Person.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Person.kt index 8a4e5711..661343a2 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Person.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/ap/Person.kt @@ -10,6 +10,8 @@ open class Person : Object { var publicKey: Key? = null protected constructor() : super() + + @Suppress("LongParameterList") constructor( type: List = emptyList(), name: String, @@ -21,7 +23,7 @@ open class Person : Object { url: String?, icon: Image?, publicKey: Key? - ) : super(add(type, "Person"), name,id = id) { + ) : super(add(type, "Person"), name, id = id) { this.preferredUsername = preferredUsername this.summary = summary this.inbox = inbox @@ -56,6 +58,4 @@ open class Person : Object { result = 31 * result + (publicKey?.hashCode() ?: 0) return result } - - } diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/api/Status.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/api/StatusForPost.kt similarity index 100% rename from src/main/kotlin/dev/usbharu/hideout/domain/model/api/Status.kt rename to src/main/kotlin/dev/usbharu/hideout/domain/model/api/StatusForPost.kt diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/RemoteUserCreateDto.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/RemoteUserCreateDto.kt index 35081932..f36eed2a 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/RemoteUserCreateDto.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/RemoteUserCreateDto.kt @@ -1,12 +1,12 @@ package dev.usbharu.hideout.domain.model.hideout.dto data class RemoteUserCreateDto( - val name:String, - val domain:String, - val screenName:String, - val description:String, - val inbox:String, - val outbox:String, - val url:String, - val publicKey:String, + val name: String, + val domain: String, + val screenName: String, + val description: String, + val inbox: String, + val outbox: String, + val url: String, + val publicKey: String, ) diff --git a/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/UserCreateDto.kt b/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/UserCreateDto.kt index e8a59f26..a57a8625 100644 --- a/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/UserCreateDto.kt +++ b/src/main/kotlin/dev/usbharu/hideout/domain/model/hideout/dto/UserCreateDto.kt @@ -1,8 +1,8 @@ package dev.usbharu.hideout.domain.model.hideout.dto data class UserCreateDto( - val name:String, - val screenName:String, - val description:String, - val password:String + val name: String, + val screenName: String, + val description: String, + val password: String ) diff --git a/src/main/kotlin/dev/usbharu/hideout/plugins/ActivityPub.kt b/src/main/kotlin/dev/usbharu/hideout/plugins/ActivityPub.kt index af7c4b86..a85eb163 100644 --- a/src/main/kotlin/dev/usbharu/hideout/plugins/ActivityPub.kt +++ b/src/main/kotlin/dev/usbharu/hideout/plugins/ActivityPub.kt @@ -61,9 +61,8 @@ val httpSignaturePlugin = createClientPlugin("HttpSign", ::HttpSignaturePluginCo format.timeZone = TimeZone.getTimeZone("GMT") onRequest { request, body -> - request.header("Date", format.format(Date())) - request.header("Host", "${request.url.host}") + request.header("Host", request.url.host) println(request.bodyType) println(request.bodyType?.type) if (request.bodyType?.type == String::class) { @@ -72,7 +71,7 @@ val httpSignaturePlugin = createClientPlugin("HttpSign", ::HttpSignaturePluginCo // UserAuthService.sha256.reset() val digest = Base64.getEncoder().encodeToString(UserAuthService.sha256.digest(body.toByteArray(Charsets.UTF_8))) - request.headers.append("Digest", "sha-256=" + digest) + request.headers.append("Digest", "sha-256=$digest") } if (request.headers.contains("Signature")) { @@ -82,11 +81,21 @@ val httpSignaturePlugin = createClientPlugin("HttpSign", ::HttpSignaturePluginCo s.split(",").forEach { parameters.add(it) } } - val keyId = parameters.find { it.startsWith("keyId") }?.split("=")?.get(1)?.replace("\"", "") + val keyId = parameters.find { it.startsWith("keyId") } + .orEmpty() + .split("=")[1] + .replace("\"", "") val algorithm = - parameters.find { it.startsWith("algorithm") }?.split("=")?.get(1)?.replace("\"", "") - val headers = parameters.find { it.startsWith("headers") }?.split("=")?.get(1)?.replace("\"", "") - ?.split(" ")?.toMutableList().orEmpty() + parameters.find { it.startsWith("algorithm") } + .orEmpty() + .split("=")[1] + .replace("\"", "") + val headers = parameters.find { it.startsWith("headers") } + .orEmpty() + .split("=")[1] + .replace("\"", "") + .split(" ") + .toMutableList() val algorithmType = when (algorithm) { "rsa-sha256" -> { @@ -132,32 +141,24 @@ val httpSignaturePlugin = createClientPlugin("HttpSign", ::HttpSignaturePluginCo request.headers.remove("Signature") signer!!.sign(object : HttpMessage, HttpRequest { - override fun headerValues(name: String?): MutableList { - return name?.let { request.headers.getAll(it) }?.toMutableList() ?: mutableListOf() - } + override fun headerValues(name: String?): MutableList = + name?.let { request.headers.getAll(it) }?.toMutableList() ?: mutableListOf() override fun addHeader(name: String?, value: String?) { val split = value?.split("=").orEmpty() name?.let { request.header(it, split.get(0) + "=\"" + split.get(1).trim('"') + "\"") } } - override fun method(): String { - return request.method.value - } - - override fun uri(): URI { - return request.url.build().toURI() - } - + override fun method(): String = request.method.value + override fun uri(): URI = request.url.build().toURI() }) val signatureHeader = request.headers.getAll("Signature").orEmpty() request.headers.remove("Signature") - signatureHeader.map { it.replace("; ", ",").replace(";", ",") }.joinToString(",") + signatureHeader.joinToString(",") { it.replace("; ", ",").replace(";", ",") } .let { request.header("Signature", it) } } - } } @@ -167,7 +168,8 @@ class KtorKeyMap(private val userAuthRepository: IUserRepository) : KeyMap { .substringAfterLast("/") val publicBytes = Base64.getDecoder().decode( userAuthRepository.findByNameAndDomain( - username, Config.configData.domain + username, + Config.configData.domain )?.publicKey?.replace("-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----")?.replace("", "") ?.replace("\n", "") ) @@ -180,7 +182,8 @@ class KtorKeyMap(private val userAuthRepository: IUserRepository) : KeyMap { .substringAfterLast("/") val publicBytes = Base64.getDecoder().decode( userAuthRepository.findByNameAndDomain( - username, Config.configData.domain + username, + Config.configData.domain )?.privateKey?.replace("-----BEGIN PRIVATE KEY-----", "")?.replace("-----END PRIVATE KEY-----", "") ?.replace("\n", "") ) @@ -188,7 +191,6 @@ class KtorKeyMap(private val userAuthRepository: IUserRepository) : KeyMap { return@runBlocking KeyFactory.getInstance("RSA").generatePrivate(x509EncodedKeySpec) } - override fun getSecretKey(keyId: String?): SecretKey { - TODO("Not yet implemented") - } + @Suppress("NotImplementedDeclaration") + override fun getSecretKey(keyId: String?): SecretKey = TODO("Not yet implemented") } diff --git a/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt b/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt index f6bebf53..fed45736 100644 --- a/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt +++ b/src/main/kotlin/dev/usbharu/hideout/plugins/Routing.kt @@ -31,6 +31,5 @@ fun Application.configureRouting( route("/api/v1") { statuses(postService) } - } } diff --git a/src/main/kotlin/dev/usbharu/hideout/plugins/Security.kt b/src/main/kotlin/dev/usbharu/hideout/plugins/Security.kt index f8a9e2b3..da66a042 100644 --- a/src/main/kotlin/dev/usbharu/hideout/plugins/Security.kt +++ b/src/main/kotlin/dev/usbharu/hideout/plugins/Security.kt @@ -1,16 +1,16 @@ +@file:Suppress("UnusedPrivateMember") + package dev.usbharu.hideout.plugins import dev.usbharu.hideout.service.IUserAuthService import io.ktor.server.application.* import io.ktor.server.auth.* -data class UserSession(val username: String) : Principal - -const val tokenAuth = "token-auth" +const val TOKEN_AUTH = "token-auth" fun Application.configureSecurity(userAuthService: IUserAuthService) { install(Authentication) { - bearer(tokenAuth) { + bearer(TOKEN_AUTH) { authenticate { bearerTokenCredential -> UserIdPrincipal(bearerTokenCredential.token) } diff --git a/src/main/kotlin/dev/usbharu/hideout/repository/IPostRepository.kt b/src/main/kotlin/dev/usbharu/hideout/repository/IPostRepository.kt index d7f523db..9fee2d02 100644 --- a/src/main/kotlin/dev/usbharu/hideout/repository/IPostRepository.kt +++ b/src/main/kotlin/dev/usbharu/hideout/repository/IPostRepository.kt @@ -4,7 +4,7 @@ import dev.usbharu.hideout.domain.model.Post import dev.usbharu.hideout.domain.model.PostEntity interface IPostRepository { - suspend fun insert(post:Post):PostEntity - suspend fun findOneById(id:Long):PostEntity - suspend fun delete(id:Long) + suspend fun insert(post: Post): PostEntity + suspend fun findOneById(id: Long): PostEntity + suspend fun delete(id: Long) } diff --git a/src/main/kotlin/dev/usbharu/hideout/repository/IUserRepository.kt b/src/main/kotlin/dev/usbharu/hideout/repository/IUserRepository.kt index 0d19094f..c35382dd 100644 --- a/src/main/kotlin/dev/usbharu/hideout/repository/IUserRepository.kt +++ b/src/main/kotlin/dev/usbharu/hideout/repository/IUserRepository.kt @@ -2,6 +2,7 @@ package dev.usbharu.hideout.repository import dev.usbharu.hideout.domain.model.hideout.entity.User +@Suppress("TooManyFunctions") interface IUserRepository { suspend fun save(user: User): User @@ -13,11 +14,11 @@ interface IUserRepository { suspend fun findByNameAndDomain(name: String, domain: String): User? - suspend fun findByDomain(domain:String): List + suspend fun findByDomain(domain: String): List - suspend fun findByNameAndDomains(names: List>): List + suspend fun findByNameAndDomains(names: List>): List - suspend fun findByUrl(url:String): User? + suspend fun findByUrl(url: String): User? suspend fun findByUrls(urls: List): List @@ -34,5 +35,5 @@ interface IUserRepository { suspend fun deleteFollower(id: Long, follower: Long) suspend fun findFollowersById(id: Long): List - suspend fun nextId():Long + suspend fun nextId(): Long } diff --git a/src/main/kotlin/dev/usbharu/hideout/repository/PostRepositoryImpl.kt b/src/main/kotlin/dev/usbharu/hideout/repository/PostRepositoryImpl.kt index 4d30dc68..237acb6b 100644 --- a/src/main/kotlin/dev/usbharu/hideout/repository/PostRepositoryImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/repository/PostRepositoryImpl.kt @@ -1,7 +1,10 @@ package dev.usbharu.hideout.repository import dev.usbharu.hideout.config.Config -import dev.usbharu.hideout.domain.model.* +import dev.usbharu.hideout.domain.model.Post +import dev.usbharu.hideout.domain.model.PostEntity +import dev.usbharu.hideout.domain.model.Posts +import dev.usbharu.hideout.domain.model.toPost import dev.usbharu.hideout.service.IdGenerateService import kotlinx.coroutines.Dispatchers import org.jetbrains.exposed.sql.* @@ -22,7 +25,6 @@ class PostRepositoryImpl(database: Database, private val idGenerateService: IdGe override suspend fun insert(post: Post): PostEntity { return query { - val generateId = idGenerateService.generateId() val name = Users.select { Users.id eq post.userId }.single().toUser().name val postUrl = Config.configData.url + "/users/$name/posts/$generateId" @@ -38,15 +40,15 @@ class PostRepositoryImpl(database: Database, private val idGenerateService: IdGe it[replyId] = post.replyId } return@query PostEntity( - generateId, - post.userId, - post.overview, - post.text, - post.createdAt, - post.visibility, - postUrl, - post.repostId, - post.replyId + id = generateId, + userId = post.userId, + overview = post.overview, + text = post.text, + createdAt = post.createdAt, + visibility = post.visibility, + url = postUrl, + repostId = post.repostId, + replyId = post.replyId ) } } diff --git a/src/main/kotlin/dev/usbharu/hideout/repository/UserRepository.kt b/src/main/kotlin/dev/usbharu/hideout/repository/UserRepository.kt index 9a577a83..2f2905d8 100644 --- a/src/main/kotlin/dev/usbharu/hideout/repository/UserRepository.kt +++ b/src/main/kotlin/dev/usbharu/hideout/repository/UserRepository.kt @@ -136,13 +136,13 @@ class UserRepository(private val database: Database, private val idGenerateServi Users.innerJoin( otherTable = UsersFollowers, onColumn = { Users.id }, - otherColumn = { userId }) - + otherColumn = { userId } + ) .innerJoin( otherTable = followers, onColumn = { UsersFollowers.followerId }, - otherColumn = { followers[Users.id] }) - + otherColumn = { followers[Users.id] } + ) .slice( followers.get(Users.id), followers.get(Users.name), @@ -177,7 +177,6 @@ class UserRepository(private val database: Database, private val idGenerateServi } } - override suspend fun delete(id: Long) { query { Users.deleteWhere { Users.id.eq(id) } @@ -202,9 +201,7 @@ class UserRepository(private val database: Database, private val idGenerateServi } } - override suspend fun nextId(): Long { - return idGenerateService.generateId() - } + override suspend fun nextId(): Long = idGenerateService.generateId() } object Users : Table("users") { @@ -230,18 +227,18 @@ object Users : Table("users") { fun ResultRow.toUser(): User { return User( - this[Users.id], - this[Users.name], - this[Users.domain], - this[Users.screenName], - this[Users.description], - this[Users.password], - this[Users.inbox], - this[Users.outbox], - this[Users.url], - this[Users.publicKey], - this[Users.privateKey], - Instant.ofEpochMilli((this[Users.createdAt])) + id = this[Users.id], + name = this[Users.name], + domain = this[Users.domain], + screenName = this[Users.screenName], + description = this[Users.description], + password = this[Users.password], + inbox = this[Users.inbox], + outbox = this[Users.outbox], + url = this[Users.url], + publicKey = this[Users.publicKey], + privateKey = this[Users.privateKey], + createdAt = Instant.ofEpochMilli((this[Users.createdAt])) ) } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt index c20221cc..28468a66 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/RegisterRouting.kt @@ -10,7 +10,6 @@ import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.register(userService: IUserService) { - routing { get("/register") { val principal = call.principal() diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRouting.kt index 9ab1d098..ea646104 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRouting.kt @@ -14,59 +14,63 @@ import io.ktor.server.routing.* fun Routing.inbox( httpSignatureVerifyService: HttpSignatureVerifyService, activityPubService: dev.usbharu.hideout.service.activitypub.ActivityPubService -){ - - route("/inbox") { - get { - call.respond(HttpStatusCode.MethodNotAllowed) +) { + route("/inbox") { + get { + call.respond(HttpStatusCode.MethodNotAllowed) + } + post { + if (httpSignatureVerifyService.verify(call.request.headers).not()) { + throw HttpSignatureVerifyException() } - post { - if (httpSignatureVerifyService.verify(call.request.headers).not()) { - throw HttpSignatureVerifyException() - } - val json = call.receiveText() - call.application.log.trace("Received: $json") - val activityTypes = activityPubService.parseActivity(json) - call.application.log.debug("ActivityTypes: ${activityTypes.name}") - val response = activityPubService.processActivity(json, activityTypes) - when (response) { - is ActivityPubObjectResponse -> call.respond( - response.httpStatusCode, - Config.configData.objectMapper.writeValueAsString(response.message.apply { + val json = call.receiveText() + call.application.log.trace("Received: $json") + val activityTypes = activityPubService.parseActivity(json) + call.application.log.debug("ActivityTypes: ${activityTypes.name}") + val response = activityPubService.processActivity(json, activityTypes) + when (response) { + is ActivityPubObjectResponse -> call.respond( + response.httpStatusCode, + Config.configData.objectMapper.writeValueAsString( + response.message.apply { context = listOf("https://www.w3.org/ns/activitystreams") - }) + } ) - is ActivityPubStringResponse -> call.respond(response.httpStatusCode, response.message) - null -> call.respond(HttpStatusCode.NotImplemented) - } + ) + + is ActivityPubStringResponse -> call.respond(response.httpStatusCode, response.message) + null -> call.respond(HttpStatusCode.NotImplemented) } } - route("/users/{name}/inbox"){ - get { - call.respond(HttpStatusCode.MethodNotAllowed) + } + route("/users/{name}/inbox") { + get { + call.respond(HttpStatusCode.MethodNotAllowed) + } + post { + if (httpSignatureVerifyService.verify(call.request.headers).not()) { + throw HttpSignatureVerifyException() } - post { - if (httpSignatureVerifyService.verify(call.request.headers).not()) { - throw HttpSignatureVerifyException() - } - val json = call.receiveText() - call.application.log.trace("Received: $json") - val activityTypes = activityPubService.parseActivity(json) - call.application.log.debug("ActivityTypes: ${activityTypes.name}") - val response = activityPubService.processActivity(json, activityTypes) - when (response) { - is ActivityPubObjectResponse -> call.respond( - response.httpStatusCode, - Config.configData.objectMapper.writeValueAsString(response.message.apply { + val json = call.receiveText() + call.application.log.trace("Received: $json") + val activityTypes = activityPubService.parseActivity(json) + call.application.log.debug("ActivityTypes: ${activityTypes.name}") + val response = activityPubService.processActivity(json, activityTypes) + when (response) { + is ActivityPubObjectResponse -> call.respond( + response.httpStatusCode, + Config.configData.objectMapper.writeValueAsString( + response.message.apply { context = listOf("https://www.w3.org/ns/activitystreams") - }) + } ) - is ActivityPubStringResponse -> call.respond(response.httpStatusCode, response.message) - null -> call.respond(HttpStatusCode.NotImplemented) - } + ) + + is ActivityPubStringResponse -> call.respond(response.httpStatusCode, response.message) + null -> call.respond(HttpStatusCode.NotImplemented) } } - + } } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/OutboxRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/OutboxRouting.kt index 7bfced91..3ad07137 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/OutboxRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/OutboxRouting.kt @@ -6,22 +6,20 @@ import io.ktor.server.response.* import io.ktor.server.routing.* fun Routing.outbox() { - - route("/outbox") { - get { - call.respond(HttpStatusCode.NotImplemented) - } - post { - call.respond(HttpStatusCode.NotImplemented) - } + route("/outbox") { + get { + call.respond(HttpStatusCode.NotImplemented) } - route("/users/{name}/outbox"){ - get { - call.respond(HttpStatusCode.NotImplemented) - } - post { - call.respond(HttpStatusCode.NotImplemented) - } + post { + call.respond(HttpStatusCode.NotImplemented) } - + } + route("/users/{name}/outbox") { + get { + call.respond(HttpStatusCode.NotImplemented) + } + post { + call.respond(HttpStatusCode.NotImplemented) + } + } } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt index 10401627..5a9edcb4 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/activitypub/UserRouting.kt @@ -34,16 +34,14 @@ fun Routing.usersAP(activityPubUserService: ActivityPubUserService, userService: class ContentTypeRouteSelector(private vararg val contentType: ContentType) : RouteSelector() { override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation { - context.call.application.log.debug("Accept: ${context.call.request.accept()}") val requestContentType = context.call.request.accept() ?: return RouteSelectorEvaluation.FailedParameter return if (requestContentType.split(",") - .find { contentType.find { contentType -> contentType.match(it) } != null } != null + .find { contentType.find { contentType -> contentType.match(it) } != null } != null ) { RouteSelectorEvaluation.Constant } else { RouteSelectorEvaluation.FailedParameter } } - } diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/api/v1/Statuses.kt b/src/main/kotlin/dev/usbharu/hideout/routing/api/v1/Statuses.kt index 710354a0..e6c08942 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/api/v1/Statuses.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/api/v1/Statuses.kt @@ -3,7 +3,6 @@ package dev.usbharu.hideout.routing.api.v1 import dev.usbharu.hideout.domain.model.Post import dev.usbharu.hideout.domain.model.api.StatusForPost import dev.usbharu.hideout.service.IPostService -import dev.usbharu.hideout.service.impl.PostService import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* diff --git a/src/main/kotlin/dev/usbharu/hideout/routing/wellknown/WebfingerRouting.kt b/src/main/kotlin/dev/usbharu/hideout/routing/wellknown/WebfingerRouting.kt index 411e3095..e5bd34bf 100644 --- a/src/main/kotlin/dev/usbharu/hideout/routing/wellknown/WebfingerRouting.kt +++ b/src/main/kotlin/dev/usbharu/hideout/routing/wellknown/WebfingerRouting.kt @@ -11,8 +11,8 @@ import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* -fun Routing.webfinger(userService: IUserService){ - route("/.well-known/webfinger"){ +fun Routing.webfinger(userService: IUserService) { + route("/.well-known/webfinger") { get { val acct = call.request.queryParameters["resource"]?.decodeURLPart() ?: throw ParameterNotExistException("Parameter(name='resource') does not exist.") diff --git a/src/main/kotlin/dev/usbharu/hideout/service/IPostService.kt b/src/main/kotlin/dev/usbharu/hideout/service/IPostService.kt index 52e3ba05..b523cb1e 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/IPostService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/IPostService.kt @@ -3,5 +3,5 @@ package dev.usbharu.hideout.service import dev.usbharu.hideout.domain.model.Post interface IPostService { - suspend fun create(post:Post) + suspend fun create(post: Post) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/IUserAuthService.kt b/src/main/kotlin/dev/usbharu/hideout/service/IUserAuthService.kt index 5c792ec8..102db32e 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/IUserAuthService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/IUserAuthService.kt @@ -7,8 +7,7 @@ interface IUserAuthService { suspend fun usernameAlreadyUse(username: String): Boolean - suspend fun generateKeyPair():KeyPair + suspend fun generateKeyPair(): KeyPair suspend fun verifyAccount(username: String, password: String): Boolean - } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/IdGenerateService.kt b/src/main/kotlin/dev/usbharu/hideout/service/IdGenerateService.kt index 8a74d9e4..b27cef4c 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/IdGenerateService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/IdGenerateService.kt @@ -1,5 +1,5 @@ package dev.usbharu.hideout.service interface IdGenerateService { - suspend fun generateId():Long + suspend fun generateId(): Long } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/SnowflakeIdGenerateService.kt b/src/main/kotlin/dev/usbharu/hideout/service/SnowflakeIdGenerateService.kt index 69cda875..6e95140a 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/SnowflakeIdGenerateService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/SnowflakeIdGenerateService.kt @@ -5,7 +5,8 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.time.Instant -open class SnowflakeIdGenerateService(private val baseTime:Long) : IdGenerateService { +@Suppress("MagicNumber") +open class SnowflakeIdGenerateService(private val baseTime: Long) : IdGenerateService { var lastTimeStamp: Long = -1 var sequenceId: Int = 0 val mutex = Mutex() @@ -13,22 +14,15 @@ open class SnowflakeIdGenerateService(private val baseTime:Long) : IdGenerateSer @Throws(IllegalStateException::class) override suspend fun generateId(): Long { return mutex.withLock { - var timestamp = getTime() if (timestamp < lastTimeStamp) { - while (timestamp <= lastTimeStamp) { - delay(1L) - timestamp = getTime() - } + timestamp = wait(timestamp) // throw IllegalStateException(" $lastTimeStamp $timestamp ${lastTimeStamp-timestamp} ") } if (timestamp == lastTimeStamp) { sequenceId++ if (sequenceId >= 4096) { - while (timestamp <= lastTimeStamp) { - delay(1L) - timestamp = getTime() - } + timestamp = wait(timestamp) sequenceId = 0 } } else { @@ -37,11 +31,16 @@ open class SnowflakeIdGenerateService(private val baseTime:Long) : IdGenerateSer lastTimeStamp = timestamp return@withLock (timestamp - baseTime).shl(22).or(1L.shl(12)).or(sequenceId.toLong()) } - - } - private fun getTime(): Long { - return Instant.now().toEpochMilli() + private suspend fun wait(timestamp: Long): Long { + var timestamp1 = timestamp + while (timestamp1 <= lastTimeStamp) { + delay(1L) + timestamp1 = getTime() + } + return timestamp1 } + + private fun getTime(): Long = Instant.now().toEpochMilli() } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateService.kt b/src/main/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateService.kt index 7eb6b391..2902a044 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateService.kt @@ -1,4 +1,5 @@ package dev.usbharu.hideout.service // 2010-11-04T01:42:54.657 +@Suppress("MagicNumber") object TwitterSnowflakeIdGenerateService : SnowflakeIdGenerateService(1288834974657L) diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowService.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowService.kt index ed2d0ec9..40e45767 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowService.kt @@ -1,11 +1,11 @@ package dev.usbharu.hideout.service.activitypub -import dev.usbharu.hideout.domain.model.ap.Follow import dev.usbharu.hideout.domain.model.ActivityPubResponse +import dev.usbharu.hideout.domain.model.ap.Follow import dev.usbharu.hideout.domain.model.job.ReceiveFollowJob import kjob.core.job.JobProps interface ActivityPubFollowService { - suspend fun receiveFollow(follow: Follow):ActivityPubResponse + suspend fun receiveFollow(follow: Follow): ActivityPubResponse suspend fun receiveFollowJob(props: JobProps) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImpl.kt index 988cb81e..2eb571ff 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImpl.kt @@ -33,7 +33,7 @@ class ActivityPubFollowServiceImpl( override suspend fun receiveFollowJob(props: JobProps) { val actor = props[ReceiveFollowJob.actor] val targetActor = props[ReceiveFollowJob.targetActor] - val person = activityPubUserService.fetchPerson(actor,targetActor) + val person = activityPubUserService.fetchPerson(actor, targetActor) val follow = Config.configData.objectMapper.readValue(props[ReceiveFollowJob.follow]) httpClient.postAp( urlString = person.inbox ?: throw IllegalArgumentException("inbox is not found"), diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteService.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteService.kt index b36aeec4..33ba42cc 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteService.kt @@ -6,6 +6,6 @@ import kjob.core.job.JobProps interface ActivityPubNoteService { - suspend fun createNote(post:PostEntity) - suspend fun createNoteJob(props:JobProps) + suspend fun createNote(post: PostEntity) + suspend fun createNoteJob(props: JobProps) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImpl.kt index 72eb6acf..d49bc03c 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImpl.kt @@ -35,7 +35,6 @@ class ActivityPubNoteServiceImpl( } } - override suspend fun createNoteJob(props: JobProps) { val actor = props[DeliverPostJob.actor] val postEntity = Config.configData.objectMapper.readValue(props[DeliverPostJob.post]) diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubService.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubService.kt index 939d3d3b..df6f24ac 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubService.kt @@ -9,7 +9,7 @@ interface ActivityPubService { suspend fun processActivity(json: String, type: ActivityType): ActivityPubResponse? - suspend fun processActivity(job: JobContextWithProps,hideoutJob: HideoutJob) + suspend fun processActivity(job: JobContextWithProps, hideoutJob: HideoutJob) } enum class ActivityType { diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubServiceImpl.kt index 320359d3..aa95000a 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubServiceImpl.kt @@ -10,6 +10,7 @@ import dev.usbharu.hideout.domain.model.job.ReceiveFollowJob import dev.usbharu.hideout.exception.JsonParseException import kjob.core.dsl.JobContextWithProps import kjob.core.job.JobProps +import org.slf4j.Logger import org.slf4j.LoggerFactory class ActivityPubServiceImpl( @@ -17,7 +18,7 @@ class ActivityPubServiceImpl( private val activityPubNoteService: ActivityPubNoteService ) : ActivityPubService { - val logger = LoggerFactory.getLogger(this::class.java) + val logger: Logger = LoggerFactory.getLogger(this::class.java) override fun parseActivity(json: String): ActivityType { val readTree = Config.configData.objectMapper.readTree(json) logger.debug("readTree: {}", readTree) @@ -33,6 +34,7 @@ class ActivityPubServiceImpl( return ActivityType.values().first { it.name.equals(type.asText(), true) } } + @Suppress("CyclomaticComplexMethod", "NotImplementedDeclaration") override suspend fun processActivity(json: String, type: ActivityType): ActivityPubResponse { return when (type) { ActivityType.Accept -> TODO() @@ -80,6 +82,4 @@ class ActivityPubServiceImpl( DeliverPostJob -> activityPubNoteService.createNoteJob(job.props as JobProps) } } - - } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserService.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserService.kt index 3446da24..659d134a 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserService.kt @@ -3,7 +3,7 @@ package dev.usbharu.hideout.service.activitypub import dev.usbharu.hideout.domain.model.ap.Person interface ActivityPubUserService { - suspend fun getPersonByName(name:String): Person + suspend fun getPersonByName(name: String): Person suspend fun fetchPerson(url: String, targetActor: String? = null): Person } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserServiceImpl.kt index 94c8557a..18811258 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubUserServiceImpl.kt @@ -15,7 +15,6 @@ import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* -import org.slf4j.LoggerFactory class ActivityPubUserServiceImpl( private val userService: IUserService, @@ -23,7 +22,6 @@ class ActivityPubUserServiceImpl( ) : ActivityPubUserService { - private val logger = LoggerFactory.getLogger(this::class.java) override suspend fun getPersonByName(name: String): Person { // TODO: JOINで書き直し val userEntity = userService.findByNameLocalUser(name) @@ -79,11 +77,10 @@ class ActivityPubUserServiceImpl( publicKeyPem = userEntity.publicKey ) ) - } catch (e: UserNotFoundException) { val httpResponse = if (targetActor != null) { - httpClient.getAp(url,"$targetActor#pubkey") - }else { + httpClient.getAp(url, "$targetActor#pubkey") + } else { httpClient.get(url) { accept(ContentType.Application.Activity) } @@ -95,16 +92,17 @@ class ActivityPubUserServiceImpl( name = person.preferredUsername ?: throw IllegalActivityPubObjectException("preferredUsername is null"), domain = url.substringAfter("://").substringBeforeLast("/"), - screenName = (person.name ?: person.preferredUsername) ?: throw IllegalActivityPubObjectException("preferredUsername is null"), - description = person.summary ?: "", + screenName = (person.name ?: person.preferredUsername) + ?: throw IllegalActivityPubObjectException("preferredUsername is null"), + description = person.summary.orEmpty(), inbox = person.inbox ?: throw IllegalActivityPubObjectException("inbox is null"), outbox = person.outbox ?: throw IllegalActivityPubObjectException("outbox is null"), url = url, - publicKey = person.publicKey?.publicKeyPem ?: throw IllegalActivityPubObjectException("publicKey is null"), + publicKey = person.publicKey?.publicKeyPem + ?: throw IllegalActivityPubObjectException("publicKey is null"), ) ) person } - } } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/impl/IUserService.kt b/src/main/kotlin/dev/usbharu/hideout/service/impl/IUserService.kt index b41f31fd..d2d61b1b 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/impl/IUserService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/impl/IUserService.kt @@ -4,6 +4,7 @@ import dev.usbharu.hideout.domain.model.hideout.dto.RemoteUserCreateDto import dev.usbharu.hideout.domain.model.hideout.dto.UserCreateDto import dev.usbharu.hideout.domain.model.hideout.entity.User +@Suppress("TooManyFunctions") interface IUserService { suspend fun findAll(limit: Int? = 100, offset: Long? = 0): List diff --git a/src/main/kotlin/dev/usbharu/hideout/service/impl/PostService.kt b/src/main/kotlin/dev/usbharu/hideout/service/impl/PostService.kt index 71b1b10f..e14694a2 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/impl/PostService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/impl/PostService.kt @@ -4,14 +4,17 @@ import dev.usbharu.hideout.domain.model.Post import dev.usbharu.hideout.repository.IPostRepository import dev.usbharu.hideout.service.IPostService import dev.usbharu.hideout.service.activitypub.ActivityPubNoteService -import dev.usbharu.hideout.service.job.JobQueueParentService import org.slf4j.LoggerFactory -class PostService(private val postRepository:IPostRepository,private val activityPubNoteService: ActivityPubNoteService) : IPostService { +class PostService( + private val postRepository: IPostRepository, + private val activityPubNoteService: ActivityPubNoteService +) : IPostService { private val logger = LoggerFactory.getLogger(this::class.java) + override suspend fun create(post: Post) { - logger.debug("create post={}",post) + logger.debug("create post={}", post) val postEntity = postRepository.insert(post) activityPubNoteService.createNote(postEntity) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/impl/UserAuthService.kt b/src/main/kotlin/dev/usbharu/hideout/service/impl/UserAuthService.kt index 60aa97a4..2d1ef29b 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/impl/UserAuthService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/impl/UserAuthService.kt @@ -12,14 +12,13 @@ class UserAuthService( val userRepository: IUserRepository ) : IUserAuthService { - override fun hash(password: String): String { val digest = sha256.digest(password.toByteArray(Charsets.UTF_8)) return hex(digest) } override suspend fun usernameAlreadyUse(username: String): Boolean { - userRepository.findByName(username) ?: return false + userRepository.findByName(username) return true } @@ -31,24 +30,25 @@ class UserAuthService( override suspend fun generateKeyPair(): KeyPair { val keyPairGenerator = KeyPairGenerator.getInstance("RSA") - keyPairGenerator.initialize(2048) + keyPairGenerator.initialize(keySize) return keyPairGenerator.generateKeyPair() } - companion object { val sha256: MessageDigest = MessageDigest.getInstance("SHA-256") + const val keySize = 2048 + const val pemSize = 64 } } fun PublicKey.toPem(): String { return "-----BEGIN PUBLIC KEY-----\n" + - Base64.getEncoder().encodeToString(encoded).chunked(64).joinToString("\n") + - "\n-----END PUBLIC KEY-----\n" + Base64.getEncoder().encodeToString(encoded).chunked(UserAuthService.pemSize).joinToString("\n") + + "\n-----END PUBLIC KEY-----\n" } fun PrivateKey.toPem(): String { return "-----BEGIN PRIVATE KEY-----\n" + - Base64.getEncoder().encodeToString(encoded).chunked(64).joinToString("\n") + - "\n-----END PRIVATE KEY-----\n" + Base64.getEncoder().encodeToString(encoded).chunked(UserAuthService.pemSize).joinToString("\n") + + "\n-----END PRIVATE KEY-----\n" } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/impl/UserService.kt b/src/main/kotlin/dev/usbharu/hideout/service/impl/UserService.kt index fcf30dcb..3118967c 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/impl/UserService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/impl/UserService.kt @@ -15,41 +15,31 @@ class UserService(private val userRepository: IUserRepository, private val userA private val maxLimit = 100 override suspend fun findAll(limit: Int?, offset: Long?): List { - return userRepository.findAllByLimitAndByOffset( min(limit ?: maxLimit, maxLimit), offset ?: 0 ) } - override suspend fun findById(id: Long): User { - return userRepository.findById(id) ?: throw UserNotFoundException("$id was not found.") - } + override suspend fun findById(id: Long): User = + userRepository.findById(id) ?: throw UserNotFoundException("$id was not found.") - override suspend fun findByIds(ids: List): List { - return userRepository.findByIds(ids) - } + override suspend fun findByIds(ids: List): List = userRepository.findByIds(ids) - override suspend fun findByName(name: String): List { - return userRepository.findByName(name) - } + override suspend fun findByName(name: String): List = userRepository.findByName(name) override suspend fun findByNameLocalUser(name: String): User { return userRepository.findByNameAndDomain(name, Config.configData.domain) ?: throw UserNotFoundException("$name was not found.") } - override suspend fun findByNameAndDomains(names: List>): List { - return userRepository.findByNameAndDomains(names) - } + override suspend fun findByNameAndDomains(names: List>): List = + userRepository.findByNameAndDomains(names) - override suspend fun findByUrl(url: String): User { - return userRepository.findByUrl(url) ?: throw UserNotFoundException("$url was not found.") - } + override suspend fun findByUrl(url: String): User = + userRepository.findByUrl(url) ?: throw UserNotFoundException("$url was not found.") - override suspend fun findByUrls(urls: List): List { - return userRepository.findByUrls(urls) - } + override suspend fun findByUrls(urls: List): List = userRepository.findByUrls(urls) override suspend fun usernameAlreadyUse(username: String): Boolean { val findByNameAndDomain = userRepository.findByNameAndDomain(username, Config.configData.domain) @@ -58,7 +48,7 @@ class UserService(private val userRepository: IUserRepository, private val userA override suspend fun createLocalUser(user: UserCreateDto): User { val nextId = userRepository.nextId() - val HashedPassword = userAuthService.hash(user.password) + val hashedPassword = userAuthService.hash(user.password) val keyPair = userAuthService.generateKeyPair() val userEntity = User( id = nextId, @@ -66,13 +56,13 @@ class UserService(private val userRepository: IUserRepository, private val userA domain = Config.configData.domain, screenName = user.screenName, description = user.description, - password = HashedPassword, + password = hashedPassword, inbox = "${Config.configData.url}/users/${user.name}/inbox", outbox = "${Config.configData.url}/users/${user.name}/outbox", url = "${Config.configData.url}/users/${user.name}", publicKey = keyPair.public.toPem(), privateKey = keyPair.private.toPem(), - Instant.now() + createdAt = Instant.now() ) return userRepository.save(userEntity) } @@ -94,12 +84,7 @@ class UserService(private val userRepository: IUserRepository, private val userA return userRepository.save(userEntity) } - override suspend fun findFollowersById(id: Long): List { - return userRepository.findFollowersById(id) - } - - override suspend fun addFollowers(id: Long, follower: Long) { - return userRepository.createFollower(id, follower) - } + override suspend fun findFollowersById(id: Long): List = userRepository.findFollowersById(id) + override suspend fun addFollowers(id: Long, follower: Long) = userRepository.createFollower(id, follower) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueParentService.kt b/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueParentService.kt index 4029514b..f553c227 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueParentService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueParentService.kt @@ -5,6 +5,6 @@ import kjob.core.dsl.ScheduleContext interface JobQueueParentService { - fun init(jobDefines:List) + fun init(jobDefines: List) suspend fun schedule(job: J, block: ScheduleContext.(J) -> Unit = {}) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueWorkerService.kt b/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueWorkerService.kt index 0d15caae..567f9e21 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueWorkerService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/job/JobQueueWorkerService.kt @@ -1,10 +1,10 @@ package dev.usbharu.hideout.service.job import kjob.core.Job -import kjob.core.dsl.JobContextWithProps -import kjob.core.dsl.JobRegisterContext import kjob.core.dsl.KJobFunctions +import kjob.core.dsl.JobContextWithProps as JCWP +import kjob.core.dsl.JobRegisterContext as JRC interface JobQueueWorkerService { - fun init(defines: List>.(Job) -> KJobFunctions>>>) + fun init(defines: List>.(Job) -> KJobFunctions>>>) } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueParentService.kt b/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueParentService.kt index 0058638e..d5367d80 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueParentService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueParentService.kt @@ -17,9 +17,7 @@ class KJobJobQueueParentService(private val database: Database) : JobQueueParent isWorker = false }.start() - override fun init(jobDefines: List) { - - } + override fun init(jobDefines: List) = Unit override suspend fun schedule(job: J, block: ScheduleContext.(J) -> Unit) { logger.debug("schedule job={}", job.name) diff --git a/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueWorkerService.kt b/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueWorkerService.kt index cab3dcc8..67d84821 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueWorkerService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/job/KJobJobQueueWorkerService.kt @@ -2,11 +2,11 @@ package dev.usbharu.hideout.service.job import dev.usbharu.kjob.exposed.ExposedKJob import kjob.core.Job -import kjob.core.dsl.JobContextWithProps -import kjob.core.dsl.JobRegisterContext import kjob.core.dsl.KJobFunctions import kjob.core.kjob import org.jetbrains.exposed.sql.Database +import kjob.core.dsl.JobContextWithProps as JCWP +import kjob.core.dsl.JobRegisterContext as JRC class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorkerService { @@ -19,10 +19,11 @@ class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorker }.start() } - override fun init(defines: List>.(Job) -> KJobFunctions>>>) { + override fun init( + defines: List>.(Job) -> KJobFunctions>>> + ) { defines.forEach { job -> kjob.register(job.first, job.second) } } - } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyService.kt b/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyService.kt index 34706206..daa2043d 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyService.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyService.kt @@ -3,5 +3,5 @@ package dev.usbharu.hideout.service.signature import io.ktor.http.* interface HttpSignatureVerifyService { - fun verify(headers:Headers):Boolean + fun verify(headers: Headers): Boolean } diff --git a/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyServiceImpl.kt b/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyServiceImpl.kt index 5c74f11d..923231c6 100644 --- a/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyServiceImpl.kt +++ b/src/main/kotlin/dev/usbharu/hideout/service/signature/HttpSignatureVerifyServiceImpl.kt @@ -2,24 +2,22 @@ package dev.usbharu.hideout.service.signature import dev.usbharu.hideout.plugins.KtorKeyMap import dev.usbharu.hideout.repository.IUserRepository -import dev.usbharu.hideout.service.IUserAuthService import io.ktor.http.* -import tech.barbero.http.message.signing.HttpMessage import tech.barbero.http.message.signing.SignatureHeaderVerifier class HttpSignatureVerifyServiceImpl(private val userAuthService: IUserRepository) : HttpSignatureVerifyService { override fun verify(headers: Headers): Boolean { val build = SignatureHeaderVerifier.builder().keyMap(KtorKeyMap(userAuthService)).build() return true - build.verify(object : HttpMessage { - override fun headerValues(name: String?): MutableList { - return name?.let { headers.getAll(it) }?.toMutableList() ?: mutableListOf() - } - - override fun addHeader(name: String?, value: String?) { - TODO() - } - - }) +// build.verify(object : HttpMessage { +// override fun headerValues(name: String?): MutableList { +// return name?.let { headers.getAll(it) }?.toMutableList() ?: mutableListOf() +// } +// +// override fun addHeader(name: String?, value: String?) { +// TODO() +// } +// +// }) } } diff --git a/src/main/kotlin/dev/usbharu/hideout/util/HttpUtil.kt b/src/main/kotlin/dev/usbharu/hideout/util/HttpUtil.kt index 90773182..78d01376 100644 --- a/src/main/kotlin/dev/usbharu/hideout/util/HttpUtil.kt +++ b/src/main/kotlin/dev/usbharu/hideout/util/HttpUtil.kt @@ -3,6 +3,18 @@ package dev.usbharu.hideout.util import io.ktor.http.* object HttpUtil { + val ContentType.Application.Activity: ContentType + get() = ContentType("application", "activity+json") + + val ContentType.Application.JsonLd: ContentType + get() { + return ContentType( + contentType = "application", + contentSubtype = "ld+json", + parameters = listOf(HeaderValueParam("profile", "https://www.w3.org/ns/activitystreams")) + ) + } + fun isContentTypeOfActivityPub( contentType: String, subType: String, @@ -25,15 +37,5 @@ object HttpUtil { contentType.parameter("profile").orEmpty() ) } - - val ContentType.Application.Activity: ContentType - get() = ContentType("application", "activity+json") - - val ContentType.Application.JsonLd: ContentType - get() = ContentType( - "application", - "ld+json", - listOf(HeaderValueParam("profile", "https://www.w3.org/ns/activitystreams")) - ) // fun } diff --git a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedJobRepository.kt b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedJobRepository.kt index 0c7f66dd..a9f5e5bb 100644 --- a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedJobRepository.kt +++ b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedJobRepository.kt @@ -56,7 +56,6 @@ class ExposedJobRepository( suspend fun query(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } - override suspend fun completeProgress(id: String): Boolean { val now = Instant.now(clock).toEpochMilli() return query { @@ -86,12 +85,17 @@ class ExposedJobRepository( override suspend fun get(id: String): ScheduledJob? { val single = query { jobs.select(jobs.id eq id.toLong()).singleOrNull() } ?: return null return single.toScheduledJob() - } override suspend fun reset(id: String, oldKjobId: UUID?): Boolean { return query { - jobs.update({ jobs.id eq id.toLong() and if (oldKjobId == null) jobs.kjobId.isNull() else jobs.kjobId eq oldKjobId.toString() }) { + jobs.update({ + jobs.id eq id.toLong() and if (oldKjobId == null) { + jobs.kjobId.isNull() + } else { + jobs.kjobId eq oldKjobId.toString() + } + }) { it[jobs.status] = JobStatus.CREATED.name it[jobs.statusMessage] = null it[jobs.kjobId] = null @@ -107,7 +111,18 @@ class ExposedJobRepository( override suspend fun save(jobSettings: JobSettings, runAt: Instant?): ScheduledJob { val now = Instant.now(clock) val scheduledJob = - ScheduledJob("", JobStatus.CREATED, runAt, null, 0, null, now, now, jobSettings, JobProgress(0)) + ScheduledJob( + id = "", + status = JobStatus.CREATED, + runAt = runAt, + statusMessage = null, + retries = 0, + kjobId = null, + createdAt = now, + updatedAt = now, + settings = jobSettings, + progress = JobProgress(0) + ) val id = query { jobs.insert { it[jobs.status] = scheduledJob.status.name @@ -168,7 +183,13 @@ class ExposedJobRepository( retries: Int ): Boolean { return query { - jobs.update({ (jobs.id eq id.toLong()) and if (oldKjobId == null) jobs.kjobId.isNull() else jobs.kjobId eq oldKjobId.toString() }) { + jobs.update({ + (jobs.id eq id.toLong()) and if (oldKjobId == null) { + jobs.kjobId.isNull() + } else { + jobs.kjobId eq oldKjobId.toString() + } + }) { it[jobs.status] = status.name it[jobs.retries] = retries it[jobs.updatedAt] = Instant.now(clock).toEpochMilli() @@ -214,6 +235,7 @@ class ExposedJobRepository( return null } + @Suppress("UNCHECKED_CAST") fun listSerialize(value: List<*>): JsonElement { return if (value.isEmpty()) { buildJsonObject { @@ -227,7 +249,7 @@ class ExposedJobRepository( is Int -> "i" to (value as List).map(::JsonPrimitive) is String -> "s" to (value as List).map(::JsonPrimitive) is Boolean -> "b" to (value as List).map(::JsonPrimitive) - else -> error("Cannot serialize unsupported list property value: $value") + else -> error("Cannot serialize unsupported list property value: $item") } buildJsonObject { put("t", t) @@ -265,6 +287,7 @@ class ExposedJobRepository( retries = single[retries], kjobId = single[kjobId]?.let { try { + @Suppress("SwallowedException") UUID.fromString(it) } catch (e: IllegalArgumentException) { null diff --git a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedKJob.kt b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedKJob.kt index 76d00008..7d1f59ac 100644 --- a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedKJob.kt +++ b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedKJob.kt @@ -9,24 +9,6 @@ import java.time.Clock class ExposedKJob(config: Configuration) : BaseKJob(config) { - companion object : KJobFactory { - override fun create(configure: Configuration.() -> Unit): KJob { - return ExposedKJob(Configuration().apply(configure)) - } - } - - class Configuration : BaseKJob.Configuration() { - var connectionString: String? = null - var driverClassName: String? = null - var connectionDatabase: Database? = null - - var jobTableName = "kjobJobs" - - var lockTableName = "kjobLocks" - - var expireLockInMinutes = 5L - } - private val database: Database = config.connectionDatabase ?: Database.connect( requireNotNull(config.connectionString), requireNotNull(config.driverClassName) @@ -34,6 +16,7 @@ class ExposedKJob(config: Configuration) : BaseKJob(c override val jobRepository: ExposedJobRepository get() = ExposedJobRepository(database, config.jobTableName, Clock.systemUTC(), config.json) + override val lockRepository: ExposedLockRepository get() = ExposedLockRepository(database, config, clock) @@ -47,4 +30,20 @@ class ExposedKJob(config: Configuration) : BaseKJob(c super.shutdown() lockRepository.clearExpired() } + + companion object : KJobFactory { + override fun create(configure: Configuration.() -> Unit): KJob = ExposedKJob(Configuration().apply(configure)) + } + + class Configuration : BaseKJob.Configuration() { + var connectionString: String? = null + var driverClassName: String? = null + var connectionDatabase: Database? = null + + var jobTableName = "kjobJobs" + + var lockTableName = "kjobLocks" + + var expireLockInMinutes = 5L + } } diff --git a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedLockRepository.kt b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedLockRepository.kt index 76d6fa44..9ed2146f 100644 --- a/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedLockRepository.kt +++ b/src/main/kotlin/dev/usbharu/kjob/exposed/ExposedLockRepository.kt @@ -48,7 +48,7 @@ class ExposedLockRepository( val lock = Lock(id, now) query { if (locks.select(locks.id eq id).limit(1) - .map { Lock(it[locks.id].value, Instant.ofEpochMilli(it[locks.expiresAt])) }.isEmpty() + .map { Lock(it[locks.id].value, Instant.ofEpochMilli(it[locks.expiresAt])) }.isEmpty() ) { locks.insert { it[locks.id] = id diff --git a/src/main/resources/META-INF/native-image/jni-config.json b/src/main/resources/META-INF/native-image/jni-config.json index 80fe1b33..c89c44cc 100644 --- a/src/main/resources/META-INF/native-image/jni-config.json +++ b/src/main/resources/META-INF/native-image/jni-config.json @@ -1,31 +1,31 @@ [ - { - "name": "sun.management.VMManagementImpl", - "fields": [ - { - "name": "compTimeMonitoringSupport" - }, - { - "name": "currentThreadCpuTimeSupport" - }, - { - "name": "objectMonitorUsageSupport" - }, - { - "name": "otherThreadCpuTimeSupport" - }, - { - "name": "remoteDiagnosticCommandsSupport" - }, - { - "name": "synchronizerUsageSupport" - }, - { - "name": "threadAllocatedMemorySupport" - }, - { - "name": "threadContentionMonitoringSupport" - } - ] - } -] \ No newline at end of file + { + "name": "sun.management.VMManagementImpl", + "fields": [ + { + "name": "compTimeMonitoringSupport" + }, + { + "name": "currentThreadCpuTimeSupport" + }, + { + "name": "objectMonitorUsageSupport" + }, + { + "name": "otherThreadCpuTimeSupport" + }, + { + "name": "remoteDiagnosticCommandsSupport" + }, + { + "name": "synchronizerUsageSupport" + }, + { + "name": "threadAllocatedMemorySupport" + }, + { + "name": "threadContentionMonitoringSupport" + } + ] + } +] diff --git a/src/main/resources/META-INF/native-image/predefined-classes-config.json b/src/main/resources/META-INF/native-image/predefined-classes-config.json index c5962d22..9587dc34 100644 --- a/src/main/resources/META-INF/native-image/predefined-classes-config.json +++ b/src/main/resources/META-INF/native-image/predefined-classes-config.json @@ -1,8 +1,7 @@ [ - { - "type": "agent-extracted", - "classes": [ - - ] - } -] \ No newline at end of file + { + "type": "agent-extracted", + "classes": [ + ] + } +] diff --git a/src/main/resources/META-INF/native-image/proxy-config.json b/src/main/resources/META-INF/native-image/proxy-config.json index 1610ea14..0d4f101c 100644 --- a/src/main/resources/META-INF/native-image/proxy-config.json +++ b/src/main/resources/META-INF/native-image/proxy-config.json @@ -1,3 +1,2 @@ [ - -] \ No newline at end of file +] diff --git a/src/main/resources/META-INF/native-image/reflect-config.json b/src/main/resources/META-INF/native-image/reflect-config.json index 4d6b60e2..33c8e95d 100644 --- a/src/main/resources/META-INF/native-image/reflect-config.json +++ b/src/main/resources/META-INF/native-image/reflect-config.json @@ -691,55 +691,46 @@ { "name": "getCreatedAt", "parameterTypes": [ - ] }, { "name": "getId", "parameterTypes": [ - ] }, { "name": "getOverview", "parameterTypes": [ - ] }, { "name": "getReplyId", "parameterTypes": [ - ] }, { "name": "getRepostId", "parameterTypes": [ - ] }, { "name": "getText", "parameterTypes": [ - ] }, { "name": "getUrl", "parameterTypes": [ - ] }, { "name": "getUserId", "parameterTypes": [ - ] }, { "name": "getVisibility", "parameterTypes": [ - ] } ] @@ -753,7 +744,6 @@ { "name": "", "parameterTypes": [ - ] }, { @@ -765,19 +755,16 @@ { "name": "getActor", "parameterTypes": [ - ] }, { "name": "getObject", "parameterTypes": [ - ] }, { "name": "setActor", "parameterTypes": [ - ] }, { @@ -794,7 +781,6 @@ { "name": "", "parameterTypes": [ - ] } ] @@ -805,7 +791,6 @@ { "name": "", "parameterTypes": [ - ] } ] @@ -819,7 +804,6 @@ { "name": "", "parameterTypes": [ - ] }, { @@ -831,7 +815,6 @@ { "name": "getObject", "parameterTypes": [ - ] } ] @@ -845,37 +828,31 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "", "parameterTypes": [ - ] }, { "name": "getActor", "parameterTypes": [ - ] }, { "name": "getObject", "parameterTypes": [ - ] }, { "name": "setActor", "parameterTypes": [ - ] }, { "name": "setObject", "parameterTypes": [ - ] } ] @@ -889,13 +866,11 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "", "parameterTypes": [ - ] } ] @@ -909,19 +884,16 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "getContext", "parameterTypes": [ - ] }, { "name": "setContext", "parameterTypes": [ - ] } ] @@ -935,49 +907,41 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "", "parameterTypes": [ - ] }, { "name": "getId", "parameterTypes": [ - ] }, { "name": "getOwner", "parameterTypes": [ - ] }, { "name": "getPublicKeyPem", "parameterTypes": [ - ] }, { "name": "setId", "parameterTypes": [ - ] }, { "name": "setOwner", "parameterTypes": [ - ] }, { "name": "setPublicKeyPem", "parameterTypes": [ - ] } ] @@ -991,67 +955,56 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "", "parameterTypes": [ - ] }, { "name": "getAttributedTo", "parameterTypes": [ - ] }, { "name": "getContent", "parameterTypes": [ - ] }, { "name": "getId", "parameterTypes": [ - ] }, { "name": "getPublished", "parameterTypes": [ - ] }, { "name": "getTo", "parameterTypes": [ - ] }, { "name": "setAttributedTo", "parameterTypes": [ - ] }, { "name": "setContent", "parameterTypes": [ - ] }, { "name": "setId", "parameterTypes": [ - ] }, { "name": "setPublished", "parameterTypes": [ - ] } ] @@ -1065,25 +1018,21 @@ { "name": "", "parameterTypes": [ - ] }, { "name": "", "parameterTypes": [ - ] }, { "name": "getName", "parameterTypes": [ - ] }, { "name": "setName", "parameterTypes": [ - ] } ] @@ -1094,7 +1043,6 @@ { "name": "add", "parameterTypes": [ - ] } ] @@ -1108,7 +1056,6 @@ { "name": "", "parameterTypes": [ - ] }, { @@ -1121,49 +1068,41 @@ { "name": "getInbox", "parameterTypes": [ - ] }, { "name": "getOutbox", "parameterTypes": [ - ] }, { "name": "getPreferredUsername", "parameterTypes": [ - ] }, { "name": "getPublicKey", "parameterTypes": [ - ] }, { "name": "getSummary", "parameterTypes": [ - ] }, { "name": "setInbox", "parameterTypes": [ - ] }, { "name": "setOutbox", "parameterTypes": [ - ] }, { "name": "setPreferredUsername", "parameterTypes": [ - ] }, { @@ -1175,7 +1114,6 @@ { "name": "setSummary", "parameterTypes": [ - ] } ] @@ -1186,7 +1124,6 @@ { "name": "", "parameterTypes": [ - ] } ] @@ -1199,7 +1136,6 @@ { "name": "", "parameterTypes": [ - ] } ] @@ -1228,7 +1164,6 @@ { "name": "parseActivity", "parameterTypes": [ - ] }, { @@ -1324,7 +1259,6 @@ { "name": "init", "parameterTypes": [ - ] }, { diff --git a/src/main/resources/META-INF/native-image/resource-config.json b/src/main/resources/META-INF/native-image/resource-config.json index 5c30b1ba..72f8cf9c 100644 --- a/src/main/resources/META-INF/native-image/resource-config.json +++ b/src/main/resources/META-INF/native-image/resource-config.json @@ -1,54 +1,53 @@ { - "resources": { - "includes": [ - { - "pattern": "\\QMETA-INF/services/ch.qos.logback.classic.spi.Configurator\\E" - }, - { - "pattern": "\\QMETA-INF/services/io.ktor.server.config.ConfigLoader\\E" - }, - { - "pattern": "\\QMETA-INF/services/java.sql.Driver\\E" - }, - { - "pattern": "\\QMETA-INF/services/kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoader\\E" - }, - { - "pattern": "\\QMETA-INF/services/kotlin.reflect.jvm.internal.impl.resolve.ExternalOverridabilityCondition\\E" - }, - { - "pattern": "\\QMETA-INF/services/org.jetbrains.exposed.sql.DatabaseConnectionAutoRegistration\\E" - }, - { - "pattern": "\\QMETA-INF/services/org.slf4j.spi.SLF4JServiceProvider\\E" - }, - { - "pattern": "\\Qapplication.conf\\E" - }, - { - "pattern": "\\Qlogback.xml\\E" - }, - { - "pattern": "\\Qorg/fusesource/jansi/internal/native/Windows/x86_64/jansi.dll\\E" - }, - { - "pattern": "\\Qorg/fusesource/jansi/jansi.properties\\E" - }, - { - "pattern": "\\Qorg/h2/util/data.zip\\E" - }, - { - "pattern": "\\Qstatic/assets/index-c7cbea7a.js\\E" - }, - { - "pattern": "\\Qstatic/index.html\\E" - }, - { - "pattern":"\\Qkotlin/kotlin.kotlin_builtins\\E" - } - ] - }, - "bundles": [ - + "resources": { + "includes": [ + { + "pattern": "\\QMETA-INF/services/ch.qos.logback.classic.spi.Configurator\\E" + }, + { + "pattern": "\\QMETA-INF/services/io.ktor.server.config.ConfigLoader\\E" + }, + { + "pattern": "\\QMETA-INF/services/java.sql.Driver\\E" + }, + { + "pattern": "\\QMETA-INF/services/kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoader\\E" + }, + { + "pattern": "\\QMETA-INF/services/kotlin.reflect.jvm.internal.impl.resolve.ExternalOverridabilityCondition\\E" + }, + { + "pattern": "\\QMETA-INF/services/org.jetbrains.exposed.sql.DatabaseConnectionAutoRegistration\\E" + }, + { + "pattern": "\\QMETA-INF/services/org.slf4j.spi.SLF4JServiceProvider\\E" + }, + { + "pattern": "\\Qapplication.conf\\E" + }, + { + "pattern": "\\Qlogback.xml\\E" + }, + { + "pattern": "\\Qorg/fusesource/jansi/internal/native/Windows/x86_64/jansi.dll\\E" + }, + { + "pattern": "\\Qorg/fusesource/jansi/jansi.properties\\E" + }, + { + "pattern": "\\Qorg/h2/util/data.zip\\E" + }, + { + "pattern": "\\Qstatic/assets/index-c7cbea7a.js\\E" + }, + { + "pattern": "\\Qstatic/index.html\\E" + }, + { + "pattern": "\\Qkotlin/kotlin.kotlin_builtins\\E" + } ] + }, + "bundles": [ + ] } diff --git a/src/main/resources/META-INF/native-image/serialization-config.json b/src/main/resources/META-INF/native-image/serialization-config.json index f63da041..5e42b093 100644 --- a/src/main/resources/META-INF/native-image/serialization-config.json +++ b/src/main/resources/META-INF/native-image/serialization-config.json @@ -1,11 +1,8 @@ { - "lambdaCapturingTypes": [ - - ], - "types": [ - - ], - "proxies": [ - - ] -} \ No newline at end of file + "lambdaCapturingTypes": [ + ], + "types": [ + ], + "proxies": [ + ] +} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index bae7027f..eb4be7a0 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -1,15 +1,15 @@ - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + diff --git a/src/test/kotlin/dev/usbharu/hideout/Empty.kt b/src/test/kotlin/dev/usbharu/hideout/Empty.kt index 0203d877..2feb27f1 100644 --- a/src/test/kotlin/dev/usbharu/hideout/Empty.kt +++ b/src/test/kotlin/dev/usbharu/hideout/Empty.kt @@ -2,6 +2,6 @@ package dev.usbharu.hideout import io.ktor.server.application.* -fun Application.empty(){ +fun Application.empty() { } diff --git a/src/test/kotlin/dev/usbharu/hideout/ap/ContextDeserializerTest.kt b/src/test/kotlin/dev/usbharu/hideout/ap/ContextDeserializerTest.kt index 116c028e..fd9f7d9c 100644 --- a/src/test/kotlin/dev/usbharu/hideout/ap/ContextDeserializerTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/ap/ContextDeserializerTest.kt @@ -44,7 +44,8 @@ class ContextDeserializerTest { } """ - val readValue = jacksonObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false).readValue(s) + val readValue = jacksonObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(s) println(readValue) println(readValue.actor) } diff --git a/src/test/kotlin/dev/usbharu/hideout/ap/ContextSerializerTest.kt b/src/test/kotlin/dev/usbharu/hideout/ap/ContextSerializerTest.kt index b93e7872..9a6013e2 100644 --- a/src/test/kotlin/dev/usbharu/hideout/ap/ContextSerializerTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/ap/ContextSerializerTest.kt @@ -5,7 +5,7 @@ import dev.usbharu.hideout.domain.model.ap.Accept import dev.usbharu.hideout.domain.model.ap.Follow import org.junit.jupiter.api.Test -class ContextSerializerTest{ +class ContextSerializerTest { @Test fun serialize() { diff --git a/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt b/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt index 63ff36cf..921dc740 100644 --- a/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt @@ -33,7 +33,7 @@ class ActivityPubKtTest { TODO() } - override suspend fun findByNameAndDomain(name: String, domain: String): User? { + override suspend fun findByNameAndDomain(name: String, domain: String): User { val keyPairGenerator = KeyPairGenerator.getInstance("RSA") keyPairGenerator.initialize(1024) val generateKeyPair = keyPairGenerator.generateKeyPair() diff --git a/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt b/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt index ad462b04..62ddd05a 100644 --- a/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt @@ -28,7 +28,7 @@ class KtorKeyMapTest { TODO() } - override suspend fun findByNameAndDomain(name: String, domain: String): User? { + override suspend fun findByNameAndDomain(name: String, domain: String): User { val keyPairGenerator = KeyPairGenerator.getInstance("RSA") keyPairGenerator.initialize(1024) val generateKeyPair = keyPairGenerator.generateKeyPair() diff --git a/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt b/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt index 36bbcf4d..b4f9d42f 100644 --- a/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt @@ -109,7 +109,8 @@ class UserRepositoryTest { } }) val user = userRepository.save( - User(0L, + User( + 0L, "test", "example.com", "testUser", @@ -123,7 +124,8 @@ class UserRepositoryTest { ) ) val follower = userRepository.save( - User(1L, + User( + 1L, "follower", "follower.example.com", "followerUser", diff --git a/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRoutingKtTest.kt b/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRoutingKtTest.kt index 94ee5880..8e93e159 100644 --- a/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRoutingKtTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/InboxRoutingKtTest.kt @@ -7,7 +7,6 @@ import dev.usbharu.hideout.plugins.configureStatusPages import dev.usbharu.hideout.service.activitypub.ActivityPubService import dev.usbharu.hideout.service.activitypub.ActivityPubUserService import dev.usbharu.hideout.service.impl.IUserService -import dev.usbharu.hideout.service.impl.UserService import dev.usbharu.hideout.service.signature.HttpSignatureVerifyService import io.ktor.client.request.* import io.ktor.http.* @@ -28,7 +27,7 @@ class InboxRoutingKtTest { } application { configureSerialization() - configureRouting(mock(), mock(), mock(), mock(),mock()) + configureRouting(mock(), mock(), mock(), mock(), mock()) } client.get("/inbox").let { Assertions.assertEquals(HttpStatusCode.MethodNotAllowed, it.status) @@ -40,10 +39,10 @@ class InboxRoutingKtTest { environment { config = ApplicationConfig("empty.conf") } - val httpSignatureVerifyService = mock{ + val httpSignatureVerifyService = mock { on { verify(any()) } doReturn true } - val activityPubService = mock{ + val activityPubService = mock { on { parseActivity(any()) } doThrow JsonParseException() } val userService = mock() @@ -51,7 +50,13 @@ class InboxRoutingKtTest { application { configureStatusPages() configureSerialization() - configureRouting(httpSignatureVerifyService, activityPubService, userService, activityPubUserService,mock()) + configureRouting( + httpSignatureVerifyService, + activityPubService, + userService, + activityPubUserService, + mock() + ) } client.post("/inbox").let { Assertions.assertEquals(HttpStatusCode.BadRequest, it.status) @@ -65,7 +70,7 @@ class InboxRoutingKtTest { } application { configureSerialization() - configureRouting(mock(), mock(), mock(), mock(),mock()) + configureRouting(mock(), mock(), mock(), mock(), mock()) } client.get("/users/test/inbox").let { Assertions.assertEquals(HttpStatusCode.MethodNotAllowed, it.status) @@ -77,10 +82,10 @@ class InboxRoutingKtTest { environment { config = ApplicationConfig("empty.conf") } - val httpSignatureVerifyService = mock{ + val httpSignatureVerifyService = mock { on { verify(any()) } doReturn true } - val activityPubService = mock{ + val activityPubService = mock { on { parseActivity(any()) } doThrow JsonParseException() } val userService = mock() @@ -88,7 +93,13 @@ class InboxRoutingKtTest { application { configureStatusPages() configureSerialization() - configureRouting(httpSignatureVerifyService, activityPubService, userService, activityPubUserService,mock()) + configureRouting( + httpSignatureVerifyService, + activityPubService, + userService, + activityPubUserService, + mock() + ) } client.post("/users/test/inbox").let { Assertions.assertEquals(HttpStatusCode.BadRequest, it.status) diff --git a/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt b/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt index 31967bbe..42606f8b 100644 --- a/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt @@ -17,7 +17,7 @@ import java.security.KeyPairGenerator import kotlin.test.assertEquals import kotlin.test.assertNull -class UserServiceTest{ +class UserServiceTest { @Test fun `createLocalUser ローカルユーザーを作成できる`() = runTest { Config.configData = ConfigData(domain = "example.com", url = "https://example.com") @@ -43,8 +43,8 @@ class UserServiceTest{ assertEquals("example.com", firstValue.domain) assertEquals("https://example.com/users/test/inbox", firstValue.inbox) assertEquals("https://example.com/users/test/outbox", firstValue.outbox) - assertEquals(generateKeyPair.public.toPem(),firstValue.publicKey) - assertEquals(generateKeyPair.private.toPem(),firstValue.privateKey) + assertEquals(generateKeyPair.public.toPem(), firstValue.publicKey) + assertEquals(generateKeyPair.private.toPem(), firstValue.privateKey) } } @@ -54,10 +54,10 @@ class UserServiceTest{ Config.configData = ConfigData(domain = "example.com", url = "https://example.com") - val userRepository = mock{ + val userRepository = mock { onBlocking { nextId() } doReturn 113345L } - val userService = UserService(userRepository,mock()) + val userService = UserService(userRepository, mock()) val user = RemoteUserCreateDto( "test", "example.com", @@ -81,7 +81,7 @@ class UserServiceTest{ assertEquals("example.com", firstValue.domain) assertEquals("https://example.com/inbox", firstValue.inbox) assertEquals("https://example.com/outbox", firstValue.outbox) - assertEquals("-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----",firstValue.publicKey) + assertEquals("-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----", firstValue.publicKey) assertNull(firstValue.privateKey) } } diff --git a/src/test/kotlin/utils/DBResetInterceptor.kt b/src/test/kotlin/utils/DBResetInterceptor.kt index 32fc88a9..c450556b 100644 --- a/src/test/kotlin/utils/DBResetInterceptor.kt +++ b/src/test/kotlin/utils/DBResetInterceptor.kt @@ -4,7 +4,7 @@ import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.transactions.TransactionManager import org.junit.jupiter.api.extension.* -class DBResetInterceptor : BeforeAllCallback,AfterAllCallback,BeforeEachCallback,AfterEachCallback { +class DBResetInterceptor : BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback { private lateinit var transactionAll: Transaction private lateinit var transactionEach: Transaction From 028c988475defb3e296d640833241a48badf0cf5 Mon Sep 17 00:00:00 2001 From: usbharu <64310155+usbharu@users.noreply.github.com> Date: Sun, 30 Apr 2023 01:38:59 +0900 Subject: [PATCH 3/4] =?UTF-8?q?style:=20=E3=83=86=E3=82=B9=E3=83=88?= =?UTF-8?q?=E3=81=AE=E3=82=B9=E3=82=BF=E3=82=A4=E3=83=AB=E3=82=92=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/kotlin/dev/usbharu/hideout/Empty.kt | 1 - .../hideout/plugins/ActivityPubKtTest.kt | 12 +++--- .../usbharu/hideout/plugins/KtorKeyMapTest.kt | 2 - .../hideout/repository/UserRepositoryTest.kt | 27 +++++++------ .../routing/activitypub/UsersAPTest.kt | 20 ++++++---- .../TwitterSnowflakeIdGenerateServiceTest.kt | 6 +-- .../ActivityPubFollowServiceImplTest.kt | 40 ++++++++++--------- .../ActivityPubNoteServiceImplTest.kt | 20 +++++++--- .../hideout/service/impl/UserServiceTest.kt | 2 - src/test/kotlin/utils/DatabaseTestBase.kt | 4 +- 10 files changed, 69 insertions(+), 65 deletions(-) diff --git a/src/test/kotlin/dev/usbharu/hideout/Empty.kt b/src/test/kotlin/dev/usbharu/hideout/Empty.kt index 2feb27f1..c5282364 100644 --- a/src/test/kotlin/dev/usbharu/hideout/Empty.kt +++ b/src/test/kotlin/dev/usbharu/hideout/Empty.kt @@ -3,5 +3,4 @@ package dev.usbharu.hideout import io.ktor.server.application.* fun Application.empty() { - } diff --git a/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt b/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt index 921dc740..e788e4bb 100644 --- a/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/plugins/ActivityPubKtTest.kt @@ -15,7 +15,6 @@ import java.time.Instant class ActivityPubKtTest { @Test fun HttpSignTest(): Unit = runBlocking { - val ktorKeyMap = KtorKeyMap(object : IUserRepository { override suspend fun save(user: User): User { TODO("Not yet implemented") @@ -96,12 +95,13 @@ class ActivityPubKtTest { override suspend fun nextId(): Long { TODO("Not yet implemented") } - }) - val httpClient = HttpClient(MockEngine { httpRequestData -> - respondOk() - }) { + val httpClient = HttpClient( + MockEngine { httpRequestData -> + respondOk() + } + ) { install(httpSignaturePlugin) { keyMap = ktorKeyMap } @@ -112,7 +112,5 @@ class ActivityPubKtTest { } httpClient.postAp("https://localhost", "test", JsonLd(emptyList())) - - } } diff --git a/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt b/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt index 62ddd05a..710b2620 100644 --- a/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/plugins/KtorKeyMapTest.kt @@ -46,7 +46,6 @@ class KtorKeyMapTest { generateKeyPair.private.toPem(), createdAt = Instant.now() ) - } override suspend fun findByDomain(domain: String): List { @@ -92,7 +91,6 @@ class KtorKeyMapTest { override suspend fun nextId(): Long { TODO("Not yet implemented") } - }) ktorKeyMap.getPrivateKey("test") diff --git a/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt b/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt index b4f9d42f..aab82880 100644 --- a/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/repository/UserRepositoryTest.kt @@ -18,7 +18,6 @@ import java.time.Clock import java.time.Instant import java.time.ZoneId - class UserRepositoryTest { lateinit var db: Database @@ -35,7 +34,6 @@ class UserRepositoryTest { @AfterEach fun tearDown() { transaction(db) { - SchemaUtils.drop(UsersFollowers) SchemaUtils.drop(Users) } @@ -43,11 +41,14 @@ class UserRepositoryTest { @Test fun `findFollowersById フォロワー一覧を取得`() = runTest { - val userRepository = UserRepository(db, object : IdGenerateService { - override suspend fun generateId(): Long { - TODO("Not yet implemented") + val userRepository = UserRepository( + db, + object : IdGenerateService { + override suspend fun generateId(): Long { + TODO("Not yet implemented") + } } - }) + ) val user = userRepository.save( User( id = 0L, @@ -98,16 +99,18 @@ class UserRepositoryTest { userRepository.findFollowersById(user.id).let { assertIterableEquals(listOf(follower, follower2), it) } - } @Test fun `createFollower フォロワー追加`() = runTest { - val userRepository = UserRepository(db, object : IdGenerateService { - override suspend fun generateId(): Long { - TODO("Not yet implemented") + val userRepository = UserRepository( + db, + object : IdGenerateService { + override suspend fun generateId(): Long { + TODO("Not yet implemented") + } } - }) + ) val user = userRepository.save( User( 0L, @@ -140,11 +143,9 @@ class UserRepositoryTest { ) userRepository.createFollower(user.id, follower.id) transaction { - val followerIds = UsersFollowers.select { UsersFollowers.userId eq user.id }.map { it[UsersFollowers.followerId] } assertIterableEquals(listOf(follower.id), followerIds) } - } } diff --git a/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/UsersAPTest.kt b/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/UsersAPTest.kt index 0e997f43..03bf53a4 100644 --- a/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/UsersAPTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/routing/activitypub/UsersAPTest.kt @@ -32,7 +32,6 @@ import java.time.Instant import kotlin.test.assertEquals import kotlin.test.assertTrue - class UsersAPTest { @Test() @@ -100,8 +99,8 @@ class UsersAPTest { } } + // @Disabled @Test() -// @Disabled fun `ユーザのURLにAcceptヘッダーをActivityとJson-LDにしてアクセスしたときPersonが返ってくる`() = testApplication { environment { config = ApplicationConfig("empty.conf") @@ -167,16 +166,21 @@ class UsersAPTest { } } + // @Disabled @Test -// @Disabled fun contentType_Test() { - assertTrue(ContentType.Application.Activity.match("application/activity+json")) val listOf = listOf(ContentType.Application.JsonLd, ContentType.Application.Activity) - assertTrue(listOf.find { contentType -> - contentType.match("application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") - }.let { it != null }) - assertTrue(ContentType.Application.JsonLd.match("application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"")) + assertTrue( + listOf.find { contentType -> + contentType.match("application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"") + }.let { it != null } + ) + assertTrue( + ContentType.Application.JsonLd.match( + "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"" + ) + ) } @Test diff --git a/src/test/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateServiceTest.kt b/src/test/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateServiceTest.kt index d1d5ff60..e1aab2f3 100644 --- a/src/test/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateServiceTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/service/TwitterSnowflakeIdGenerateServiceTest.kt @@ -1,6 +1,6 @@ package dev.usbharu.hideout.service -//import kotlinx.coroutines.NonCancellable.message +// import kotlinx.coroutines.NonCancellable.message import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @@ -16,17 +16,13 @@ class TwitterSnowflakeIdGenerateServiceTest { val mutex = Mutex() val mutableListOf = mutableListOf() coroutineScope { - repeat(500000) { - launch(Dispatchers.IO) { val id = TwitterSnowflakeIdGenerateService.generateId() mutex.withLock { mutableListOf.add(id) - } } - } } diff --git a/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImplTest.kt b/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImplTest.kt index a8eae660..93dfec61 100644 --- a/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImplTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubFollowServiceImplTest.kt @@ -122,28 +122,30 @@ class ActivityPubFollowServiceImplTest { mock(), activityPubUserService, userService, - HttpClient(MockEngine { httpRequestData -> - assertEquals(person.inbox, httpRequestData.url.toString()) - val accept = Accept( - type = emptyList(), - name = "Follow", - `object` = Follow( + HttpClient( + MockEngine { httpRequestData -> + assertEquals(person.inbox, httpRequestData.url.toString()) + val accept = Accept( type = emptyList(), name = "Follow", - `object` = "https://example.com", - actor = "https://follower.example.com" - ), - actor = "https://example.com" - ) - accept.context += "https://www.w3.org/ns/activitystreams" - assertEquals( - accept, - Config.configData.objectMapper.readValue( - httpRequestData.body.toByteArray().decodeToString() + `object` = Follow( + type = emptyList(), + name = "Follow", + `object` = "https://example.com", + actor = "https://follower.example.com" + ), + actor = "https://example.com" ) - ) - respondOk() - }) + accept.context += "https://www.w3.org/ns/activitystreams" + assertEquals( + accept, + Config.configData.objectMapper.readValue( + httpRequestData.body.toByteArray().decodeToString() + ) + ) + respondOk() + } + ) ) activityPubFollowService.receiveFollowJob( JobProps( diff --git a/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImplTest.kt b/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImplTest.kt index bb15ffde..af5274de 100644 --- a/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImplTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/service/activitypub/ActivityPubNoteServiceImplTest.kt @@ -73,7 +73,13 @@ class ActivityPubNoteServiceImplTest { val jobQueueParentService = mock() val activityPubNoteService = ActivityPubNoteServiceImpl(mock(), jobQueueParentService, userService) val postEntity = PostEntity( - 1L, 1L, null, "test text", 1L, 1, "https://example.com" + 1L, + 1L, + null, + "test text", + 1L, + 1, + "https://example.com" ) activityPubNoteService.createNote(postEntity) verify(jobQueueParentService, times(2)).schedule(eq(DeliverPostJob), any()) @@ -82,17 +88,19 @@ class ActivityPubNoteServiceImplTest { @Test fun `createPostJob 新しい投稿のJob`() = runTest { Config.configData = ConfigData(objectMapper = JsonObjectMapper.objectMapper) - val httpClient = HttpClient(MockEngine { httpRequestData -> - assertEquals("https://follower.example.com/inbox", httpRequestData.url.toString()) - respondOk() - }) + val httpClient = HttpClient( + MockEngine { httpRequestData -> + assertEquals("https://follower.example.com/inbox", httpRequestData.url.toString()) + respondOk() + } + ) val activityPubNoteService = ActivityPubNoteServiceImpl(httpClient, mock(), mock()) activityPubNoteService.createNoteJob( JobProps( data = mapOf( DeliverPostJob.actor.name to "https://follower.example.com", DeliverPostJob.post.name to "{\"id\":1,\"userId\":1,\"inReplyToId\":null,\"text\":\"test text\"," + - "\"createdAt\":1,\"updatedAt\":1,\"url\":\"https://example.com\"}", + "\"createdAt\":1,\"updatedAt\":1,\"url\":\"https://example.com\"}", DeliverPostJob.inbox.name to "https://follower.example.com/inbox" ), json = Json diff --git a/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt b/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt index 42606f8b..deab1ce6 100644 --- a/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt +++ b/src/test/kotlin/dev/usbharu/hideout/service/impl/UserServiceTest.kt @@ -50,10 +50,8 @@ class UserServiceTest { @Test fun `createRemoteUser リモートユーザーを作成できる`() = runTest { - Config.configData = ConfigData(domain = "example.com", url = "https://example.com") - val userRepository = mock { onBlocking { nextId() } doReturn 113345L } diff --git a/src/test/kotlin/utils/DatabaseTestBase.kt b/src/test/kotlin/utils/DatabaseTestBase.kt index 10653631..d81f8b80 100644 --- a/src/test/kotlin/utils/DatabaseTestBase.kt +++ b/src/test/kotlin/utils/DatabaseTestBase.kt @@ -4,7 +4,6 @@ import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.DatabaseConfig import org.junit.jupiter.api.extension.ExtendWith - @ExtendWith(DBResetInterceptor::class) abstract class DatabaseTestBase { companion object { @@ -12,7 +11,8 @@ abstract class DatabaseTestBase { Database.connect( "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver", - databaseConfig = DatabaseConfig { useNestedTransactions = true }) + databaseConfig = DatabaseConfig { useNestedTransactions = true } + ) } } } From d556313866ff78fab7cf684016c749e62adbfc3d Mon Sep 17 00:00:00 2001 From: usbharu <64310155+usbharu@users.noreply.github.com> Date: Sun, 30 Apr 2023 01:55:07 +0900 Subject: [PATCH 4/4] =?UTF-8?q?chore:=20Lint=E3=82=A8=E3=83=A9=E3=83=BC?= =?UTF-8?q?=E3=81=AE=E8=A8=B1=E5=AE=B9=E7=AF=84=E5=9B=B2=E3=82=9220?= =?UTF-8?q?=E3=81=AB=E8=A8=AD=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- detekt.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/detekt.yml b/detekt.yml index f8c0fb04..73a9d00a 100644 --- a/detekt.yml +++ b/detekt.yml @@ -1,3 +1,6 @@ +build: + maxIssues: 20 + style: ClassOrdering: active: true @@ -68,6 +71,10 @@ complexity: ignoreOverridden: true ignorePrivate: true + LongMethod: + active: true + excludes: + - "**/test/**" exceptions: ExceptionRaisedInUnexpectedLocation: @@ -104,6 +111,8 @@ formatting: naming: FunctionMaxLength: active: true + excludes: + - "**/test/**" FunctionMinLength: active: true