Merge pull request #54 from usbharu/feature/fix-jobqueue

fix: ジョブキュー等を修正
This commit is contained in:
usbharu 2023-09-25 17:44:11 +09:00 committed by GitHub
commit 74cea24a77
50 changed files with 375 additions and 246 deletions

View File

@ -2,6 +2,7 @@ build:
maxIssues: 20
weights:
Indentation: 0
MagicNumber: 0
style:
ClassOrdering:

View File

@ -0,0 +1,51 @@
package dev.usbharu.hideout
import dev.usbharu.hideout.domain.model.job.HideoutJob
import dev.usbharu.hideout.service.ap.APService
import dev.usbharu.hideout.service.job.JobQueueParentService
import dev.usbharu.hideout.service.job.JobQueueWorkerService
import org.slf4j.LoggerFactory
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
@Component
class JobQueueRunner(private val jobQueueParentService: JobQueueParentService, private val jobs: List<HideoutJob>) :
ApplicationRunner {
override fun run(args: ApplicationArguments?) {
LOGGER.info("Init job queue. ${jobs.size}")
jobQueueParentService.init(jobs)
}
companion object {
val LOGGER = LoggerFactory.getLogger(JobQueueRunner::class.java)
}
}
@Component
class JobQueueWorkerRunner(
private val jobQueueWorkerService: JobQueueWorkerService,
private val jobs: List<HideoutJob>,
private val apService: APService
) : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
LOGGER.info("Init job queue worker.")
jobQueueWorkerService.init(
jobs.map {
it to {
execute {
LOGGER.debug("excute job ${it.name}")
apService.processActivity(
job = this,
hideoutJob = it
)
}
}
}
)
}
companion object {
val LOGGER = LoggerFactory.getLogger(JobQueueWorkerRunner::class.java)
}
}

View File

@ -8,6 +8,7 @@ import org.springframework.boot.runApplication
@ConfigurationPropertiesScan
class SpringApplication
@Suppress("SpreadOperator")
fun main(args: Array<String>) {
runApplication<SpringApplication>(*args)
}

View File

@ -0,0 +1,23 @@
package dev.usbharu.hideout.config
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class ActivityPubConfig {
@Bean
@Qualifier("activitypub")
fun objectMapper(): ObjectMapper {
val objectMapper = jacksonObjectMapper()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
return objectMapper
}
}

View File

@ -1,12 +1,40 @@
package dev.usbharu.hideout.config
import dev.usbharu.hideout.plugins.KtorKeyMap
import dev.usbharu.hideout.plugins.httpSignaturePlugin
import dev.usbharu.hideout.query.UserQueryService
import dev.usbharu.hideout.service.core.Transaction
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.logging.*
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import tech.barbero.http.message.signing.KeyMap
@Configuration
class HttpClientConfig {
@Bean
fun httpClient(): HttpClient = HttpClient(CIO)
fun httpClient(keyMap: KeyMap): HttpClient = HttpClient(CIO).config {
install(httpSignaturePlugin) {
this.keyMap = keyMap
}
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.ALL
}
expectSuccess = true
}
@Bean
fun keyMap(
userQueryService: UserQueryService,
transaction: Transaction,
applicationConfig: ApplicationConfig
): KtorKeyMap {
return KtorKeyMap(
userQueryService,
transaction,
applicationConfig
)
}
}

View File

@ -33,7 +33,7 @@ import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.util.*
@EnableWebSecurity(debug = true)
@EnableWebSecurity(debug = false)
@Configuration
class SecurityConfig {
@ -55,7 +55,6 @@ class SecurityConfig {
return http.build()
}
@Bean
@Order(2)
fun defaultSecurityFilterChain(http: HttpSecurity, introspector: HandlerMappingIntrospector): SecurityFilterChain {
@ -66,6 +65,7 @@ class SecurityConfig {
it.requestMatchers(PathRequest.toH2Console()).permitAll()
it.requestMatchers(
builder.pattern("/inbox"),
builder.pattern("/users/*/inbox"),
builder.pattern("/api/v1/apps"),
builder.pattern("/api/v1/instance/**"),
builder.pattern("/.well-known/**"),
@ -85,6 +85,8 @@ class SecurityConfig {
.formLogin(Customizer.withDefaults())
.csrf {
it.ignoringRequestMatchers(builder.pattern("/api/**"))
it.ignoringRequestMatchers(builder.pattern("/users/*/inbox"))
it.ignoringRequestMatchers(builder.pattern("/inbox"))
it.ignoringRequestMatchers(PathRequest.toH2Console())
}
.headers {
@ -96,9 +98,7 @@ class SecurityConfig {
}
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
@Bean
fun genJwkSource(): JWKSource<SecurityContext> {
@ -128,9 +128,8 @@ class SecurityConfig {
}
@Bean
fun jwtDecoder(jwkSource: JWKSource<SecurityContext>): JwtDecoder {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource)
}
fun jwtDecoder(jwkSource: JWKSource<SecurityContext>): JwtDecoder =
OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource)
@Bean
fun authorizationServerSettings(): AuthorizationServerSettings {

View File

@ -5,6 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.net.URL
@Configuration
class SpringConfig {
@ -28,7 +29,7 @@ class SpringConfig {
@ConfigurationProperties("hideout")
data class ApplicationConfig(
val url: String
val url: URL
)
@ConfigurationProperties("hideout.database")

View File

@ -12,7 +12,6 @@ import javax.sql.DataSource
@EnableTransactionManagement
class SpringTransactionConfig(val datasource: DataSource) : TransactionManagementConfigurer {
@Bean
override fun annotationDrivenTransactionManager(): PlatformTransactionManager {
return SpringTransactionManager(datasource)
}
override fun annotationDrivenTransactionManager(): PlatformTransactionManager =
SpringTransactionManager(datasource)
}

View File

@ -12,10 +12,11 @@ interface InboxController {
@RequestMapping(
"/inbox",
"/users/{username}/inbox",
produces = ["application/activity+json", "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""],
produces = [
"application/activity+json",
"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""
],
method = [RequestMethod.GET, RequestMethod.POST]
)
suspend fun inbox(@RequestBody string: String): ResponseEntity<Unit> {
return ResponseEntity(HttpStatus.ACCEPTED)
}
fun inbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.ACCEPTED)
}

View File

@ -1,6 +1,7 @@
package dev.usbharu.hideout.controller
import dev.usbharu.hideout.service.ap.APService
import kotlinx.coroutines.runBlocking
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestBody
@ -8,9 +9,9 @@ import org.springframework.web.bind.annotation.RestController
@RestController
class InboxControllerImpl(private val apService: APService) : InboxController {
override suspend fun inbox(@RequestBody string: String): ResponseEntity<Unit> {
override fun inbox(@RequestBody string: String): ResponseEntity<Unit> = runBlocking {
val parseActivity = apService.parseActivity(string)
apService.processActivity(string, parseActivity)
return ResponseEntity(HttpStatus.ACCEPTED)
ResponseEntity(HttpStatus.ACCEPTED)
}
}

View File

@ -10,7 +10,5 @@ import org.springframework.web.bind.annotation.RestController
@RestController
interface OutboxController {
@RequestMapping("/outbox", "/users/{username}/outbox", method = [RequestMethod.POST, RequestMethod.GET])
fun outbox(@RequestBody string: String): ResponseEntity<Unit> {
return ResponseEntity(HttpStatus.ACCEPTED)
}
fun outbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.ACCEPTED)
}

View File

@ -7,7 +7,5 @@ import org.springframework.web.bind.annotation.RestController
@RestController
class OutboxControllerImpl : OutboxController {
override fun outbox(@RequestBody string: String): ResponseEntity<Unit> {
return ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
}
override fun outbox(@RequestBody string: String): ResponseEntity<Unit> = ResponseEntity(HttpStatus.NOT_IMPLEMENTED)
}

View File

@ -9,5 +9,5 @@ import org.springframework.web.bind.annotation.RestController
@RestController
interface UserAPController {
@GetMapping("/users/{username}")
suspend fun userAp(@PathVariable("username") username: String): ResponseEntity<Person>
fun userAp(@PathVariable("username") username: String): ResponseEntity<Person>
}

View File

@ -2,14 +2,16 @@ package dev.usbharu.hideout.controller
import dev.usbharu.hideout.domain.model.ap.Person
import dev.usbharu.hideout.service.ap.APUserService
import kotlinx.coroutines.runBlocking
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
@RestController
class UserAPControllerImpl(private val apUserService: APUserService) : UserAPController {
override suspend fun userAp(username: String): ResponseEntity<Person> {
override fun userAp(username: String): ResponseEntity<Person> = runBlocking {
val person = apUserService.getPersonByName(username)
return ResponseEntity(person, HttpStatus.OK)
person.context += listOf("https://www.w3.org/ns/activitystreams")
ResponseEntity(person, HttpStatus.OK)
}
}

View File

@ -29,14 +29,8 @@ class HostMetaController(private val applicationConfig: ApplicationConfig) {
}"""
@GetMapping("/.well-known/host-meta", produces = ["application/xml"])
fun hostmeta(): ResponseEntity<String> {
return ResponseEntity(xml, HttpStatus.OK)
}
fun hostmeta(): ResponseEntity<String> = ResponseEntity(xml, HttpStatus.OK)
@GetMapping("/.well-known/host-meta.json", produces = ["application/json"])
fun hostmetJson(): ResponseEntity<String> {
return ResponseEntity(json, HttpStatus.OK)
}
fun hostmetJson(): ResponseEntity<String> = ResponseEntity(json, HttpStatus.OK)
}

View File

@ -20,11 +20,13 @@ class NodeinfoController(private val applicationConfig: ApplicationConfig) {
"${applicationConfig.url}/nodeinfo/2.0"
)
)
), HttpStatus.OK
),
HttpStatus.OK
)
}
@GetMapping("/nodeinfo/2.0")
@Suppress("FunctionNaming")
fun nodeinfo2_0(): ResponseEntity<Nodeinfo2_0> {
return ResponseEntity(
Nodeinfo2_0(

View File

@ -10,7 +10,6 @@ import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import java.net.URL
@Controller
class WebFingerController(
@ -21,14 +20,14 @@ class WebFingerController(
fun webfinger(@RequestParam("resource") resource: String): ResponseEntity<WebFinger> = runBlocking {
val acct = AcctUtil.parse(resource.replace("acct:", ""))
val user =
webFingerApiService.findByNameAndDomain(acct.username, acct.domain ?: URL(applicationConfig.url).host)
webFingerApiService.findByNameAndDomain(acct.username, acct.domain ?: applicationConfig.url.host)
val webFinger = WebFinger(
"acct:${user.name}@${user.domain}",
listOf(
WebFinger.Link(
"self",
"application/activity+json",
applicationConfig.url + "/users/" + user.id
user.url
)
)
)

View File

@ -42,10 +42,12 @@ class UserDetailsImpl(
)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSubTypes
@Suppress("UnnecessaryAbstractClass")
abstract class UserDetailsMixin
class UserDetailsDeserializer : JsonDeserializer<UserDetailsImpl>() {
val SIMPLE_GRANTED_AUTHORITY_SET = object : TypeReference<Set<SimpleGrantedAuthority>>() {}
private val SIMPLE_GRANTED_AUTHORITY_SET = object : TypeReference<Set<SimpleGrantedAuthority>>() {}
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): UserDetailsImpl {
val mapper = p.codec as ObjectMapper
val jsonNode: JsonNode = mapper.readTree(p)
@ -57,14 +59,14 @@ class UserDetailsDeserializer : JsonDeserializer<UserDetailsImpl>() {
val password = jsonNode.readText("password")
return UserDetailsImpl(
jsonNode["id"].longValue(),
jsonNode.readText("username"),
password,
true,
true,
true,
true,
authorities.toMutableList(),
id = jsonNode["id"].longValue(),
username = jsonNode.readText("username"),
password = password,
enabled = true,
accountNonExpired = true,
credentialsNonExpired = true,
accountNonLocked = true,
authorities = authorities.toMutableList(),
)
}

View File

@ -1,21 +1,25 @@
package dev.usbharu.hideout.domain.model.job
import kjob.core.Job
import org.springframework.stereotype.Component
sealed class HideoutJob(name: String = "") : Job(name)
@Component
object ReceiveFollowJob : HideoutJob("ReceiveFollowJob") {
val actor = string("actor")
val follow = string("follow")
val targetActor = string("targetActor")
}
@Component
object DeliverPostJob : HideoutJob("DeliverPostJob") {
val post = string("post")
val actor = string("actor")
val inbox = string("inbox")
}
@Component
object DeliverReactionJob : HideoutJob("DeliverReactionJob") {
val reaction = string("reaction")
val postUrl = string("postUrl")
@ -24,6 +28,7 @@ object DeliverReactionJob : HideoutJob("DeliverReactionJob") {
val id = string("id")
}
@Component
object DeliverRemoveReactionJob : HideoutJob("DeliverRemoveReactionJob") {
val id = string("id")
val inbox = string("inbox")

View File

@ -1,6 +1,5 @@
package dev.usbharu.hideout.domain.model.wellknown
data class Nodeinfo(
val links: List<Links>
) {

View File

@ -1,5 +1,6 @@
package dev.usbharu.hideout.domain.model.wellknown
@Suppress("ClassNaming")
data class Nodeinfo2_0(
val version: String,
val software: Software,

View File

@ -1,6 +1,7 @@
package dev.usbharu.hideout.plugins
import dev.usbharu.hideout.config.Config
import com.fasterxml.jackson.databind.ObjectMapper
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.domain.model.ap.JsonLd
import dev.usbharu.hideout.query.UserQueryService
import dev.usbharu.hideout.service.core.Transaction
@ -26,13 +27,18 @@ import java.text.SimpleDateFormat
import java.util.*
import javax.crypto.SecretKey
suspend fun HttpClient.postAp(urlString: String, username: String, jsonLd: JsonLd): HttpResponse {
suspend fun HttpClient.postAp(
urlString: String,
username: String,
jsonLd: JsonLd,
objectMapper: ObjectMapper
): HttpResponse {
jsonLd.context += "https://www.w3.org/ns/activitystreams"
return this.post(urlString) {
header("Accept", ContentType.Application.Activity)
header("Content-Type", ContentType.Application.Activity)
header("Signature", "keyId=\"$username\",algorithm=\"rsa-sha256\",headers=\"(request-target) digest date\"")
val text = Config.configData.objectMapper.writeValueAsString(jsonLd)
val text = objectMapper.writeValueAsString(jsonLd)
setBody(text)
}
}
@ -157,7 +163,11 @@ val httpSignaturePlugin = createClientPlugin("HttpSign", ::HttpSignaturePluginCo
}
}
class KtorKeyMap(private val userQueryService: UserQueryService, private val transaction: Transaction) : KeyMap {
class KtorKeyMap(
private val userQueryService: UserQueryService,
private val transaction: Transaction,
private val applicationConfig: ApplicationConfig
) : KeyMap {
override fun getPublicKey(keyId: String?): PublicKey = runBlocking {
val username = (keyId ?: throw IllegalArgumentException("keyId is null")).substringBeforeLast("#pubkey")
.substringAfterLast("/")
@ -165,7 +175,7 @@ class KtorKeyMap(private val userQueryService: UserQueryService, private val tra
transaction.transaction {
userQueryService.findByNameAndDomain(
username,
Config.configData.domain
applicationConfig.url.host
).run {
publicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
@ -185,7 +195,7 @@ class KtorKeyMap(private val userQueryService: UserQueryService, private val tra
transaction.transaction {
userQueryService.findByNameAndDomain(
username,
Config.configData.domain
applicationConfig.url.host
).privateKey?.run {
replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")

View File

@ -48,9 +48,9 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
it[clientSecretExpiresAt] = registeredClient.clientSecretExpiresAt
it[clientName] = registeredClient.clientName
it[clientAuthenticationMethods] =
registeredClient.clientAuthenticationMethods.map { it.value }.joinToString(",")
registeredClient.clientAuthenticationMethods.map { method -> method.value }.joinToString(",")
it[authorizationGrantTypes] =
registeredClient.authorizationGrantTypes.map { it.value }.joinToString(",")
registeredClient.authorizationGrantTypes.map { type -> type.value }.joinToString(",")
it[redirectUris] = registeredClient.redirectUris.joinToString(",")
it[postLogoutRedirectUris] = registeredClient.postLogoutRedirectUris.joinToString(",")
it[scopes] = registeredClient.scopes.joinToString(",")
@ -100,20 +100,7 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
private fun <T, U> jsonToMap(json: String): Map<T, U> = objectMapper.readValue(json)
companion object {
val objectMapper: ObjectMapper = ObjectMapper()
val LOGGER = LoggerFactory.getLogger(RegisteredClientRepositoryImpl::class.java)
init {
val classLoader = ExposedOAuth2AuthorizationService::class.java.classLoader
val modules = SecurityJackson2Modules.getModules(classLoader)
this.objectMapper.registerModules(JavaTimeModule())
this.objectMapper.registerModules(modules)
this.objectMapper.registerModules(OAuth2AuthorizationServerJackson2Module())
}
}
@Suppress("CyclomaticComplexMethod")
fun ResultRow.toRegisteredClient(): SpringRegisteredClient {
fun resolveClientAuthenticationMethods(string: String): ClientAuthenticationMethod {
return when (string) {
@ -175,6 +162,20 @@ class RegisteredClientRepositoryImpl(private val database: Database) : Registere
return builder.build()
}
companion object {
val objectMapper: ObjectMapper = ObjectMapper()
val LOGGER = LoggerFactory.getLogger(RegisteredClientRepositoryImpl::class.java)
init {
val classLoader = ExposedOAuth2AuthorizationService::class.java.classLoader
val modules = SecurityJackson2Modules.getModules(classLoader)
this.objectMapper.registerModules(JavaTimeModule())
this.objectMapper.registerModules(modules)
this.objectMapper.registerModules(OAuth2AuthorizationServerJackson2Module())
}
}
}
// org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql

View File

@ -1,7 +1,8 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.domain.model.ap.Create
import dev.usbharu.hideout.domain.model.ap.Note
import dev.usbharu.hideout.domain.model.hideout.entity.Post
@ -20,6 +21,7 @@ import io.ktor.client.*
import io.ktor.client.statement.*
import kjob.core.job.JobProps
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
import java.time.Instant
@ -41,7 +43,10 @@ class APNoteServiceImpl(
private val apUserService: APUserService,
private val userQueryService: UserQueryService,
private val followerQueryService: FollowerQueryService,
private val postQueryService: PostQueryService
private val postQueryService: PostQueryService,
@Qualifier("activitypub") private val objectMapper: ObjectMapper,
private val applicationConfig: ApplicationConfig
) : APNoteService {
private val logger = LoggerFactory.getLogger(this::class.java)
@ -49,7 +54,7 @@ class APNoteServiceImpl(
override suspend fun createNote(post: Post) {
val followers = followerQueryService.findFollowersById(post.userId)
val userEntity = userQueryService.findById(post.userId)
val note = Config.configData.objectMapper.writeValueAsString(post)
val note = objectMapper.writeValueAsString(post)
followers.forEach { followerEntity ->
jobQueueParentService.schedule(DeliverPostJob) {
props[DeliverPostJob.actor] = userEntity.url
@ -61,7 +66,7 @@ class APNoteServiceImpl(
override suspend fun createNoteJob(props: JobProps<DeliverPostJob>) {
val actor = props[DeliverPostJob.actor]
val postEntity = Config.configData.objectMapper.readValue<Post>(props[DeliverPostJob.post])
val postEntity = objectMapper.readValue<Post>(props[DeliverPostJob.post])
val note = Note(
name = "Note",
id = postEntity.url,
@ -79,8 +84,9 @@ class APNoteServiceImpl(
name = "Create Note",
`object` = note,
actor = note.attributedTo,
id = "${Config.configData.url}/create/note/${postEntity.id}"
)
id = "${applicationConfig.url}/create/note/${postEntity.id}"
),
objectMapper
)
}
@ -95,7 +101,7 @@ class APNoteServiceImpl(
url,
targetActor?.let { "$targetActor#pubkey" }
)
val note = Config.configData.objectMapper.readValue<Note>(response.bodyAsText())
val note = objectMapper.readValue<Note>(response.bodyAsText())
return note(note, targetActor, url)
}

View File

@ -1,5 +1,6 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.domain.model.ap.Like
@ -14,6 +15,7 @@ import dev.usbharu.hideout.query.UserQueryService
import dev.usbharu.hideout.service.job.JobQueueParentService
import io.ktor.client.*
import kjob.core.job.JobProps
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
import java.time.Instant
@ -31,8 +33,10 @@ class APReactionServiceImpl(
private val httpClient: HttpClient,
private val userQueryService: UserQueryService,
private val followerQueryService: FollowerQueryService,
private val postQueryService: PostQueryService
) : APReactionService {
private val postQueryService: PostQueryService,
@Qualifier("activitypub") private val objectMapper: ObjectMapper,
) : APReactionService {
override suspend fun reaction(like: Reaction) {
val followers = followerQueryService.findFollowersById(like.userId)
val user = userQueryService.findById(like.userId)
@ -79,7 +83,8 @@ class APReactionServiceImpl(
`object` = postUrl,
id = "${Config.configData.url}/like/note/$id",
content = content
)
),
objectMapper
)
}
@ -96,7 +101,8 @@ class APReactionServiceImpl(
`object` = like,
id = "${Config.configData.url}/undo/note/${like.id}",
published = Instant.now()
)
),
objectMapper
)
}
}

View File

@ -1,7 +1,7 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.domain.model.ActivityPubResponse
import dev.usbharu.hideout.domain.model.ActivityPubStringResponse
import dev.usbharu.hideout.domain.model.ap.Accept
@ -15,9 +15,9 @@ import dev.usbharu.hideout.service.user.UserService
import io.ktor.client.*
import io.ktor.http.*
import kjob.core.job.JobProps
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
interface APReceiveFollowService {
suspend fun receiveFollow(follow: Follow): ActivityPubResponse
suspend fun receiveFollowJob(props: JobProps<ReceiveFollowJob>)
@ -30,24 +30,26 @@ class APReceiveFollowServiceImpl(
private val userService: UserService,
private val httpClient: HttpClient,
private val userQueryService: UserQueryService,
private val transaction: Transaction
private val transaction: Transaction,
@Qualifier("activitypub") private val objectMapper: ObjectMapper
) : APReceiveFollowService {
override suspend fun receiveFollow(follow: Follow): ActivityPubResponse {
// TODO: Verify HTTP Signature
jobQueueParentService.schedule(ReceiveFollowJob) {
props[ReceiveFollowJob.actor] = follow.actor
props[ReceiveFollowJob.follow] = Config.configData.objectMapper.writeValueAsString(follow)
props[ReceiveFollowJob.follow] = objectMapper.writeValueAsString(follow)
props[ReceiveFollowJob.targetActor] = follow.`object`
}
return ActivityPubStringResponse(HttpStatusCode.OK, "{}", ContentType.Application.Json)
}
override suspend fun receiveFollowJob(props: JobProps<ReceiveFollowJob>) {
// throw Exception()
transaction.transaction {
val actor = props[ReceiveFollowJob.actor]
val targetActor = props[ReceiveFollowJob.targetActor]
val person = apUserService.fetchPerson(actor, targetActor)
val follow = Config.configData.objectMapper.readValue<Follow>(props[ReceiveFollowJob.follow])
val follow = objectMapper.readValue<Follow>(props[ReceiveFollowJob.follow])
httpClient.postAp(
urlString = person.inbox ?: throw IllegalArgumentException("inbox is not found"),
username = "$targetActor#pubkey",
@ -55,7 +57,8 @@ class APReceiveFollowServiceImpl(
name = "Follow",
`object` = follow,
actor = targetActor
)
),
objectMapper
)
val targetEntity = userQueryService.findByUrl(targetActor)

View File

@ -1,9 +1,11 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.ObjectMapper
import dev.usbharu.hideout.domain.model.ap.Follow
import dev.usbharu.hideout.domain.model.hideout.dto.SendFollowDto
import dev.usbharu.hideout.plugins.postAp
import io.ktor.client.*
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
@ -12,7 +14,10 @@ interface APSendFollowService {
}
@Service
class APSendFollowServiceImpl(private val httpClient: HttpClient) : APSendFollowService {
class APSendFollowServiceImpl(
private val httpClient: HttpClient,
@Qualifier("activitypub") private val objectMapper: ObjectMapper,
) : APSendFollowService {
override suspend fun sendFollow(sendFollowDto: SendFollowDto) {
val follow = Follow(
name = "Follow",
@ -22,7 +27,8 @@ class APSendFollowServiceImpl(private val httpClient: HttpClient) : APSendFollow
httpClient.postAp(
urlString = sendFollowDto.followTargetUserId.inbox,
username = sendFollowDto.userId.url,
jsonLd = follow
jsonLd = follow,
objectMapper
)
}
}

View File

@ -1,8 +1,8 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.domain.model.ActivityPubResponse
import dev.usbharu.hideout.domain.model.ap.Follow
import dev.usbharu.hideout.domain.model.job.*
@ -11,6 +11,7 @@ import kjob.core.dsl.JobContextWithProps
import kjob.core.job.JobProps
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
@ -181,12 +182,13 @@ class APServiceImpl(
private val apAcceptService: APAcceptService,
private val apCreateService: APCreateService,
private val apLikeService: APLikeService,
private val apReactionService: APReactionService
private val apReactionService: APReactionService,
@Qualifier("activitypub") private val objectMapper: ObjectMapper
) : APService {
val logger: Logger = LoggerFactory.getLogger(this::class.java)
override fun parseActivity(json: String): ActivityType {
val readTree = Config.configData.objectMapper.readTree(json)
val readTree = objectMapper.readTree(json)
logger.trace("readTree: {}", readTree)
if (readTree.isObject.not()) {
throw JsonParseException("Json is not object.")
@ -204,17 +206,17 @@ class APServiceImpl(
override suspend fun processActivity(json: String, type: ActivityType): ActivityPubResponse {
logger.debug("proccess activity: {}", type)
return when (type) {
ActivityType.Accept -> apAcceptService.receiveAccept(Config.configData.objectMapper.readValue(json))
ActivityType.Accept -> apAcceptService.receiveAccept(objectMapper.readValue(json))
ActivityType.Follow -> apReceiveFollowService.receiveFollow(
Config.configData.objectMapper.readValue(
objectMapper.readValue(
json,
Follow::class.java
)
)
ActivityType.Create -> apCreateService.receiveCreate(Config.configData.objectMapper.readValue(json))
ActivityType.Like -> apLikeService.receiveLike(Config.configData.objectMapper.readValue(json))
ActivityType.Undo -> apUndoService.receiveUndo(Config.configData.objectMapper.readValue(json))
ActivityType.Create -> apCreateService.receiveCreate(objectMapper.readValue(json))
ActivityType.Like -> apLikeService.receiveLike(objectMapper.readValue(json))
ActivityType.Undo -> apUndoService.receiveUndo(objectMapper.readValue(json))
else -> {
throw IllegalArgumentException("$type is not supported.")
@ -224,16 +226,25 @@ class APServiceImpl(
override suspend fun <T : HideoutJob> processActivity(job: JobContextWithProps<T>, hideoutJob: HideoutJob) {
logger.debug("processActivity: ${hideoutJob.name}")
when (hideoutJob) {
ReceiveFollowJob -> apReceiveFollowService.receiveFollowJob(
job.props as JobProps<ReceiveFollowJob>
)
DeliverPostJob -> apNoteService.createNoteJob(job.props as JobProps<DeliverPostJob>)
DeliverReactionJob -> apReactionService.reactionJob(job.props as JobProps<DeliverReactionJob>)
DeliverRemoveReactionJob -> apReactionService.removeReactionJob(
// println(apReceiveFollowService::class.java)
// apReceiveFollowService.receiveFollowJob(job.props as JobProps<ReceiveFollowJob>)
when {
hideoutJob is ReceiveFollowJob -> {
apReceiveFollowService.receiveFollowJob(
job.props as JobProps<ReceiveFollowJob>
)
}
hideoutJob is DeliverPostJob -> apNoteService.createNoteJob(job.props as JobProps<DeliverPostJob>)
hideoutJob is DeliverReactionJob -> apReactionService.reactionJob(job.props as JobProps<DeliverReactionJob>)
hideoutJob is DeliverRemoveReactionJob -> apReactionService.removeReactionJob(
job.props as JobProps<DeliverRemoveReactionJob>
)
else -> {
throw IllegalStateException("WTF")
}
}
}
}

View File

@ -1,7 +1,8 @@
package dev.usbharu.hideout.service.ap
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.domain.model.ap.Image
import dev.usbharu.hideout.domain.model.ap.Key
import dev.usbharu.hideout.domain.model.ap.Person
@ -18,6 +19,7 @@ import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
@Service
@ -41,16 +43,18 @@ class APUserServiceImpl(
private val userService: UserService,
private val httpClient: HttpClient,
private val userQueryService: UserQueryService,
private val transaction: Transaction
private val transaction: Transaction,
private val applicationConfig: ApplicationConfig,
@Qualifier("activitypub") private val objectMapper: ObjectMapper
) :
APUserService {
override suspend fun getPersonByName(name: String): Person {
val userEntity = transaction.transaction {
userQueryService.findByNameAndDomain(name, Config.configData.domain)
userQueryService.findByNameAndDomain(name, applicationConfig.url.host)
}
// TODO: JOINで書き直し
val userUrl = "${Config.configData.url}/users/$name"
val userUrl = "${applicationConfig.url}/users/$name"
return Person(
type = emptyList(),
name = userEntity.name,
@ -73,7 +77,7 @@ class APUserServiceImpl(
owner = userUrl,
publicKeyPem = userEntity.publicKey
),
endpoints = mapOf("sharedInbox" to "${Config.configData.url}/inbox")
endpoints = mapOf("sharedInbox" to "${applicationConfig.url}/inbox")
)
}
@ -105,7 +109,7 @@ class APUserServiceImpl(
owner = url,
publicKeyPem = userEntity.publicKey
),
endpoints = mapOf("sharedInbox" to "${Config.configData.url}/inbox")
endpoints = mapOf("sharedInbox" to "${applicationConfig.url}/inbox")
) to userEntity
} catch (ignore: FailedToGetResourcesException) {
val httpResponse = if (targetActor != null) {
@ -115,7 +119,7 @@ class APUserServiceImpl(
accept(ContentType.Application.Activity)
}
}
val person = Config.configData.objectMapper.readValue<Person>(httpResponse.bodyAsText())
val person = objectMapper.readValue<Person>(httpResponse.bodyAsText())
person to userService.createRemoteUser(
RemoteUserCreateDto(

View File

@ -18,10 +18,10 @@ class AccountApiServiceImpl(private val accountService: AccountService, private
AccountApiService {
override suspend fun verifyCredentials(userid: Long): CredentialAccount = transaction.transaction {
val account = accountService.findById(userid)
of(account)
from(account)
}
private fun of(account: Account): CredentialAccount {
private fun from(account: Account): CredentialAccount {
return CredentialAccount(
id = account.id,
username = account.username,

View File

@ -55,7 +55,5 @@ class AppApiServiceImpl(
}
}
private fun parseScope(string: String): Set<String> {
return string.split(" ").toSet()
}
private fun parseScope(string: String): Set<String> = string.split(" ").toSet()
}

View File

@ -3,7 +3,6 @@ package dev.usbharu.hideout.service.api.mastodon
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.domain.mastodon.model.generated.*
import org.springframework.stereotype.Service
import java.net.URL
@Service
interface InstanceApiService {
@ -12,17 +11,18 @@ interface InstanceApiService {
@Service
class InstanceApiServiceImpl(private val applicationConfig: ApplicationConfig) : InstanceApiService {
@Suppress("LongMethod")
override suspend fun v1Instance(): V1Instance {
val url = applicationConfig.url
val url1 = URL(url)
return V1Instance(
uri = url1.host,
uri = url.host,
title = "Hideout Server",
shortDescription = "Hideout test server",
description = "This server is operated for testing of Hideout. We are not responsible for any events that occur when associating with this server",
description = "This server is operated for testing of Hideout." +
" We are not responsible for any events that occur when associating with this server",
email = "i@usbharu.dev",
version = "0.0.1",
urls = V1InstanceUrls("wss://${url1.host}"),
urls = V1InstanceUrls("wss://${url.host}"),
stats = V1InstanceStats(1, 0, 0),
thumbnail = null,
languages = listOf("ja-JP"),
@ -37,7 +37,7 @@ class InstanceApiServiceImpl(private val applicationConfig: ApplicationConfig) :
23
),
mediaAttachments = V1InstanceConfigurationMediaAttachments(
listOf(),
emptyList(),
0,
0,
0,

View File

@ -26,6 +26,7 @@ class StatsesApiServiceImpl(
private val userQueryService: UserQueryService
) :
StatusesApiService {
@Suppress("LongMethod")
override suspend fun postStatus(statusesRequest: StatusesRequest, user: UserDetailsImpl): Status {
val visibility = when (statusesRequest.visibility) {
StatusesRequest.Visibility.public -> Visibility.PUBLIC
@ -37,12 +38,12 @@ class StatsesApiServiceImpl(
val post = postService.createLocal(
PostCreateDto(
statusesRequest.status.orEmpty(),
statusesRequest.spoilerText,
visibility,
null,
statusesRequest.inReplyToId?.toLongOrNull(),
user.id
text = statusesRequest.status.orEmpty(),
overview = statusesRequest.spoilerText,
visibility = visibility,
repostId = null,
repolyId = statusesRequest.inReplyToId?.toLongOrNull(),
userId = user.id
)
)
val account = accountService.findById(user.id)
@ -58,7 +59,7 @@ class StatsesApiServiceImpl(
val replyUser = if (post.replyId != null) {
try {
userQueryService.findById(postQueryService.findById(post.replyId).userId).id
} catch (e: FailedToGetResourcesException) {
} catch (ignore: FailedToGetResourcesException) {
null
}
} else {
@ -82,7 +83,7 @@ class StatsesApiServiceImpl(
favouritesCount = 0,
repliesCount = 0,
url = post.url,
post.replyId?.toString(),
inReplyToId = post.replyId?.toString(),
inReplyToAccountId = replyUser?.toString(),
reblog = null,
language = null,

View File

@ -40,6 +40,7 @@ class ExposedOAuth2AuthorizationService(
}
}
@Suppress("LongMethod", "CyclomaticComplexMethod")
override fun save(authorization: OAuth2Authorization?): Unit = runBlocking {
requireNotNull(authorization)
transaction.transaction {
@ -56,7 +57,8 @@ class ExposedOAuth2AuthorizationService(
it[registeredClientId] = authorization.registeredClientId
it[principalName] = authorization.principalName
it[authorizationGrantType] = authorization.authorizationGrantType.value
it[authorizedScopes] = authorization.authorizedScopes.joinToString(",").takeIf { it.isNotEmpty() }
it[authorizedScopes] =
authorization.authorizedScopes.joinToString(",").takeIf { s -> s.isNotEmpty() }
it[attributes] = mapToJson(authorization.attributes)
it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE)
it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue
@ -99,7 +101,8 @@ class ExposedOAuth2AuthorizationService(
it[registeredClientId] = authorization.registeredClientId
it[principalName] = authorization.principalName
it[authorizationGrantType] = authorization.authorizationGrantType.value
it[authorizedScopes] = authorization.authorizedScopes.joinToString(",").takeIf { it.isNotEmpty() }
it[authorizedScopes] =
authorization.authorizedScopes.joinToString(",").takeIf { s -> s.isNotEmpty() }
it[attributes] = mapToJson(authorization.attributes)
it[state] = authorization.getAttribute(OAuth2ParameterNames.STATE)
it[authorizationCodeValue] = authorizationCodeToken?.token?.tokenValue
@ -111,8 +114,9 @@ class ExposedOAuth2AuthorizationService(
it[accessTokenIssuedAt] = accessToken?.token?.issuedAt
it[accessTokenExpiresAt] = accessToken?.token?.expiresAt
it[accessTokenMetadata] = accessToken?.metadata?.let { it1 -> mapToJson(it1) }
it[accessTokenType] = accessToken?.token?.tokenType?.value
it[accessTokenScopes] = accessToken?.token?.scopes?.joinToString(",")?.takeIf { it.isNotEmpty() }
it[accessTokenType] = accessToken?.run { token.tokenType.value }
it[accessTokenScopes] =
accessToken?.run { token.scopes.joinToString(",").takeIf { s -> s.isNotEmpty() } }
it[refreshTokenValue] = refreshToken?.token?.tokenValue
it[refreshTokenIssuedAt] = refreshToken?.token?.issuedAt
it[refreshTokenExpiresAt] = refreshToken?.token?.expiresAt
@ -203,6 +207,7 @@ class ExposedOAuth2AuthorizationService(
}
}
@Suppress("LongMethod", "CyclomaticComplexMethod")
fun ResultRow.toAuthorization(): OAuth2Authorization {
val registeredClientId = this[Authorization.registeredClientId]

View File

@ -1,5 +1,6 @@
package dev.usbharu.hideout.service.auth
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.plugins.KtorKeyMap
import dev.usbharu.hideout.query.UserQueryService
import dev.usbharu.hideout.service.core.Transaction
@ -15,10 +16,13 @@ interface HttpSignatureVerifyService {
@Service
class HttpSignatureVerifyServiceImpl(
private val userQueryService: UserQueryService,
private val transaction: Transaction
private val transaction: Transaction,
private val applicationConfig: ApplicationConfig
) : HttpSignatureVerifyService {
override fun verify(headers: Headers): Boolean {
val build = SignatureHeaderVerifier.builder().keyMap(KtorKeyMap(userQueryService, transaction)).build()
val build =
SignatureHeaderVerifier.builder().keyMap(KtorKeyMap(userQueryService, transaction, applicationConfig))
.build()
return true
// build.verify(object : HttpMessage {
// override fun headerValues(name: String?): MutableList<String> {

View File

@ -9,7 +9,6 @@ import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
import java.net.URL
@Service
class UserDetailsServiceImpl(
@ -23,16 +22,16 @@ class UserDetailsServiceImpl(
throw UsernameNotFoundException("$username not found")
}
transaction.transaction {
val findById = userQueryService.findByNameAndDomain(username, URL(applicationConfig.url).host)
val findById = userQueryService.findByNameAndDomain(username, applicationConfig.url.host)
UserDetailsImpl(
findById.id,
findById.name,
findById.password,
true,
true,
true,
true,
mutableListOf()
id = findById.id,
username = findById.name,
password = findById.password,
enabled = true,
accountNonExpired = true,
credentialsNonExpired = true,
accountNonLocked = true,
authorities = mutableListOf()
)
}
}

View File

@ -1,12 +1,14 @@
package dev.usbharu.hideout.service.job
import kjob.core.Job
import kjob.core.dsl.KJobFunctions
import org.springframework.stereotype.Service
import dev.usbharu.hideout.domain.model.job.HideoutJob as HJ
import kjob.core.dsl.JobContextWithProps as JCWP
import kjob.core.dsl.JobRegisterContext as JRC
@Service
interface JobQueueWorkerService {
fun init(defines: List<Pair<Job, JRC<Job, JCWP<Job>>.(Job) -> KJobFunctions<Job, JCWP<Job>>>>)
fun init(
defines: List<Pair<HJ, JRC<HJ, JCWP<HJ>>.(HJ) -> KJobFunctions<HJ, JCWP<HJ>>>>
)
}

View File

@ -1,13 +1,13 @@
package dev.usbharu.hideout.service.job
import dev.usbharu.kjob.exposed.ExposedKJob
import kjob.core.Job
import kjob.core.dsl.JobRegisterContext
import kjob.core.dsl.KJobFunctions
import kjob.core.kjob
import org.jetbrains.exposed.sql.Database
import org.springframework.stereotype.Service
import dev.usbharu.hideout.domain.model.job.HideoutJob as HJ
import kjob.core.dsl.JobContextWithProps as JCWP
import kjob.core.dsl.JobRegisterContext as JRC
@Service
class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorkerService {
@ -22,7 +22,7 @@ class KJobJobQueueWorkerService(private val database: Database) : JobQueueWorker
}
override fun init(
defines: List<Pair<Job, JRC<Job, JCWP<Job>>.(Job) -> KJobFunctions<Job, JCWP<Job>>>>
defines: List<Pair<HJ, JobRegisterContext<HJ, JCWP<HJ>>.(HJ) -> KJobFunctions<HJ, JCWP<HJ>>>>
) {
defines.forEach { job ->
kjob.register(job.first, job.second)

View File

@ -25,15 +25,15 @@ class AccountServiceImpl(private val userQueryService: UserQueryService) : Accou
header = findById.url + "/header.jpg",
headerStatic = findById.url + "/header.jpg",
locked = false,
emptyList(),
emptyList(),
false,
false,
false,
findById.createdAt.toString(),
findById.createdAt.toString(),
0,
0,
fields = emptyList(),
emojis = emptyList(),
bot = false,
group = false,
discoverable = false,
createdAt = findById.createdAt.toString(),
lastStatusAt = findById.createdAt.toString(),
statusesCount = 0,
followersCount = 0,
)
}
}

View File

@ -12,9 +12,7 @@ class UserAuthServiceImpl(
val userQueryService: UserQueryService
) : UserAuthService {
override fun hash(password: String): String {
return BCryptPasswordEncoder().encode(password)
}
override fun hash(password: String): String = BCryptPasswordEncoder().encode(password)
override suspend fun usernameAlreadyUse(username: String): Boolean {
userQueryService.findByName(username)

View File

@ -1,6 +1,6 @@
package dev.usbharu.hideout.service.user
import dev.usbharu.hideout.config.Config
import dev.usbharu.hideout.config.ApplicationConfig
import dev.usbharu.hideout.domain.model.hideout.dto.RemoteUserCreateDto
import dev.usbharu.hideout.domain.model.hideout.dto.SendFollowDto
import dev.usbharu.hideout.domain.model.hideout.dto.UserCreateDto
@ -19,12 +19,13 @@ class UserServiceImpl(
private val userAuthService: UserAuthService,
private val apSendFollowService: APSendFollowService,
private val userQueryService: UserQueryService,
private val followerQueryService: FollowerQueryService
private val followerQueryService: FollowerQueryService,
private val applicationConfig: ApplicationConfig
) :
UserService {
override suspend fun usernameAlreadyUse(username: String): Boolean {
val findByNameAndDomain = userQueryService.findByNameAndDomain(username, Config.configData.domain)
val findByNameAndDomain = userQueryService.findByNameAndDomain(username, applicationConfig.url.host)
return findByNameAndDomain != null
}
@ -35,13 +36,13 @@ class UserServiceImpl(
val userEntity = User.of(
id = nextId,
name = user.name,
domain = Config.configData.domain,
domain = applicationConfig.url.host,
screenName = user.screenName,
description = user.description,
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}",
inbox = "${applicationConfig.url}/users/${user.name}/inbox",
outbox = "${applicationConfig.url}/users/${user.name}/outbox",
url = "${applicationConfig.url}/users/${user.name}",
publicKey = keyPair.public.toPem(),
privateKey = keyPair.private.toPem(),
createdAt = Instant.now()
@ -70,7 +71,7 @@ class UserServiceImpl(
override suspend fun followRequest(id: Long, followerId: Long): Boolean {
val user = userRepository.findById(id) ?: throw UserNotFoundException("$id was not found.")
val follower = userRepository.findById(followerId) ?: throw UserNotFoundException("$followerId was not found.")
return if (user.domain == Config.configData.domain) {
return if (user.domain == applicationConfig.url.host) {
follow(id, followerId)
true
} else {

View File

@ -1,16 +0,0 @@
package dev.usbharu.hideout.util
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
object JsonUtil {
val objectMapper = jacksonObjectMapper().registerModule(JavaTimeModule())
fun mapToJson(map: Map<*, *>, objectMapper: ObjectMapper = this.objectMapper): String =
objectMapper.writeValueAsString(map)
fun <K, V> jsonToMap(json: String, objectMapper: ObjectMapper = this.objectMapper): Map<K, V> =
objectMapper.readValue(json)
}

View File

@ -1,39 +0,0 @@
package dev.usbharu.hideout.util
import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.*
object JsonWebKeyUtil {
fun publicKeyToJwk(publicKey: String, kid: String): String {
val x509EncodedKeySpec = X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))
val generatePublic = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec)
return publicKeyToJwk(generatePublic as RSAPublicKey, kid)
}
fun publicKeyToJwk(publicKey: RSAPublicKey, kid: String): String {
val e = encodeBase64UInt(publicKey.publicExponent)
val n = encodeBase64UInt(publicKey.modulus)
return """{"keys":[{"e":"$e","n":"$n","use":"sig","kid":"$kid","kty":"RSA"}]}"""
}
private fun encodeBase64UInt(bigInteger: BigInteger, minLength: Int = -1): String {
require(bigInteger.signum() >= 0) { "Cannot encode negative numbers" }
var bytes = bigInteger.toByteArray()
if (bigInteger.bitLength() % 8 == 0 && (bytes[0] == 0.toByte()) && bytes.size > 1) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.size)
}
if (minLength != -1) {
if (bytes.size < minLength) {
val array = ByteArray(minLength)
System.arraycopy(bytes, 0, array, minLength - bytes.size, bytes.size)
bytes = array
}
}
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
}
}

View File

@ -4,7 +4,7 @@
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="TRACE">
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
@ -12,5 +12,5 @@
<logger name="kjob.core.internal.scheduler.JobServiceImpl" level="INFO"/>
<logger name="Exposed" level="INFO"/>
<logger name="io.ktor.server.plugins.contentnegotiation" level="INFO"/>
<logger name="org.springframework.security" level="trace"/>
<logger name="org.springframework.security" level="DEBUG"/>
</configuration>

View File

@ -12,6 +12,8 @@ import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import utils.JsonObjectMapper.objectMapper
import utils.TestApplicationConfig.testApplicationConfig
import utils.TestTransaction
import java.security.KeyPairGenerator
import java.time.Instant
@ -41,7 +43,7 @@ class ActivityPubKtTest {
}
}
runBlocking {
val ktorKeyMap = KtorKeyMap(userQueryService, TestTransaction)
val ktorKeyMap = KtorKeyMap(userQueryService, TestTransaction, testApplicationConfig)
val httpClient = HttpClient(
MockEngine { httpRequestData ->
@ -57,7 +59,7 @@ class ActivityPubKtTest {
}
}
httpClient.postAp("https://localhost", "test", JsonLd(emptyList()))
httpClient.postAp("https://localhost", "test", JsonLd(emptyList()), objectMapper)
}
}
}

View File

@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
import utils.TestApplicationConfig.testApplicationConfig
import utils.TestTransaction
import java.security.KeyPairGenerator
import java.time.Instant
@ -36,7 +37,7 @@ class KtorKeyMapTest {
)
}
}
val ktorKeyMap = KtorKeyMap(userQueryService, TestTransaction)
val ktorKeyMap = KtorKeyMap(userQueryService, TestTransaction, testApplicationConfig)
ktorKeyMap.getPrivateKey("test")
}

View File

@ -22,13 +22,15 @@ import org.junit.jupiter.api.Test
import org.mockito.Mockito.eq
import org.mockito.kotlin.*
import utils.JsonObjectMapper
import utils.JsonObjectMapper.objectMapper
import utils.TestApplicationConfig.testApplicationConfig
import java.time.Instant
import kotlin.test.assertEquals
class APNoteServiceImplTest {
@Test
fun `createPost 新しい投稿`() = runTest {
val followers = listOf<User>(
val followers = listOf(
User.of(
2L,
"follower",
@ -84,7 +86,9 @@ class APNoteServiceImplTest {
mock(),
userQueryService,
followerQueryService,
mock()
mock(),
objectMapper = objectMapper,
applicationConfig = testApplicationConfig
)
val postEntity = Post.of(
1L,
@ -109,13 +113,15 @@ class APNoteServiceImplTest {
}
)
val activityPubNoteService = APNoteServiceImpl(
httpClient,
mock(),
mock(),
mock(),
mock(),
mock(),
mock()
httpClient = httpClient,
jobQueueParentService = mock(),
postRepository = mock(),
apUserService = mock(),
userQueryService = mock(),
followerQueryService = mock(),
postQueryService = mock(),
objectMapper = objectMapper,
applicationConfig = testApplicationConfig
)
activityPubNoteService.createNoteJob(
JobProps(

View File

@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers.anyString
import org.mockito.kotlin.*
import utils.JsonObjectMapper
import utils.JsonObjectMapper.objectMapper
import utils.TestTransaction
import java.time.Instant
@ -34,7 +35,10 @@ class APReceiveFollowServiceImplTest {
onBlocking { schedule(eq(ReceiveFollowJob), any()) } doReturn Unit
}
val activityPubFollowService =
APReceiveFollowServiceImpl(jobQueueParentService, mock(), mock(), mock(), mock(), TestTransaction)
APReceiveFollowServiceImpl(
jobQueueParentService, mock(), mock(), mock(), mock(), TestTransaction,
objectMapper
)
activityPubFollowService.receiveFollow(
Follow(
emptyList(),
@ -163,7 +167,8 @@ class APReceiveFollowServiceImplTest {
}
),
userQueryService,
TestTransaction
TestTransaction,
objectMapper
)
activityPubFollowService.receiveFollowJob(
JobProps(

View File

@ -12,6 +12,7 @@ import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers.anyString
import org.mockito.kotlin.*
import utils.TestApplicationConfig.testApplicationConfig
import java.security.KeyPairGenerator
import kotlin.test.assertEquals
import kotlin.test.assertNull
@ -28,7 +29,8 @@ class UserServiceTest {
onBlocking { hash(anyString()) } doReturn "hashedPassword"
onBlocking { generateKeyPair() } doReturn generateKeyPair
}
val userService = UserServiceImpl(userRepository, userAuthService, mock(), mock(), mock())
val userService =
UserServiceImpl(userRepository, userAuthService, mock(), mock(), mock(), testApplicationConfig)
userService.createLocalUser(UserCreateDto("test", "testUser", "XXXXXXXXXXXXX", "test"))
verify(userRepository, times(1)).save(any())
argumentCaptor<dev.usbharu.hideout.domain.model.hideout.entity.User> {
@ -54,7 +56,7 @@ class UserServiceTest {
val userRepository = mock<UserRepository> {
onBlocking { nextId() } doReturn 113345L
}
val userService = UserServiceImpl(userRepository, mock(), mock(), mock(), mock())
val userService = UserServiceImpl(userRepository, mock(), mock(), mock(), mock(), testApplicationConfig)
val user = RemoteUserCreateDto(
"test",
"example.com",

View File

@ -0,0 +1,8 @@
package utils
import dev.usbharu.hideout.config.ApplicationConfig
import java.net.URL
object TestApplicationConfig {
val testApplicationConfig = ApplicationConfig(URL("https://example.com"))
}