Merge pull request #11 from usbharu/feature/detekt

Feature/detekt
This commit is contained in:
usbharu 2023-04-30 02:02:15 +09:00 committed by GitHub
commit daf6acf4f8
76 changed files with 689 additions and 616 deletions

View File

@ -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,11 @@ graalvmNative {
}
}
}
detekt {
parallel = true
config = files("detekt.yml")
buildUponDefaultConfig = true
basePath = rootDir.absolutePath
autoCorrect = true
}

147
detekt.yml Normal file
View File

@ -0,0 +1,147 @@
build:
maxIssues: 20
style:
ClassOrdering:
active: true
MandatoryBracesIfStatements:
active: true
MandatoryBracesLoops:
active: true
MultilineLambdaItParameter:
active: false
UseEmptyCounterpart:
active: true
ExpressionBodySyntax:
active: true
WildcardImport:
active: false
ReturnCount:
active: false
MagicNumber:
ignorePropertyDeclaration: true
ForbiddenComment:
active: false
complexity:
CognitiveComplexMethod:
active: true
ComplexCondition:
active: true
ComplexInterface:
active: true
threshold: 30
LabeledExpression:
active: false
NamedArguments:
active: true
ignoreArgumentsMatchingNames: true
threshold: 5
NestedBlockDepth:
active: true
NestedScopeFunctions:
active: true
ReplaceSafeCallChainWithRun:
active: true
StringLiteralDuplication:
active: false
LongParameterList:
constructorThreshold: 10
TooManyFunctions:
ignoreDeprecated: true
ignoreOverridden: true
ignorePrivate: true
LongMethod:
active: true
excludes:
- "**/test/**"
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
NoWildcardImports:
active: false
naming:
FunctionMaxLength:
active: true
excludes:
- "**/test/**"
FunctionMinLength:
active: true
LambdaParameterNaming:
active: true
ConstructorParameterNaming:
excludes:
- "**/domain/model/ap/*"
ignoreOverridden: true
VariableNaming:
excludes:
- "**/domain/model/ap/*"
performance:
UnnecessaryPartOfBinaryExpression:
active: true
UnnecessaryTemporaryInstantiation:
active: true
potential-bugs:
CastToNullableType:
active: true
DontDowncastCollectionTypes:
active: true
ElseCaseInsteadOfExhaustiveWhen:
active: true

View File

@ -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<IUserRepository> { UserRepository(get(),get()) }
single<IUserRepository> { UserRepository(get(), get()) }
single<IUserAuthService> { UserAuthService(get()) }
single<HttpSignatureVerifyService> { HttpSignatureVerifyServiceImpl(get()) }
single<JobQueueParentService> {
val kJobJobQueueService = KJobJobQueueParentService(get())
kJobJobQueueService.init(listOf())
kJobJobQueueService.init(emptyList())
kJobJobQueueService
}
single<HttpClient> {
@ -83,15 +83,14 @@ fun Application.parent() {
}
single<ActivityPubFollowService> { ActivityPubFollowServiceImpl(get(), get(), get(), get()) }
single<ActivityPubService> { ActivityPubServiceImpl(get(), get()) }
single<IUserService> { UserService(get(),get()) }
single<IUserService> { UserService(get(), get()) }
single<ActivityPubUserService> { ActivityPubUserServiceImpl(get(), get()) }
single<ActivityPubNoteService> { ActivityPubNoteServiceImpl(get(), get(), get()) }
single<IPostService> { PostService(get(), get()) }
single<IPostRepository> { PostRepositoryImpl(get(), get()) }
single<IdGenerateService> {TwitterSnowflakeIdGenerateService}
single<IdGenerateService> { 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)
}

View File

@ -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()}"
}

View File

@ -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()}"
}

View File

@ -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`
}
}

View File

@ -28,6 +28,4 @@ open class Image : Object {
result = 31 * result + (url?.hashCode() ?: 0)
return result
}
}

View File

@ -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<String>() {
@ -60,10 +54,7 @@ class ContextDeserializer : JsonDeserializer<String>() {
class ContextSerializer : JsonSerializer<List<String>>() {
override fun isEmpty(value: List<String>?): Boolean {
return value.isNullOrEmpty()
}
override fun isEmpty(value: List<String>?): Boolean = value.isNullOrEmpty()
override fun serialize(value: List<String>?, gen: JsonGenerator?, serializers: SerializerProvider?) {
if (value.isNullOrEmpty()) {
@ -80,5 +71,4 @@ class ContextSerializer : JsonSerializer<List<String>>() {
gen?.writeEndArray()
}
}
}

View File

@ -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
}
}

View File

@ -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()}"
}

View File

@ -10,27 +10,16 @@ open class Object : JsonLd {
private var type: List<String> = emptyList()
var name: String? = null
var actor: String? = null
var id:String? = null
var id: String? = null
protected constructor()
constructor(type: List<String>, name: String? = null,actor:String? = null,id:String? = null) : super() {
constructor(type: List<String>, 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<String>, type: String): List<String> {
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<String>, type: String): List<String> {
val toMutableList = list.toMutableList()
toMutableList.add(type)
return toMutableList.distinct()
}
}
}
class TypeSerializer : JsonSerializer<List<String>>() {
@ -69,5 +63,4 @@ class TypeSerializer : JsonSerializer<List<String>>() {
gen?.writeEndArray()
}
}
}

View File

@ -10,6 +10,8 @@ open class Person : Object {
var publicKey: Key? = null
protected constructor() : super()
@Suppress("LongParameterList")
constructor(
type: List<String> = 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
}
}

View File

@ -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,
)

View File

@ -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
)

View File

@ -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<String> {
return name?.let { request.headers.getAll(it) }?.toMutableList() ?: mutableListOf()
}
override fun headerValues(name: String?): MutableList<String> =
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")
}

View File

@ -31,6 +31,5 @@ fun Application.configureRouting(
route("/api/v1") {
statuses(postService)
}
}
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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<User>
suspend fun findByDomain(domain: String): List<User>
suspend fun findByNameAndDomains(names: List<Pair<String,String>>): List<User>
suspend fun findByNameAndDomains(names: List<Pair<String, String>>): List<User>
suspend fun findByUrl(url:String): User?
suspend fun findByUrl(url: String): User?
suspend fun findByUrls(urls: List<String>): List<User>
@ -34,5 +35,5 @@ interface IUserRepository {
suspend fun deleteFollower(id: Long, follower: Long)
suspend fun findFollowersById(id: Long): List<User>
suspend fun nextId():Long
suspend fun nextId(): Long
}

View File

@ -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
)
}
}

View File

@ -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]))
)
}

View File

@ -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<UserIdPrincipal>()

View File

@ -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)
}
}
}
}

View File

@ -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)
}
}
}

View File

@ -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
}
}
}

View File

@ -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.*

View File

@ -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.")

View File

@ -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)
}

View File

@ -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
}

View File

@ -1,5 +1,5 @@
package dev.usbharu.hideout.service
interface IdGenerateService {
suspend fun generateId():Long
suspend fun generateId(): Long
}

View File

@ -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()
}

View File

@ -1,4 +1,5 @@
package dev.usbharu.hideout.service
// 2010-11-04T01:42:54.657
@Suppress("MagicNumber")
object TwitterSnowflakeIdGenerateService : SnowflakeIdGenerateService(1288834974657L)

View File

@ -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<ReceiveFollowJob>)
}

View File

@ -33,7 +33,7 @@ class ActivityPubFollowServiceImpl(
override suspend fun receiveFollowJob(props: JobProps<ReceiveFollowJob>) {
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<Follow>(props[ReceiveFollowJob.follow])
httpClient.postAp(
urlString = person.inbox ?: throw IllegalArgumentException("inbox is not found"),

View File

@ -6,6 +6,6 @@ import kjob.core.job.JobProps
interface ActivityPubNoteService {
suspend fun createNote(post:PostEntity)
suspend fun createNoteJob(props:JobProps<DeliverPostJob>)
suspend fun createNote(post: PostEntity)
suspend fun createNoteJob(props: JobProps<DeliverPostJob>)
}

View File

@ -35,7 +35,6 @@ class ActivityPubNoteServiceImpl(
}
}
override suspend fun createNoteJob(props: JobProps<DeliverPostJob>) {
val actor = props[DeliverPostJob.actor]
val postEntity = Config.configData.objectMapper.readValue<PostEntity>(props[DeliverPostJob.post])

View File

@ -9,7 +9,7 @@ interface ActivityPubService {
suspend fun processActivity(json: String, type: ActivityType): ActivityPubResponse?
suspend fun <T : HideoutJob> processActivity(job: JobContextWithProps<T>,hideoutJob: HideoutJob)
suspend fun <T : HideoutJob> processActivity(job: JobContextWithProps<T>, hideoutJob: HideoutJob)
}
enum class ActivityType {

View File

@ -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<DeliverPostJob>)
}
}
}

View File

@ -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
}

View File

@ -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
}
}
}

View File

@ -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<User>

View File

@ -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)
}

View File

@ -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"
}

View File

@ -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<User> {
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<Long>): List<User> {
return userRepository.findByIds(ids)
}
override suspend fun findByIds(ids: List<Long>): List<User> = userRepository.findByIds(ids)
override suspend fun findByName(name: String): List<User> {
return userRepository.findByName(name)
}
override suspend fun findByName(name: String): List<User> = 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<Pair<String, String>>): List<User> {
return userRepository.findByNameAndDomains(names)
}
override suspend fun findByNameAndDomains(names: List<Pair<String, String>>): List<User> =
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<String>): List<User> {
return userRepository.findByUrls(urls)
}
override suspend fun findByUrls(urls: List<String>): List<User> = 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<User> {
return userRepository.findFollowersById(id)
}
override suspend fun addFollowers(id: Long, follower: Long) {
return userRepository.createFollower(id, follower)
}
override suspend fun findFollowersById(id: Long): List<User> = userRepository.findFollowersById(id)
override suspend fun addFollowers(id: Long, follower: Long) = userRepository.createFollower(id, follower)
}

View File

@ -5,6 +5,6 @@ import kjob.core.dsl.ScheduleContext
interface JobQueueParentService {
fun init(jobDefines:List<Job>)
fun init(jobDefines: List<Job>)
suspend fun <J : Job> schedule(job: J, block: ScheduleContext<J>.(J) -> Unit = {})
}

View File

@ -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<Pair<Job, JobRegisterContext<Job, JobContextWithProps<Job>>.(Job) -> KJobFunctions<Job, JobContextWithProps<Job>>>>)
fun init(defines: List<Pair<Job, JRC<Job, JCWP<Job>>.(Job) -> KJobFunctions<Job, JCWP<Job>>>>)
}

View File

@ -17,9 +17,7 @@ class KJobJobQueueParentService(private val database: Database) : JobQueueParent
isWorker = false
}.start()
override fun init(jobDefines: List<Job>) {
}
override fun init(jobDefines: List<Job>) = Unit
override suspend fun <J : Job> schedule(job: J, block: ScheduleContext<J>.(J) -> Unit) {
logger.debug("schedule job={}", job.name)

View File

@ -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<Pair<Job,JobRegisterContext<Job, JobContextWithProps<Job>>.(Job) -> KJobFunctions<Job, JobContextWithProps<Job>>>>) {
override fun init(
defines: List<Pair<Job, JRC<Job, JCWP<Job>>.(Job) -> KJobFunctions<Job, JCWP<Job>>>>
) {
defines.forEach { job ->
kjob.register(job.first, job.second)
}
}
}

View File

@ -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
}

View File

@ -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<String> {
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<String> {
// return name?.let { headers.getAll(it) }?.toMutableList() ?: mutableListOf()
// }
//
// override fun addHeader(name: String?, value: String?) {
// TODO()
// }
//
// })
}
}

View File

@ -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
}

View File

@ -56,7 +56,6 @@ class ExposedJobRepository(
suspend fun <T> 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<Int>).map(::JsonPrimitive)
is String -> "s" to (value as List<String>).map(::JsonPrimitive)
is Boolean -> "b" to (value as List<Boolean>).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

View File

@ -9,24 +9,6 @@ import java.time.Clock
class ExposedKJob(config: Configuration) : BaseKJob<ExposedKJob.Configuration>(config) {
companion object : KJobFactory<ExposedKJob, Configuration> {
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<ExposedKJob.Configuration>(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<ExposedKJob.Configuration>(c
super.shutdown()
lockRepository.clearExpired()
}
companion object : KJobFactory<ExposedKJob, Configuration> {
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
}
}

View File

@ -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

View File

@ -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"
}
]
}
]
{
"name": "sun.management.VMManagementImpl",
"fields": [
{
"name": "compTimeMonitoringSupport"
},
{
"name": "currentThreadCpuTimeSupport"
},
{
"name": "objectMonitorUsageSupport"
},
{
"name": "otherThreadCpuTimeSupport"
},
{
"name": "remoteDiagnosticCommandsSupport"
},
{
"name": "synchronizerUsageSupport"
},
{
"name": "threadAllocatedMemorySupport"
},
{
"name": "threadContentionMonitoringSupport"
}
]
}
]

View File

@ -1,8 +1,7 @@
[
{
"type": "agent-extracted",
"classes": [
]
}
]
{
"type": "agent-extracted",
"classes": [
]
}
]

View File

@ -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": "<init>",
"parameterTypes": [
]
},
{
@ -765,19 +755,16 @@
{
"name": "getActor",
"parameterTypes": [
]
},
{
"name": "getObject",
"parameterTypes": [
]
},
{
"name": "setActor",
"parameterTypes": [
]
},
{
@ -794,7 +781,6 @@
{
"name": "<init>",
"parameterTypes": [
]
}
]
@ -805,7 +791,6 @@
{
"name": "<init>",
"parameterTypes": [
]
}
]
@ -819,7 +804,6 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
@ -831,7 +815,6 @@
{
"name": "getObject",
"parameterTypes": [
]
}
]
@ -845,37 +828,31 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "getActor",
"parameterTypes": [
]
},
{
"name": "getObject",
"parameterTypes": [
]
},
{
"name": "setActor",
"parameterTypes": [
]
},
{
"name": "setObject",
"parameterTypes": [
]
}
]
@ -889,13 +866,11 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "<init>",
"parameterTypes": [
]
}
]
@ -909,19 +884,16 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "getContext",
"parameterTypes": [
]
},
{
"name": "setContext",
"parameterTypes": [
]
}
]
@ -935,49 +907,41 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "getId",
"parameterTypes": [
]
},
{
"name": "getOwner",
"parameterTypes": [
]
},
{
"name": "getPublicKeyPem",
"parameterTypes": [
]
},
{
"name": "setId",
"parameterTypes": [
]
},
{
"name": "setOwner",
"parameterTypes": [
]
},
{
"name": "setPublicKeyPem",
"parameterTypes": [
]
}
]
@ -991,67 +955,56 @@
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "<init>",
"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": "<init>",
"parameterTypes": [
]
},
{
"name": "<init>",
"parameterTypes": [
]
},
{
"name": "getName",
"parameterTypes": [
]
},
{
"name": "setName",
"parameterTypes": [
]
}
]
@ -1094,7 +1043,6 @@
{
"name": "add",
"parameterTypes": [
]
}
]
@ -1108,7 +1056,6 @@
{
"name": "<init>",
"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": "<init>",
"parameterTypes": [
]
}
]
@ -1199,7 +1136,6 @@
{
"name": "<init>",
"parameterTypes": [
]
}
]
@ -1228,7 +1164,6 @@
{
"name": "parseActivity",
"parameterTypes": [
]
},
{
@ -1324,7 +1259,6 @@
{
"name": "init",
"parameterTypes": [
]
},
{

View File

@ -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": [
]
}

View File

@ -1,11 +1,8 @@
{
"lambdaCapturingTypes": [
],
"types": [
],
"proxies": [
]
}
"lambdaCapturingTypes": [
],
"types": [
],
"proxies": [
]
}

View File

@ -1,15 +1,15 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
<logger name="kjob.core.internal.scheduler.JobServiceImpl" level="INFO"/>
<logger name="Exposed" level="INFO"/>
<logger name="io.ktor.server.plugins.contentnegotiation" level="INFO"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
<logger name="kjob.core.internal.scheduler.JobServiceImpl" level="INFO"/>
<logger name="Exposed" level="INFO"/>
<logger name="io.ktor.server.plugins.contentnegotiation" level="INFO"/>
</configuration>

View File

@ -2,6 +2,5 @@ package dev.usbharu.hideout
import io.ktor.server.application.*
fun Application.empty(){
fun Application.empty() {
}

View File

@ -44,7 +44,8 @@ class ContextDeserializerTest {
}
"""
val readValue = jacksonObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false).readValue<Follow>(s)
val readValue = jacksonObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue<Follow>(s)
println(readValue)
println(readValue.actor)
}

View File

@ -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() {

View File

@ -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")
@ -33,7 +32,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()
@ -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()))
}
}

View File

@ -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()
@ -46,7 +46,6 @@ class KtorKeyMapTest {
generateKeyPair.private.toPem(),
createdAt = Instant.now()
)
}
override suspend fun findByDomain(domain: String): List<User> {
@ -92,7 +91,6 @@ class KtorKeyMapTest {
override suspend fun nextId(): Long {
TODO("Not yet implemented")
}
})
ktorKeyMap.getPrivateKey("test")

View File

@ -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,18 +99,21 @@ 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,
User(
0L,
"test",
"example.com",
"testUser",
@ -123,7 +127,8 @@ class UserRepositoryTest {
)
)
val follower = userRepository.save(
User(1L,
User(
1L,
"follower",
"follower.example.com",
"followerUser",
@ -138,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)
}
}
}

View File

@ -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<HttpSignatureVerifyService>{
val httpSignatureVerifyService = mock<HttpSignatureVerifyService> {
on { verify(any()) } doReturn true
}
val activityPubService = mock<ActivityPubService>{
val activityPubService = mock<ActivityPubService> {
on { parseActivity(any()) } doThrow JsonParseException()
}
val userService = mock<IUserService>()
@ -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<HttpSignatureVerifyService>{
val httpSignatureVerifyService = mock<HttpSignatureVerifyService> {
on { verify(any()) } doReturn true
}
val activityPubService = mock<ActivityPubService>{
val activityPubService = mock<ActivityPubService> {
on { parseActivity(any()) } doThrow JsonParseException()
}
val userService = mock<IUserService>()
@ -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)

View File

@ -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

View File

@ -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<Long>()
coroutineScope {
repeat(500000) {
launch(Dispatchers.IO) {
val id = TwitterSnowflakeIdGenerateService.generateId()
mutex.withLock {
mutableListOf.add(id)
}
}
}
}

View File

@ -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<Accept>(
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<Accept>(
httpRequestData.body.toByteArray().decodeToString()
)
)
respondOk()
}
)
)
activityPubFollowService.receiveFollowJob(
JobProps(

View File

@ -73,7 +73,13 @@ class ActivityPubNoteServiceImplTest {
val jobQueueParentService = mock<JobQueueParentService>()
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<String, Any>(
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

View File

@ -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,21 +43,19 @@ 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)
}
}
@Test
fun `createRemoteUser リモートユーザーを作成できる`() = runTest {
Config.configData = ConfigData(domain = "example.com", url = "https://example.com")
val userRepository = mock<IUserRepository>{
val userRepository = mock<IUserRepository> {
onBlocking { nextId() } doReturn 113345L
}
val userService = UserService(userRepository,mock())
val userService = UserService(userRepository, mock())
val user = RemoteUserCreateDto(
"test",
"example.com",
@ -81,7 +79,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)
}
}

View File

@ -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

View File

@ -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 }
)
}
}
}