diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentRepository.kt index c6aaeeb2..00240744 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentRepository.kt @@ -1,5 +1,6 @@ package kr.co.vividnext.sodalive.content.comment +import com.querydsl.core.types.dsl.BooleanExpression import com.querydsl.core.types.dsl.CaseBuilder import com.querydsl.core.types.dsl.Expressions import com.querydsl.jpa.JPAExpressions @@ -100,7 +101,8 @@ class AudioContentCommentQueryRepositoryImpl( audioContentComment.id, audioContentComment.member.id, displayName, - audioContentComment.member.profileImage.prepend("/").prepend(cloudFrontHost), + audioContentComment.member.profileImage.coalesce("profile/default-profile.png") + .prepend("/").prepend(cloudFrontHost), audioContentComment.comment, audioContentComment.languageCode, audioContentComment.isSecret, @@ -152,13 +154,7 @@ class AudioContentCommentQueryRepositoryImpl( override fun commentReplyCountByAudioContentCommentId(commentId: Long, memberId: Long): Int { return queryFactory.select(audioContentComment.id) .from(audioContentComment) - .where( - audioContentComment.parent.isNotNull - .and(audioContentComment.parent.id.eq(commentId)) - .and(audioContentComment.isActive.isTrue) - .and(audioContentComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) - .and(audioContentComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) - ) + .where(visibleReplyCondition(commentId, memberId)) .fetch() .size } @@ -194,7 +190,8 @@ class AudioContentCommentQueryRepositoryImpl( audioContentComment.id, audioContentComment.member.id, displayName, - audioContentComment.member.profileImage.prepend("/").prepend(cloudFrontHost), + audioContentComment.member.profileImage.coalesce("profile/default-profile.png") + .prepend("/").prepend(cloudFrontHost), audioContentComment.comment, audioContentComment.languageCode, audioContentComment.isSecret, @@ -205,13 +202,7 @@ class AudioContentCommentQueryRepositoryImpl( ) .from(audioContentComment) .innerJoin(audioContentComment.member, member) - .where( - audioContentComment.parent.isNotNull - .and(audioContentComment.parent.id.eq(commentId)) - .and(audioContentComment.isActive.isTrue) - .and(audioContentComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) - .and(audioContentComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) - ) + .where(visibleReplyCondition(commentId, memberId)) .offset(offset) .limit(limit.toLong()) .orderBy(audioContentComment.createdAt.desc()) @@ -269,6 +260,30 @@ class AudioContentCommentQueryRepositoryImpl( return response } + private fun visibleReplyCondition(commentId: Long, memberId: Long): BooleanExpression { + return audioContentComment.parent.id.eq(commentId) + .and(audioContentComment.isActive.isTrue) + .and(audioContentComment.parent.isActive.isTrue) + .and(audioContentComment.parent.parent.isNull) + .and(audioContentComment.audioContent.id.eq(audioContentComment.parent.audioContent.id)) + .and( + audioContentComment.parent.isSecret.isFalse + .or(audioContentComment.parent.member.id.eq(memberId)) + .or(audioContentComment.audioContent.member.id.eq(memberId)) + ) + .and( + audioContentComment.isSecret.isFalse + .or(audioContentComment.member.id.eq(memberId)) + .or(audioContentComment.audioContent.member.id.eq(memberId)) + .or( + audioContentComment.member.id.eq(audioContentComment.audioContent.member.id) + .and(audioContentComment.parent.member.id.eq(memberId)) + ) + ) + .and(audioContentComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) + .and(audioContentComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) + } + private fun blockedMemberIdSubQuery(memberId: Long) = JPAExpressions .select(blockMember.blockedMember.id) .from(blockMember) diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentService.kt index a9f4e2ea..05ee7e8b 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentService.kt @@ -14,6 +14,7 @@ import kr.co.vividnext.sodalive.i18n.LangContext import kr.co.vividnext.sodalive.i18n.SodaMessageSource import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.block.BlockMemberRepository +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creatorname.application.CreatorLocalizedNameService import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher @@ -21,6 +22,8 @@ import org.springframework.data.domain.Pageable import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional +import javax.persistence.EntityManager +import javax.persistence.LockModeType @Service @Transactional(readOnly = true) @@ -33,6 +36,8 @@ class AudioContentCommentService( private val messageSource: SodaMessageSource, private val langContext: LangContext, private val localizedNameService: CreatorLocalizedNameService, + private val threadLocks: CommentThreadLockPort, + private val entityManager: EntityManager, @Value("\${cloud.aws.cloud-front.host}") private val cloudFrontHost: String @@ -62,23 +67,28 @@ class AudioContentCommentService( contentId = audioContent.id!! ) - if (isSecret && !isExistsAudioContent) { + val parent = parentId?.let { + threadLocks.lockContentRoot(it)?.takeIf { root -> + root.isActive && root.audioContent?.id == audioContentId + } ?: throw SodaException(messageKey = "content.comment.error.invalid_access_retry") + } + if (parent?.isSecret == true && parent.member?.id != member.id && creator.id != member.id) { + throw SodaException(messageKey = "content.comment.error.invalid_access_retry") + } + val isCreatorReply = parent != null && member.id == creator.id + val effectiveSecret = parent?.isSecret == true || (isSecret && !isCreatorReply) + if (effectiveSecret && !isCreatorReply && !isExistsAudioContent) { throw SodaException(messageKey = "content.comment.error.secret_requires_purchase") } - val audioContentComment = AudioContentComment(comment = comment, languageCode = languageCode, isSecret = isSecret) + val audioContentComment = AudioContentComment( + comment = comment, + languageCode = languageCode, + isSecret = effectiveSecret + ) audioContentComment.audioContent = audioContent audioContentComment.member = member - - val parent = if (parentId != null) { - repository.findByIdOrNull(id = parentId) - } else { - null - } - - if (parent != null) { - audioContentComment.parent = parent - } + audioContentComment.parent = parent val savedContentComment = repository.save(audioContentComment) @@ -125,6 +135,14 @@ class AudioContentCommentService( fun modifyComment(request: ModifyCommentRequest, member: Member) { val audioContentComment = repository.findByIdOrNull(request.commentId) ?: throw SodaException(messageKey = "content.comment.error.invalid_access_retry") + val root = threadLocks.lockContentRoot(audioContentComment.parent?.id ?: request.commentId) + ?: throw SodaException(messageKey = "content.comment.error.invalid_access_retry") + if (audioContentComment.id != root.id) { + entityManager.refresh(audioContentComment, LockModeType.PESSIMISTIC_WRITE) + if (!root.isActive || audioContentComment.audioContent?.id != root.audioContent?.id) { + throw SodaException(messageKey = "content.comment.error.invalid_access_retry") + } + } if (audioContentComment.member!!.id!! == member.id!!) { if (request.comment != null) { diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerQueryRepository.kt index a91f8c37..0968a9df 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerQueryRepository.kt @@ -583,6 +583,7 @@ class ExplorerQueryRepository( languageCode = it.languageCode, date = date.format(cheersDateFormatter), replyList = it.children.asSequence() + .filter { cheers -> cheers.isActive && cheers.creator?.id == creatorId } .filterNot { cheers -> cheers.member?.id != null && blockedMemberIdSet.contains(cheers.member!!.id!!) } @@ -772,13 +773,6 @@ class ExplorerQueryRepository( .toSet() } - fun getCreatorCheers(cheersId: Long): CreatorCheers? { - return queryFactory - .selectFrom(creatorCheers) - .where(creatorCheers.id.eq(cheersId)) - .fetchFirst() - } - fun getCheers(cheersId: Long): CreatorCheers? { return queryFactory .selectFrom(creatorCheers) diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerService.kt index 63f93ec9..54e6d0d3 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerService.kt @@ -32,6 +32,7 @@ import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.MemberService import kr.co.vividnext.sodalive.member.contentpreference.MemberContentPreferenceService import kr.co.vividnext.sodalive.v2.api.creator.channel.fantalk.dto.CreatorChannelFanTalkResponse +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creatorname.application.CreatorLocalizedNameService import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher @@ -44,6 +45,8 @@ import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.time.temporal.TemporalAdjusters +import javax.persistence.EntityManager +import javax.persistence.LockModeType import kotlin.random.Random @Service @@ -67,6 +70,8 @@ class ExplorerService( private val messageSource: SodaMessageSource, private val langContext: LangContext, private val localizedNameService: CreatorLocalizedNameService, + private val threadLocks: CommentThreadLockPort, + private val entityManager: EntityManager, @Value("\${cloud.aws.cloud-front.host}") private val cloudFrontHost: String @@ -601,15 +606,12 @@ class ExplorerService( cheers.member = member cheers.creator = creator - val parent = if (request.parentId != null) { - queryRepository.getCreatorCheers(request.parentId) - } else { - null - } - - if (parent != null) { - cheers.parent = parent + val parent = request.parentId?.let { + threadLocks.lockFanTalkRoot(it)?.takeIf { root -> + root.isActive && root.creator?.id == request.creatorId + } ?: throw SodaException(messageKey = "common.error.invalid_request") } + cheers.parent = parent val savedCheers = cheersRepository.save(cheers) @@ -650,6 +652,14 @@ class ExplorerService( fun modifyCheers(request: PutWriteCheersRequest, member: Member): CreatorChannelFanTalkResponse { val cheers = queryRepository.getCheers(request.cheersId) ?: throw SodaException(messageKey = "common.error.invalid_request") + val root = threadLocks.lockFanTalkRoot(cheers.parent?.id ?: request.cheersId) + ?: throw SodaException(messageKey = "common.error.invalid_request") + if (cheers.id != root.id) { + entityManager.refresh(cheers, LockModeType.PESSIMISTIC_WRITE) + if (!root.isActive || cheers.creator?.id != root.creator?.id) { + throw SodaException(messageKey = "common.error.invalid_request") + } + } val isWriter = cheers.member!!.id!! == member.id!! val isCreator = cheers.creator!!.id!! == member.id!! diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityService.kt index ada466e7..19da655d 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityService.kt @@ -27,6 +27,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.block.BlockMemberRepository import kr.co.vividnext.sodalive.utils.generateFileName import kr.co.vividnext.sodalive.utils.validateImage +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService import kr.co.vividnext.sodalive.v2.home.following.application.HomeFollowingNewsPublishService import org.slf4j.LoggerFactory @@ -63,6 +64,7 @@ class CreatorCommunityService( private val homeFollowingNewsPublishService: HomeFollowingNewsPublishService, private val creatorCommunityTranslationService: CreatorCommunityTranslationService, private val entityManager: EntityManager, + private val threadLocks: CommentThreadLockPort, @Value("\${cloud.aws.s3.bucket}") private val imageBucket: String, @@ -499,6 +501,10 @@ class CreatorCommunityService( ) { val post = repository.findByIdAndActive(postId = postId, isAdult = isAdult) ?: throw SodaException(messageKey = "creator.community.invalid_request_retry") + entityManager.refresh(post, LockModeType.PESSIMISTIC_WRITE) + if (!post.isActive || (!isAdult && post.isAdult)) { + throw SodaException(messageKey = "creator.community.invalid_request_retry") + } val creatorId = post.member!!.id!! @@ -508,23 +514,28 @@ class CreatorCommunityService( val isExistOrdered = useCanRepository.isExistCommunityPostOrdered(postId = postId, memberId = member.id!!) - if (isSecret && !isExistOrdered) { + val parent = parentId?.let { + val candidate = commentRepository.findByIdOrNull(it) + ?: throw SodaException(messageKey = "creator.community.invalid_access_retry") + if (candidate.creatorCommunity?.id != postId) { + throw SodaException(messageKey = "creator.community.invalid_access_retry") + } + threadLocks.lockCommunityRoot(it)?.takeIf { root -> root.isActive } + ?: throw SodaException(messageKey = "creator.community.invalid_access_retry") + } + if (parent?.isSecret == true && parent.member?.id != member.id && creatorId != member.id) { + throw SodaException(messageKey = "creator.community.invalid_access_retry") + } + val isCreatorReply = parent != null && member.id == creatorId + val effectiveSecret = parent?.isSecret == true || (isSecret && !isCreatorReply) + if (effectiveSecret && !isCreatorReply && !isExistOrdered) { throw SodaException(messageKey = "creator.community.secret_comment_purchase_required") } - val postComment = CreatorCommunityComment(comment = comment, isSecret = isSecret) + val postComment = CreatorCommunityComment(comment = comment, isSecret = effectiveSecret) postComment.creatorCommunity = post postComment.member = member - - val parent = if (parentId != null) { - commentRepository.findByIdOrNull(id = parentId) - } else { - null - } - - if (parent != null) { - postComment.parent = parent - } + postComment.parent = parent commentRepository.save(postComment) @@ -550,6 +561,14 @@ class CreatorCommunityService( fun modifyCommunityPostComment(request: ModifyCommunityPostCommentRequest, member: Member) { val postComment = commentRepository.findByIdOrNull(id = request.commentId) ?: throw SodaException(messageKey = "creator.community.invalid_access_retry") + val root = threadLocks.lockCommunityRoot(postComment.parent?.id ?: request.commentId) + ?: throw SodaException(messageKey = "creator.community.invalid_access_retry") + if (postComment.id != root.id) { + entityManager.refresh(postComment, LockModeType.PESSIMISTIC_WRITE) + if (!root.isActive || postComment.creatorCommunity?.id != root.creatorCommunity?.id) { + throw SodaException(messageKey = "creator.community.invalid_access_retry") + } + } if (request.comment != null && postComment.member!!.id!! == member.id!!) { postComment.comment = request.comment diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/comment/CreatorCommunityCommentRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/comment/CreatorCommunityCommentRepository.kt index 4d56d68e..05bd20c2 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/comment/CreatorCommunityCommentRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/comment/CreatorCommunityCommentRepository.kt @@ -1,5 +1,6 @@ package kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment +import com.querydsl.core.types.dsl.BooleanExpression import com.querydsl.core.types.dsl.Expressions import com.querydsl.jpa.JPAExpressions import com.querydsl.jpa.impl.JPAQueryFactory @@ -85,7 +86,8 @@ class CreatorCommunityCommentQueryRepositoryImpl( creatorCommunityComment.id, creatorCommunityComment.member.id, creatorCommunityComment.member.nickname, - creatorCommunityComment.member.profileImage.prepend("/").prepend(imageHost), + creatorCommunityComment.member.profileImage.coalesce("profile/default-profile.png") + .prepend("/").prepend(imageHost), creatorCommunityComment.comment, creatorCommunityComment.isSecret, formattedDate, @@ -109,13 +111,7 @@ class CreatorCommunityCommentQueryRepositoryImpl( override fun commentReplyCountByCommentId(commentId: Long, memberId: Long): Int { return queryFactory.select(creatorCommunityComment.id) .from(creatorCommunityComment) - .where( - creatorCommunityComment.isActive.isTrue - .and(creatorCommunityComment.parent.isNotNull) - .and(creatorCommunityComment.parent.id.eq(commentId)) - .and(creatorCommunityComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) - .and(creatorCommunityComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) - ) + .where(visibleReplyCondition(commentId, memberId)) .fetch() .size } @@ -170,7 +166,8 @@ class CreatorCommunityCommentQueryRepositoryImpl( creatorCommunityComment.id, creatorCommunityComment.member.id, creatorCommunityComment.member.nickname, - creatorCommunityComment.member.profileImage.prepend("/").prepend(imageHost), + creatorCommunityComment.member.profileImage.coalesce("profile/default-profile.png") + .prepend("/").prepend(imageHost), creatorCommunityComment.comment, creatorCommunityComment.isSecret, formattedDate, @@ -178,13 +175,7 @@ class CreatorCommunityCommentQueryRepositoryImpl( ) ) .from(creatorCommunityComment) - .where( - creatorCommunityComment.isActive.isTrue - .and(creatorCommunityComment.parent.isNotNull) - .and(creatorCommunityComment.parent.id.eq(commentId)) - .and(creatorCommunityComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) - .and(creatorCommunityComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) - ) + .where(visibleReplyCondition(commentId, memberId)) .offset(offset) .limit(limit) .orderBy(creatorCommunityComment.createdAt.desc()) @@ -194,6 +185,30 @@ class CreatorCommunityCommentQueryRepositoryImpl( } } + private fun visibleReplyCondition(commentId: Long, memberId: Long): BooleanExpression { + return creatorCommunityComment.parent.id.eq(commentId) + .and(creatorCommunityComment.isActive.isTrue) + .and(creatorCommunityComment.parent.isActive.isTrue) + .and(creatorCommunityComment.parent.parent.isNull) + .and(creatorCommunityComment.creatorCommunity.id.eq(creatorCommunityComment.parent.creatorCommunity.id)) + .and( + creatorCommunityComment.parent.isSecret.isFalse + .or(creatorCommunityComment.parent.member.id.eq(memberId)) + .or(creatorCommunityComment.creatorCommunity.member.id.eq(memberId)) + ) + .and( + creatorCommunityComment.isSecret.isFalse + .or(creatorCommunityComment.member.id.eq(memberId)) + .or(creatorCommunityComment.creatorCommunity.member.id.eq(memberId)) + .or( + creatorCommunityComment.member.id.eq(creatorCommunityComment.creatorCommunity.member.id) + .and(creatorCommunityComment.parent.member.id.eq(memberId)) + ) + ) + .and(creatorCommunityComment.member.id.notIn(blockedMemberIdSubQuery(memberId))) + .and(creatorCommunityComment.member.id.notIn(blockingMemberIdSubQuery(memberId))) + } + private fun blockedMemberIdSubQuery(memberId: Long) = JPAExpressions .select(blockMember.blockedMember.id) .from(blockMember) diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/AiCharacterAdminFanTalkFacade.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/AiCharacterAdminFanTalkFacade.kt index ffb2fe74..8e3cbfda 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/AiCharacterAdminFanTalkFacade.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/AiCharacterAdminFanTalkFacade.kt @@ -15,6 +15,7 @@ import kr.co.vividnext.sodalive.v2.api.admin.aicharacter.error.AiCharacterAdminA import kr.co.vividnext.sodalive.v2.api.creator.channel.fantalk.dto.CreatorChannelFanTalkReplyResponse import kr.co.vividnext.sodalive.v2.api.creator.channel.fantalk.dto.CreatorChannelFanTalkResponse import kr.co.vividnext.sodalive.v2.api.creator.channel.fantalk.dto.CreatorChannelFanTalkTabResponse +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.common.domain.toCdnUrl import kr.co.vividnext.sodalive.v2.creator.channel.fantalk.domain.CreatorChannelFanTalkQueryPolicy import org.springframework.beans.factory.annotation.Value @@ -22,6 +23,8 @@ import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional +import javax.persistence.EntityManager +import javax.persistence.LockModeType @Service class AiCharacterAdminFanTalkFacade( @@ -31,6 +34,8 @@ class AiCharacterAdminFanTalkFacade( private val creatorCheersRepository: CreatorCheersRepository, private val queryPolicy: CreatorChannelFanTalkQueryPolicy, private val applicationEventPublisher: ApplicationEventPublisher, + private val threadLocks: CommentThreadLockPort, + private val entityManager: EntityManager, @Value("\${cloud.aws.cloud-front.host}") private val cloudFrontHost: String ) { @Transactional(readOnly = true) @@ -75,6 +80,8 @@ class AiCharacterAdminFanTalkFacade( val creator = target.creatorMember val creatorMemberId = creator.id ?: throw invalidRequest() val parent = repository.findActiveRoot(creatorMemberId, fanTalkId) ?: throw invalidRequest() + threadLocks.lockFanTalkRoot(fanTalkId) ?: throw invalidRequest() + if (!parent.isActive || parent.creator?.id != creatorMemberId) throw invalidRequest() val savedReply = creatorCheersRepository.save( CreatorCheers(cheers = request.content, languageCode = null).apply { member = creator @@ -107,6 +114,8 @@ class AiCharacterAdminFanTalkFacade( val target = resolveActiveTarget(characterId) val creatorMemberId = target.creatorMember.id ?: throw invalidRequest() val fanRoot = repository.findFanRoot(creatorMemberId, fanTalkId) ?: throw invalidRequest() + threadLocks.lockFanTalkRoot(fanTalkId) ?: throw invalidRequest() + if (fanRoot.creator?.id != creatorMemberId || fanRoot.member?.id == creatorMemberId) throw invalidRequest() fanRoot.isActive = false } @@ -121,7 +130,10 @@ class AiCharacterAdminFanTalkFacade( val request = readRequest(requestString, AiCharacterAdminFanTalkReplyUpdateRequest::class.java) val target = resolveActiveTarget(characterId) val creatorMemberId = target.creatorMember.id ?: throw invalidRequest() + val root = threadLocks.lockFanTalkRoot(fanTalkId) ?: throw invalidRequest() + if (!root.isActive || root.creator?.id != creatorMemberId) throw invalidRequest() val reply = repository.findUpdatableReply(creatorMemberId, fanTalkId, replyId) ?: throw invalidRequest() + entityManager.refresh(reply, LockModeType.PESSIMISTIC_WRITE) request.content?.let { reply.cheers = it } request.isActive?.let { reply.isActive = it } diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/adapter/out/persistence/DefaultCommentThreadLockRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/adapter/out/persistence/DefaultCommentThreadLockRepository.kt new file mode 100644 index 00000000..4447588f --- /dev/null +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/adapter/out/persistence/DefaultCommentThreadLockRepository.kt @@ -0,0 +1,43 @@ +package kr.co.vividnext.sodalive.v2.commentthread.adapter.out.persistence + +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort +import org.springframework.stereotype.Repository +import org.springframework.transaction.annotation.Propagation +import org.springframework.transaction.annotation.Transactional +import javax.persistence.EntityManager +import javax.persistence.LockModeType + +@Repository +@Transactional(propagation = Propagation.MANDATORY) +class DefaultCommentThreadLockRepository(private val entityManager: EntityManager) : CommentThreadLockPort { + override fun lockContentRoot(rootId: Long): AudioContentComment? { + val root = entityManager.find(AudioContentComment::class.java, rootId, LockModeType.PESSIMISTIC_WRITE) ?: return null + if (root.parent != null) return null + entityManager.refresh(root, LockModeType.PESSIMISTIC_WRITE) + return root + } + + override fun lockCommunityRoot(rootId: Long): CreatorCommunityComment? { + val root = entityManager.find(CreatorCommunityComment::class.java, rootId) ?: return null + if (root.parent != null) return null + val post = entityManager.find( + CreatorCommunity::class.java, + root.creatorCommunity!!.id, + LockModeType.PESSIMISTIC_WRITE + ) + entityManager.refresh(post, LockModeType.PESSIMISTIC_WRITE) + entityManager.refresh(root, LockModeType.PESSIMISTIC_WRITE) + return root + } + + override fun lockFanTalkRoot(rootId: Long): CreatorCheers? { + val root = entityManager.find(CreatorCheers::class.java, rootId, LockModeType.PESSIMISTIC_WRITE) ?: return null + if (root.parent != null) return null + entityManager.refresh(root, LockModeType.PESSIMISTIC_WRITE) + return root + } +} diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/port/out/CommentThreadLockPort.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/port/out/CommentThreadLockPort.kt new file mode 100644 index 00000000..327cbb23 --- /dev/null +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/commentthread/port/out/CommentThreadLockPort.kt @@ -0,0 +1,12 @@ +package kr.co.vividnext.sodalive.v2.commentthread.port.out + +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment + +/** Requires a write transaction; returns refreshed roots including inactive rows, or null for missing/non-root IDs. */ +interface CommentThreadLockPort { + fun lockContentRoot(rootId: Long): AudioContentComment? + fun lockCommunityRoot(rootId: Long): CreatorCommunityComment? + fun lockFanTalkRoot(rootId: Long): CreatorCheers? +} diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/community/adapter/out/persistence/DefaultCreatorChannelCommunityQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/community/adapter/out/persistence/DefaultCreatorChannelCommunityQueryRepository.kt index eff7f526..940ea639 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/community/adapter/out/persistence/DefaultCreatorChannelCommunityQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/community/adapter/out/persistence/DefaultCreatorChannelCommunityQueryRepository.kt @@ -523,9 +523,23 @@ class DefaultCreatorChannelCommunityQueryRepository( } private fun visibleSecretReplyCondition(viewerId: Long): BooleanExpression { - return creatorCommunityComment.isSecret.isFalse - .or(creatorCommunityComment.creatorCommunity.member.id.eq(viewerId)) - .or(creatorCommunityComment.member.id.eq(viewerId)) + return creatorCommunityComment.parent.isActive.isTrue + .and(creatorCommunityComment.parent.parent.isNull) + .and(creatorCommunityComment.creatorCommunity.id.eq(creatorCommunityComment.parent.creatorCommunity.id)) + .and( + creatorCommunityComment.parent.isSecret.isFalse + .or(creatorCommunityComment.creatorCommunity.member.id.eq(viewerId)) + .or(creatorCommunityComment.parent.member.id.eq(viewerId)) + ) + .and( + creatorCommunityComment.isSecret.isFalse + .or(creatorCommunityComment.member.id.eq(viewerId)) + .or(creatorCommunityComment.creatorCommunity.member.id.eq(viewerId)) + .or( + creatorCommunityComment.member.id.eq(creatorCommunityComment.creatorCommunity.member.id) + .and(creatorCommunityComment.parent.member.id.eq(viewerId)) + ) + ) } private fun notBlockedCommentWriterCondition(viewerId: Long): BooleanExpression { diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/fantalk/adapter/out/persistence/DefaultCreatorChannelFanTalkQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/fantalk/adapter/out/persistence/DefaultCreatorChannelFanTalkQueryRepository.kt index dac6b022..a8241ade 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/fantalk/adapter/out/persistence/DefaultCreatorChannelFanTalkQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/creator/channel/fantalk/adapter/out/persistence/DefaultCreatorChannelFanTalkQueryRepository.kt @@ -119,6 +119,9 @@ class DefaultCreatorChannelFanTalkQueryRepository( creatorCheers.creator.id.eq(creatorId), creatorCheers.member.id.eq(creatorId), creatorCheers.isActive.isTrue, + creatorCheers.parent.isActive.isTrue, + creatorCheers.parent.parent.isNull, + creatorCheers.parent.creator.id.eq(creatorId), creatorCheers.parent.id.`in`(parentFanTalkIds) ) .orderBy(creatorCheers.createdAt.asc(), creatorCheers.id.asc()) diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/content/CreatorCommunityLanguageDetectTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/content/CreatorCommunityLanguageDetectTest.kt index eb18410e..2388dd87 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/content/CreatorCommunityLanguageDetectTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/content/CreatorCommunityLanguageDetectTest.kt @@ -34,6 +34,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRepository import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.block.BlockMemberRepository +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.adapter.out.persistence.CreatorCommunityTranslation import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.adapter.out.persistence.CreatorCommunityTranslationRepository import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService @@ -728,6 +729,7 @@ class CreatorCommunityLanguageDetectTest @Autowired constructor( homeFollowingNewsPublishService = Mockito.mock(HomeFollowingNewsPublishService::class.java), creatorCommunityTranslationService = creatorCommunityTranslationService, entityManager = entityManager, + threadLocks = Mockito.mock(CommentThreadLockPort::class.java), imageBucket = "test-image-bucket", contentBucket = "test-content-bucket", imageHost = "https://test.cloudfront.net" diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentNameMetadataTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentNameMetadataTest.kt index 000f9644..ede5a756 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentNameMetadataTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/content/comment/AudioContentCommentNameMetadataTest.kt @@ -12,6 +12,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.block.BlockMemberRepository import kr.co.vividnext.sodalive.support.LegacyCreatorNameTestConfiguration +import kr.co.vividnext.sodalive.v2.commentthread.adapter.out.persistence.DefaultCommentThreadLockRepository import kr.co.vividnext.sodalive.v2.creatorname.application.CreatorLocalizedNameService import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals @@ -73,6 +74,8 @@ class AudioContentCommentNameMetadataTest @Autowired constructor( SodaMessageSource(), LangContext(), localizedNameService, + DefaultCommentThreadLockRepository(entityManager), + entityManager, "https://cdn.test" ) diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerServiceTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerServiceTest.kt index b3143abb..75db7634 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerServiceTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/ExplorerServiceTest.kt @@ -18,6 +18,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.MemberService import kr.co.vividnext.sodalive.member.contentpreference.MemberContentPreferenceService +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creatorname.application.CreatorLocalizedNameService import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows @@ -26,8 +27,11 @@ import org.junit.jupiter.api.Test import org.mockito.Mockito import org.springframework.context.ApplicationEventPublisher import java.time.LocalDateTime +import javax.persistence.EntityManager class ExplorerServiceTest { + private val threadLocks = Mockito.mock(CommentThreadLockPort::class.java) + @Test @DisplayName("팬톡 수정은 작성자나 크리에이터가 아닌 요청자에게 데이터를 반환하지 않는다") fun shouldRejectModifyCheersForNonWriterAndNonCreator() { @@ -39,6 +43,7 @@ class ExplorerServiceTest { ) val requester = createMember(id = 30L, nickname = "requester") Mockito.doReturn(cheers).`when`(queryRepository).getCheers(101L) + Mockito.doReturn(cheers).`when`(threadLocks).lockFanTalkRoot(101L) assertThrows(SodaException::class.java) { service.modifyCheers(PutWriteCheersRequest(cheersId = 101L, content = "stolen"), requester) @@ -54,6 +59,7 @@ class ExplorerServiceTest { val writer = createMember(id = 10L, nickname = "deleted_writer", role = MemberRole.CREATOR) val cheers = createCheers(writer, createMember(id = 20L, nickname = "creator", role = MemberRole.CREATOR)) Mockito.doReturn(cheers).`when`(queryRepository).getCheers(101L) + Mockito.doReturn(cheers).`when`(threadLocks).lockFanTalkRoot(101L) Mockito.`when`(localizedNameService.findLocalizedNames(listOf(10L), Lang.JA)).thenReturn(mapOf(10L to "alias")) val response = service.modifyCheers(PutWriteCheersRequest(cheersId = 101L, content = "modified"), writer) @@ -83,6 +89,8 @@ class ExplorerServiceTest { messageSource = Mockito.mock(SodaMessageSource::class.java), langContext = LangContext().apply { setLang(Lang.JA) }, localizedNameService = localizedNameService, + threadLocks = threadLocks, + entityManager = Mockito.mock(EntityManager::class.java), cloudFrontHost = "https://cdn.test" ) } diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityServiceTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityServiceTest.kt index 0487c7cd..70880c3c 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityServiceTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityServiceTest.kt @@ -23,6 +23,7 @@ import kr.co.vividnext.sodalive.i18n.SodaMessageSource import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.block.BlockMemberRepository +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityDisplayContent import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService import kr.co.vividnext.sodalive.v2.home.following.application.HomeFollowingNewsPublishService @@ -91,6 +92,7 @@ class CreatorCommunityServiceTest { homeFollowingNewsPublishService = homeFollowingNewsPublishService, creatorCommunityTranslationService = creatorCommunityTranslationService, entityManager = entityManager, + threadLocks = Mockito.mock(CommentThreadLockPort::class.java), imageBucket = "image-bucket", contentBucket = "content-bucket", imageHost = "https://cdn.test" diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityTranslationEndToEndTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityTranslationEndToEndTest.kt index 7e56d58b..740b3cab 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityTranslationEndToEndTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/explorer/profile/creatorCommunity/CreatorCommunityTranslationEndToEndTest.kt @@ -25,6 +25,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRepository import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.block.BlockMemberRepository +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.adapter.out.persistence.CreatorCommunityTranslation import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.adapter.out.persistence.CreatorCommunityTranslationRepository import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService @@ -205,6 +206,7 @@ class CreatorCommunityTranslationEndToEndTest @Autowired constructor( homeFollowingNewsPublishService = Mockito.mock(HomeFollowingNewsPublishService::class.java), creatorCommunityTranslationService = translationService, entityManager = entityManager, + threadLocks = Mockito.mock(CommentThreadLockPort::class.java), imageBucket = "test-image-bucket", contentBucket = "test-content-bucket", imageHost = "https://cdn.test" diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/community/LegacyCommunityPostCharacterizationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/community/LegacyCommunityPostCharacterizationTest.kt index ecc42b79..d354defa 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/community/LegacyCommunityPostCharacterizationTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/community/LegacyCommunityPostCharacterizationTest.kt @@ -23,6 +23,7 @@ import kr.co.vividnext.sodalive.i18n.SodaMessageSource import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.block.BlockMemberRepository +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creator.channel.community.translation.application.CreatorCommunityTranslationService import kr.co.vividnext.sodalive.v2.home.following.application.HomeFollowingNewsPublishService import org.junit.jupiter.api.Assertions.assertEquals @@ -69,6 +70,7 @@ class LegacyCommunityPostCharacterizationTest { homeFollowingNewsPublishService = homeFollowingNewsPublishService, creatorCommunityTranslationService = Mockito.mock(CreatorCommunityTranslationService::class.java), entityManager = Mockito.mock(EntityManager::class.java), + threadLocks = Mockito.mock(CommentThreadLockPort::class.java), imageBucket = "image-bucket", contentBucket = "content-bucket", imageHost = "https://cdn.test" diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/LegacyFanTalkReplyCharacterizationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/LegacyFanTalkReplyCharacterizationTest.kt index 9f146e9a..a49bd725 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/LegacyFanTalkReplyCharacterizationTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/admin/aicharacter/fantalk/LegacyFanTalkReplyCharacterizationTest.kt @@ -22,6 +22,7 @@ import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.member.MemberService import kr.co.vividnext.sodalive.member.contentpreference.MemberContentPreferenceService +import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort import kr.co.vividnext.sodalive.v2.creatorname.application.CreatorLocalizedNameService import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse @@ -36,6 +37,7 @@ import org.mockito.ArgumentCaptor import org.mockito.Mockito import org.springframework.context.ApplicationEventPublisher import java.time.LocalDateTime +import javax.persistence.EntityManager class LegacyFanTalkReplyCharacterizationTest { private lateinit var memberService: MemberService @@ -44,6 +46,7 @@ class LegacyFanTalkReplyCharacterizationTest { private lateinit var applicationEventPublisher: ApplicationEventPublisher private lateinit var messageSource: SodaMessageSource private lateinit var localizedNameService: CreatorLocalizedNameService + private lateinit var threadLocks: CommentThreadLockPort private lateinit var service: ExplorerService @BeforeEach @@ -54,6 +57,7 @@ class LegacyFanTalkReplyCharacterizationTest { applicationEventPublisher = Mockito.mock(ApplicationEventPublisher::class.java) messageSource = Mockito.mock(SodaMessageSource::class.java) localizedNameService = Mockito.mock(CreatorLocalizedNameService::class.java) + threadLocks = Mockito.mock(CommentThreadLockPort::class.java) service = ExplorerService( memberService = memberService, memberContentPreferenceService = Mockito.mock(MemberContentPreferenceService::class.java), @@ -70,6 +74,8 @@ class LegacyFanTalkReplyCharacterizationTest { messageSource = messageSource, langContext = LangContext().apply { setLang(Lang.KO) }, localizedNameService = localizedNameService, + threadLocks = threadLocks, + entityManager = Mockito.mock(EntityManager::class.java), cloudFrontHost = "https://cdn.test" ) } @@ -82,7 +88,7 @@ class LegacyFanTalkReplyCharacterizationTest { val root = createCheers(id = 100L, content = "root fan talk", member = writer, creator = creator) val createdAt = LocalDateTime.of(2026, 7, 28, 11, 30) Mockito.`when`(queryRepository.getMember(creator.id!!)).thenReturn(creator) - Mockito.`when`(queryRepository.getCreatorCheers(root.id!!)).thenReturn(root) + Mockito.`when`(threadLocks.lockFanTalkRoot(root.id!!)).thenReturn(root) stubSave(id = 101L, createdAt = createdAt) val response = service.writeCheers( @@ -119,33 +125,31 @@ class LegacyFanTalkReplyCharacterizationTest { } @Test - @DisplayName("기존 FanTalk 작성은 존재하지 않는 parent를 root 글처럼 저장하고 언어 코드가 있으면 감지 이벤트를 발행하지 않는다") - fun shouldCreateRootFanTalkWhenRequestedParentDoesNotExist() { + @DisplayName("기존 FanTalk 작성은 존재하지 않는 parent를 거부하고 원댓글을 대신 저장하지 않는다") + fun shouldRejectMissingParentWithoutCreatingRootFanTalk() { val creator = createMember(30L, "root-creator", MemberRole.CREATOR) val writer = createMember(40L, "root-writer") Mockito.`when`(queryRepository.getMember(creator.id!!)).thenReturn(creator) - Mockito.`when`(queryRepository.getCreatorCheers(999L)).thenReturn(null) - stubSave(id = 102L, createdAt = LocalDateTime.of(2026, 7, 28, 11, 31)) - service.writeCheers( - PostWriteCheersRequest( - parentId = 999L, - creatorId = creator.id!!, - content = "new root fan talk", - languageCode = "ko" - ), - writer - ) + val exception = assertThrows(SodaException::class.java) { + service.writeCheers( + PostWriteCheersRequest( + parentId = 999L, + creatorId = creator.id!!, + content = "new root fan talk", + languageCode = "ko" + ), + writer + ) + } - val cheersCaptor = ArgumentCaptor.forClass(CreatorCheers::class.java) - Mockito.verify(cheersRepository).save(cheersCaptor.capture()) - assertNull(cheersCaptor.value.parent) - Mockito.verifyNoInteractions(applicationEventPublisher) + assertEquals("common.error.invalid_request", exception.messageKey) + Mockito.verifyNoInteractions(cheersRepository, applicationEventPublisher) } @Test - @DisplayName("기존 FanTalk 작성은 조회된 비활성 nested parent에도 답변을 연결한다") - fun shouldAllowReplyToInactiveNestedParentReturnedByQueryRepository() { + @DisplayName("기존 FanTalk 작성은 비활성 nested parent에 답글을 저장하지 않는다") + fun shouldRejectInactiveNestedParentWithoutCreatingReply() { val creator = createMember(50L, "nested-creator", MemberRole.CREATOR) val writer = createMember(60L, "nested-writer") val root = createCheers(id = 200L, content = "root", member = writer, creator = creator) @@ -154,22 +158,21 @@ class LegacyFanTalkReplyCharacterizationTest { isActive = false } Mockito.`when`(queryRepository.getMember(creator.id!!)).thenReturn(creator) - Mockito.`when`(queryRepository.getCreatorCheers(nested.id!!)).thenReturn(nested) - stubSave(id = 202L, createdAt = LocalDateTime.of(2026, 7, 28, 11, 32)) - service.writeCheers( - PostWriteCheersRequest( - parentId = nested.id, - creatorId = creator.id!!, - content = "nested reply", - languageCode = "ko" - ), - writer - ) + val exception = assertThrows(SodaException::class.java) { + service.writeCheers( + PostWriteCheersRequest( + parentId = nested.id, + creatorId = creator.id!!, + content = "nested reply", + languageCode = "ko" + ), + writer + ) + } - val cheersCaptor = ArgumentCaptor.forClass(CreatorCheers::class.java) - Mockito.verify(cheersRepository).save(cheersCaptor.capture()) - assertSame(nested, cheersCaptor.value.parent) + assertEquals("common.error.invalid_request", exception.messageKey) + Mockito.verifyNoInteractions(cheersRepository, applicationEventPublisher) assertSame(root, nested.parent) assertFalse(nested.isActive) } @@ -180,7 +183,7 @@ class LegacyFanTalkReplyCharacterizationTest { val creator = createMember(70L, "duplicate-creator", MemberRole.CREATOR) val root = createCheers(id = 300L, content = "root", member = creator, creator = creator) Mockito.`when`(queryRepository.getMember(creator.id!!)).thenReturn(creator) - Mockito.`when`(queryRepository.getCreatorCheers(root.id!!)).thenReturn(root) + Mockito.`when`(threadLocks.lockFanTalkRoot(root.id!!)).thenReturn(root) Mockito.`when`(localizedNameService.findLocalizedNames(listOf(creator.id!!), Lang.KO)) .thenReturn(mapOf(creator.id!! to "Korean creator alias")) var nextId = 301L diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadConcurrencyIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadConcurrencyIntegrationTest.kt new file mode 100644 index 00000000..f9dbc8f4 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadConcurrencyIntegrationTest.kt @@ -0,0 +1,93 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.common.SodaException +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import org.springframework.transaction.support.TransactionTemplate +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +class CommentThreadConcurrencyIntegrationTest : CommentThreadIntegrationSupport() { + @ParameterizedTest + @EnumSource(ThreadKind::class) + @DisplayName("부모를 미리 읽은 별도 트랜잭션도 삭제 커밋 후 공유 잠금에서 부모 상태를 새로 읽고 답글을 거부한다") + fun shouldRejectReplyAfterConcurrentDeletionDespiteManagedActiveParent(kind: ThreadKind) { + val transactions = TransactionTemplate(transactionManager) + val rootId = transactions.execute { root(kind) }!! + val snapshotLoaded = CountDownLatch(1) + val deletionCommitted = CountDownLatch(1) + val executor = Executors.newSingleThreadExecutor() + val writer = executor.submit { + try { + transactions.executeWithoutResult { + loadRoot(kind, rootId) + snapshotLoaded.countDown() + check(deletionCommitted.await(10, TimeUnit.SECONDS)) { "Parent deletion did not complete" } + writeReply(kind, rootId) + } + null + } catch (exception: SodaException) { + exception + } + } + + try { + assertTrue(snapshotLoaded.await(10, TimeUnit.SECONDS), "Writer did not load its managed parent") + + transactions.executeWithoutResult { deleteRoot(kind, rootId) } + deletionCommitted.countDown() + + assertNotNull(writer.get(15, TimeUnit.SECONDS), "A stale active parent must not permit an insert") + val replyCount = transactions.execute { + val entityName = when (kind) { + ThreadKind.CONTENT -> "AudioContentComment" + ThreadKind.COMMUNITY -> "CreatorCommunityComment" + ThreadKind.FANTALK -> "CreatorCheers" + } + entityManager.createQuery( + "select count(c) from $entityName c where c.parent.id = :rootId", + java.lang.Long::class.java + ).setParameter("rootId", rootId).singleResult.toLong() + } + assertEquals(0L, replyCount) + } finally { + deletionCommitted.countDown() + writer.cancel(true) + executor.shutdownNow() + assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS), "Writer executor did not stop") + } + } + + @AfterEach + fun removeCommittedFixtures() { + TransactionTemplate(transactionManager).executeWithoutResult { + listOf(true, false).forEach { children -> + val parentCondition = if (children) "is not null" else "is null" + entityManager.createQuery( + "delete from AudioContentComment c where c.audioContent.id = :id and c.parent $parentCondition" + ).setParameter("id", content.id).executeUpdate() + entityManager.createQuery( + "delete from CreatorCommunityComment c where c.creatorCommunity.id = :id and c.parent $parentCondition" + ).setParameter("id", post.id).executeUpdate() + entityManager.createQuery( + "delete from CreatorCheers c where c.creator.id = :id and c.parent $parentCondition" + ).setParameter("id", creator.id).executeUpdate() + } + entityManager.createQuery("delete from AudioContent c where c.id = :id") + .setParameter("id", content.id).executeUpdate() + entityManager.createQuery("delete from CreatorCommunity p where p.id = :id") + .setParameter("id", post.id).executeUpdate() + entityManager.createQuery("delete from AudioContentTheme t where t.id = :id") + .setParameter("id", theme.id).executeUpdate() + entityManager.createQuery("delete from Member m where m.id in :ids") + .setParameter("ids", listOf(creator.id, fan.id, outsider.id, replyWriter.id)).executeUpdate() + entityManager.clear() + } + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadIntegrationSupport.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadIntegrationSupport.kt new file mode 100644 index 00000000..cf991923 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadIntegrationSupport.kt @@ -0,0 +1,210 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.content.AudioContent +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.content.comment.AudioContentCommentRepository +import kr.co.vividnext.sodalive.content.comment.AudioContentCommentService +import kr.co.vividnext.sodalive.content.comment.ModifyCommentRequest +import kr.co.vividnext.sodalive.content.theme.AudioContentTheme +import kr.co.vividnext.sodalive.explorer.ExplorerQueryRepository +import kr.co.vividnext.sodalive.explorer.ExplorerService +import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers +import kr.co.vividnext.sodalive.explorer.profile.PostWriteCheersRequest +import kr.co.vividnext.sodalive.explorer.profile.PutWriteCheersRequest +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunityService +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityCommentRepository +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.ModifyCommunityPostCommentRequest +import kr.co.vividnext.sodalive.member.Member +import kr.co.vividnext.sodalive.member.MemberRole +import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer +import kr.co.vividnext.sodalive.v2.creator.channel.community.adapter.out.persistence.DefaultCreatorChannelCommunityQueryRepository +import kr.co.vividnext.sodalive.v2.creator.channel.fantalk.adapter.out.persistence.DefaultCreatorChannelFanTalkQueryRepository +import org.junit.jupiter.api.BeforeEach +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.context.ApplicationEventPublisher +import org.springframework.test.context.ContextConfiguration +import org.springframework.transaction.PlatformTransactionManager +import org.springframework.transaction.support.TransactionTemplate +import javax.persistence.EntityManager + +@SpringBootTest(properties = ["cloud.aws.cloud-front.host=https://test.cloudfront.net"]) +@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class]) +abstract class CommentThreadIntegrationSupport { + @Autowired + protected lateinit var entityManager: EntityManager + + @Autowired + protected lateinit var transactionManager: PlatformTransactionManager + + @Autowired + protected lateinit var contentService: AudioContentCommentService + + @Autowired + protected lateinit var communityService: CreatorCommunityService + + @Autowired + protected lateinit var explorerService: ExplorerService + + @Autowired + protected lateinit var contentComments: AudioContentCommentRepository + + @Autowired + protected lateinit var communityComments: CreatorCommunityCommentRepository + + @Autowired + protected lateinit var communityQuery: DefaultCreatorChannelCommunityQueryRepository + + @Autowired + protected lateinit var fanTalkQuery: DefaultCreatorChannelFanTalkQueryRepository + + @Autowired + protected lateinit var explorerQuery: ExplorerQueryRepository + + @MockBean + private lateinit var applicationEventPublisher: ApplicationEventPublisher + + protected lateinit var creator: Member + protected lateinit var fan: Member + protected lateinit var outsider: Member + protected lateinit var replyWriter: Member + protected lateinit var theme: AudioContentTheme + protected lateinit var content: AudioContent + protected lateinit var post: CreatorCommunity + + @BeforeEach + fun prepareThreadFixtures() { + TransactionTemplate(transactionManager).executeWithoutResult { + entityManager.createNativeQuery( + "CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'" + ).executeUpdate() + entityManager.createNativeQuery( + "CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'" + ).executeUpdate() + creator = member("thread-creator", MemberRole.CREATOR) + fan = member("thread-fan") + outsider = member("thread-outsider") + replyWriter = member("thread-reply-writer") + theme = AudioContentTheme(theme = "thread-theme", image = "theme.png").also(entityManager::persist) + content = saveContent() + post = savePost() + entityManager.flush() + entityManager.clear() + } + } + + protected fun saveContent(): AudioContent = AudioContent( + title = "thread-content", + detail = "detail", + languageCode = "ko", + isCommentAvailable = true + ).apply { + member = creator + theme = this@CommentThreadIntegrationSupport.theme + isActive = true + }.also(entityManager::persist) + + protected fun savePost(): CreatorCommunity = CreatorCommunity( + content = "thread-post", + price = 0, + isCommentAvailable = true, + isAdult = false + ).apply { member = creator }.also(entityManager::persist) + + protected fun contentComment( + writer: Member = fan, + secret: Boolean = false, + parent: AudioContentComment? = null + ): AudioContentComment = AudioContentComment(comment = "content reply", languageCode = "ko", isSecret = secret).apply { + member = writer + audioContent = content + this.parent = parent + }.also(entityManager::persist) + + protected fun communityComment( + writer: Member = fan, + secret: Boolean = false, + parent: CreatorCommunityComment? = null + ): CreatorCommunityComment = CreatorCommunityComment(comment = "community reply", isSecret = secret).apply { + member = writer + creatorCommunity = post + this.parent = parent + }.also(entityManager::persist) + + protected fun fanTalk(writer: Member = fan, parent: CreatorCheers? = null): CreatorCheers = CreatorCheers( + cheers = "fan talk", + languageCode = "ko" + ).apply { + member = writer + creator = this@CommentThreadIntegrationSupport.creator + this.parent = parent + }.also(entityManager::persist) + + protected fun flushAndClear() { + entityManager.flush() + entityManager.clear() + } + + protected fun deleteRoot(kind: ThreadKind, rootId: Long) { + when (kind) { + ThreadKind.CONTENT -> contentService.modifyComment(ModifyCommentRequest(rootId, isActive = false), creator) + ThreadKind.COMMUNITY -> communityService.modifyCommunityPostComment( + ModifyCommunityPostCommentRequest(rootId, comment = null, isActive = false), + creator + ) + ThreadKind.FANTALK -> explorerService.modifyCheers(PutWriteCheersRequest(rootId, isActive = false), creator) + } + } + + protected fun writeReply(kind: ThreadKind, parentId: Long) { + when (kind) { + ThreadKind.CONTENT -> contentService.registerComment( + creator, + "new reply", + content.id!!, + parentId, + false, + "ko" + ) + ThreadKind.COMMUNITY -> communityService.createCommunityPostComment( + creator, + "new reply", + post.id!!, + parentId, + false, + true + ) + ThreadKind.FANTALK -> explorerService.writeCheers( + PostWriteCheersRequest(parentId, creator.id!!, "new reply", "ko"), + creator + ) + } + } + + protected fun root(kind: ThreadKind): Long = when (kind) { + ThreadKind.CONTENT -> contentComment().id!! + ThreadKind.COMMUNITY -> communityComment().id!! + ThreadKind.FANTALK -> fanTalk().id!! + } + + protected fun loadRoot(kind: ThreadKind, id: Long) { + when (kind) { + ThreadKind.CONTENT -> entityManager.find(AudioContentComment::class.java, id) + ThreadKind.COMMUNITY -> entityManager.find(CreatorCommunityComment::class.java, id) + ThreadKind.FANTALK -> entityManager.find(CreatorCheers::class.java, id) + } + } + + enum class ThreadKind { CONTENT, COMMUNITY, FANTALK } + + private fun member(name: String, role: MemberRole = MemberRole.USER): Member = Member( + email = "$name@test.com", + password = "password", + nickname = name, + role = role, + profileImage = "$name.png" + ).also(entityManager::persist) +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadParentValidationIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadParentValidationIntegrationTest.kt new file mode 100644 index 00000000..f63d011b --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadParentValidationIntegrationTest.kt @@ -0,0 +1,111 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.common.SodaException +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment +import kr.co.vividnext.sodalive.member.Member +import kr.co.vividnext.sodalive.member.MemberRole +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.EnumSource +import org.junit.jupiter.params.provider.MethodSource +import org.springframework.transaction.annotation.Transactional +import java.util.stream.Stream + +@Transactional +class CommentThreadParentValidationIntegrationTest : CommentThreadIntegrationSupport() { + @ParameterizedTest + @MethodSource("invalidParents") + @DisplayName("기존 앱 작성은 없는 부모를 원댓글로 대체하지 않고 비활성·답글·다른 자원 부모를 insert 없이 거부한다") + fun shouldRejectInvalidParentsWithoutFallbackInsert(kind: ThreadKind, invalid: InvalidParent) { + val parentId = invalidParent(kind, invalid) + flushAndClear() + val beforeCount = countRows(kind) + + assertThrows(SodaException::class.java) { writeReply(kind, parentId) } + + assertEquals(beforeCount, countRows(kind)) + } + + @ParameterizedTest + @EnumSource(ThreadKind::class) + @DisplayName("기존 앱 쓰기는 같은 활성 부모에 여러 크리에이터 답글을 실제 저장할 수 있다") + fun shouldPersistMultipleCreatorRepliesForSameActiveRoot(kind: ThreadKind) { + val rootId = root(kind) + flushAndClear() + + writeReply(kind, rootId) + writeReply(kind, rootId) + flushAndClear() + + val count = entityManager.createQuery( + "select count(c) from ${entityName(kind)} c where c.parent.id = :rootId and c.isActive = true", + java.lang.Long::class.java + ).setParameter("rootId", rootId).singleResult.toLong() + assertEquals(2L, count) + } + + private fun invalidParent(kind: ThreadKind, invalid: InvalidParent): Long { + val rootId = root(kind) + return when (kind) { + ThreadKind.CONTENT -> { + val root = entityManager.find(AudioContentComment::class.java, rootId) + when (invalid) { + InvalidParent.INACTIVE -> root.apply { isActive = false }.id!! + InvalidParent.NESTED -> contentComment(creator, parent = root).id!! + InvalidParent.FOREIGN_RESOURCE -> root.apply { audioContent = saveContent() }.id!! + InvalidParent.MISSING -> Long.MAX_VALUE + } + } + ThreadKind.COMMUNITY -> { + val root = entityManager.find(CreatorCommunityComment::class.java, rootId) + when (invalid) { + InvalidParent.INACTIVE -> root.apply { isActive = false }.id!! + InvalidParent.NESTED -> communityComment(creator, parent = root).id!! + InvalidParent.FOREIGN_RESOURCE -> root.apply { creatorCommunity = savePost() }.id!! + InvalidParent.MISSING -> Long.MAX_VALUE + } + } + ThreadKind.FANTALK -> { + val root = entityManager.find(CreatorCheers::class.java, rootId) + when (invalid) { + InvalidParent.INACTIVE -> root.apply { isActive = false }.id!! + InvalidParent.NESTED -> fanTalk(creator, root).id!! + InvalidParent.FOREIGN_RESOURCE -> root.apply { + creator = Member( + email = "other-owner@test.com", + password = "password", + nickname = "other-owner", + role = MemberRole.CREATOR + ).also(entityManager::persist) + }.id!! + InvalidParent.MISSING -> Long.MAX_VALUE + } + } + } + } + + private fun countRows(kind: ThreadKind): Long = entityManager.createQuery( + "select count(c) from ${entityName(kind)} c", + java.lang.Long::class.java + ).singleResult.toLong() + + private fun entityName(kind: ThreadKind): String = when (kind) { + ThreadKind.CONTENT -> "AudioContentComment" + ThreadKind.COMMUNITY -> "CreatorCommunityComment" + ThreadKind.FANTALK -> "CreatorCheers" + } + + enum class InvalidParent { MISSING, INACTIVE, NESTED, FOREIGN_RESOURCE } + + companion object { + @JvmStatic + fun invalidParents(): Stream = ThreadKind.values().flatMap { kind -> + InvalidParent.values().map { Arguments.of(kind, it) } + }.stream() + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadPrivacyIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadPrivacyIntegrationTest.kt new file mode 100644 index 00000000..82b30b5e --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadPrivacyIntegrationTest.kt @@ -0,0 +1,256 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment +import kr.co.vividnext.sodalive.i18n.Lang +import kr.co.vividnext.sodalive.member.block.BlockMember +import org.junit.jupiter.api.Assertions.assertAll +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.EnumSource +import org.junit.jupiter.params.provider.MethodSource +import org.springframework.transaction.annotation.Transactional +import java.time.LocalDateTime +import java.util.stream.Stream + +@Transactional +class CommentThreadPrivacyIntegrationTest : CommentThreadIntegrationSupport() { + @ParameterizedTest + @MethodSource("visibilityCases") + @DisplayName("앱 답글 목록과 개수와 미리보기는 부모와 답글의 공개 범위 및 원댓글 팬 권한을 함께 적용한다") + fun shouldApplyThreadPrivacyToListsCountsAndPreviews(surface: Surface, visibility: Visibility, viewer: Viewer) { + val writer = when (viewer) { + Viewer.FAN, Viewer.CREATOR -> creator + Viewer.REPLY_WRITER, Viewer.OUTSIDER -> replyWriter + } + val rootId: Long + val replyId: Long + when (surface) { + Surface.CONTENT -> { + val root = contentComment(secret = visibility.parentSecret) + rootId = root.id!! + replyId = contentComment(writer, visibility.replySecret, root).id!! + } + Surface.LEGACY_COMMUNITY, Surface.V2_COMMUNITY -> { + val root = communityComment(secret = visibility.parentSecret) + rootId = root.id!! + replyId = communityComment(writer, visibility.replySecret, root).id!! + } + } + flushAndClear() + val viewerId = when (viewer) { + Viewer.FAN -> fan.id!! + Viewer.CREATOR -> creator.id!! + Viewer.REPLY_WRITER -> replyWriter.id!! + Viewer.OUTSIDER -> outsider.id!! + } + + val actual = replies(surface, rootId, viewerId) + + val expected = if (viewer in visibility.allowed) setOf(replyId) else emptySet() + assertAll( + { assertEquals(expected, actual.ids, "reply list") }, + { assertEquals(expected.size, actual.count, "reply count") }, + { assertEquals(if (surface == Surface.V2_COMMUNITY) expected else null, actual.previewIds, "V2 preview") } + ) + } + + @ParameterizedTest + @EnumSource(value = Surface::class, names = ["CONTENT", "LEGACY_COMMUNITY"]) + @DisplayName("공개 부모 작성자도 다른 일반 팬의 비밀 답글은 목록과 개수에서 볼 수 없다") + fun shouldHideAnotherFansSecretReplyFromParentFan(surface: Surface) { + val rootId = when (surface) { + Surface.CONTENT -> contentComment().let { root -> + contentComment(replyWriter, secret = true, parent = root) + root.id!! + } + Surface.LEGACY_COMMUNITY -> communityComment().let { root -> + communityComment(replyWriter, secret = true, parent = root) + root.id!! + } + Surface.V2_COMMUNITY -> error("V2 ordinary secret reply privacy has an existing repository regression") + } + flushAndClear() + + val actual = replies(surface, rootId, fan.id!!) + + assertEquals(emptySet(), actual.ids) + assertEquals(0, actual.count) + } + + @ParameterizedTest + @EnumSource(Surface::class) + @DisplayName("부모 삭제는 답글 row를 활성 상태로 보존하면서 앱 직접 답글 목록과 개수와 미리보기에서 숨긴다") + fun shouldHideActiveRepliesAfterDeletingOnlyParent(surface: Surface) { + val rootId: Long + val replyId: Long + val kind: ThreadKind + when (surface) { + Surface.CONTENT -> { + val root = contentComment() + rootId = root.id!! + replyId = contentComment(creator, parent = root).id!! + kind = ThreadKind.CONTENT + } + Surface.LEGACY_COMMUNITY, Surface.V2_COMMUNITY -> { + val root = communityComment() + rootId = root.id!! + replyId = communityComment(creator, parent = root).id!! + kind = ThreadKind.COMMUNITY + } + } + flushAndClear() + + deleteRoot(kind, rootId) + flushAndClear() + + val actual = replies(surface, rootId, creator.id!!) + assertAll( + { assertEquals(emptySet(), actual.ids) }, + { assertEquals(0, actual.count) }, + { assertEquals(if (surface == Surface.V2_COMMUNITY) emptySet() else null, actual.previewIds) }, + { + val active = when (kind) { + ThreadKind.CONTENT -> entityManager.find(AudioContentComment::class.java, replyId).isActive + ThreadKind.COMMUNITY -> entityManager.find(CreatorCommunityComment::class.java, replyId).isActive + ThreadKind.FANTALK -> error("FanTalk is tested separately") + } + assertTrue(active, "parent deletion must not cascade soft deletion") + } + ) + } + + @ParameterizedTest + @EnumSource(Surface::class) + @DisplayName("다른 콘텐츠나 게시글에 연결된 답글은 부모 ID를 직접 알아도 목록과 개수와 미리보기에서 제외한다") + fun shouldHideRepliesWithMixedResourceParents(surface: Surface) { + val rootId = when (surface) { + Surface.CONTENT -> contentComment().let { root -> + contentComment(creator, parent = root).audioContent = saveContent() + root.id!! + } + Surface.LEGACY_COMMUNITY, Surface.V2_COMMUNITY -> communityComment().let { root -> + communityComment(creator, parent = root).creatorCommunity = savePost() + root.id!! + } + } + flushAndClear() + + val actual = replies(surface, rootId, creator.id!!) + + assertAll( + { assertEquals(emptySet(), actual.ids) }, + { assertEquals(0, actual.count) }, + { assertEquals(if (surface == Surface.V2_COMMUNITY) emptySet() else null, actual.previewIds) } + ) + } + + @ParameterizedTest + @EnumSource(Surface::class) + @DisplayName("기존 앱의 공개 다중 답글을 보존하고 양방향 차단 작성자와 비활성 답글을 제외한다") + fun shouldPreserveMultiplePublicRepliesAndApplicableBlocks(surface: Surface) { + val rootId: Long + val expected: Set + val latestId: Long + when (surface) { + Surface.CONTENT -> { + val root = contentComment() + val first = contentComment(creator, parent = root) + val second = contentComment(fan, parent = root) + contentComment(replyWriter, parent = root) + contentComment(outsider, parent = root) + contentComment(creator, parent = root).isActive = false + rootId = root.id!! + expected = setOf(first.id!!, second.id!!) + latestId = second.id!! + first.createdAt = LocalDateTime.of(2026, 11, 20, 10, 0) + second.createdAt = LocalDateTime.of(2026, 11, 20, 11, 0) + } + Surface.LEGACY_COMMUNITY, Surface.V2_COMMUNITY -> { + val root = communityComment() + val first = communityComment(creator, parent = root) + val second = communityComment(fan, parent = root) + communityComment(replyWriter, parent = root) + communityComment(outsider, parent = root) + communityComment(creator, parent = root).isActive = false + rootId = root.id!! + expected = setOf(first.id!!, second.id!!) + latestId = second.id!! + first.createdAt = LocalDateTime.of(2026, 11, 20, 10, 0) + second.createdAt = LocalDateTime.of(2026, 11, 20, 11, 0) + } + } + BlockMember().apply { member = fan; blockedMember = replyWriter }.also(entityManager::persist) + BlockMember().apply { member = outsider; blockedMember = fan }.also(entityManager::persist) + flushAndClear() + + val actual = replies(surface, rootId, fan.id!!) + + assertAll( + { assertEquals(expected, actual.ids) }, + { assertEquals(2, actual.count) }, + { assertEquals(if (surface == Surface.V2_COMMUNITY) setOf(latestId) else null, actual.previewIds) } + ) + } + + private fun replies(surface: Surface, rootId: Long, viewerId: Long): Replies = when (surface) { + Surface.CONTENT -> { + val items = contentComments.getAudioContentCommentReplyList( + "https://test.cloudfront.net", + rootId, + viewerId, + "UTC", + 0, + 10 + ) + val count = contentComments.commentReplyCountByAudioContentCommentId(rootId, viewerId) + val roots = contentComments.findByContentId( + "https://test.cloudfront.net", + content.id!!, + viewerId, + viewerId == creator.id, + "UTC", + 0, + 10 + ) + assertEquals(count, roots.singleOrNull()?.replyCount ?: 0, "embedded root reply count") + Replies(items.map { it.id }.toSet(), count, null) + } + Surface.LEGACY_COMMUNITY -> { + val items = communityComments.getCommunityCommentReplyList(rootId, viewerId, "UTC", 0, 10) + val count = communityComments.commentReplyCountByCommentId(rootId, viewerId) + val roots = communityComments.findByPostId(post.id!!, viewerId, viewerId == creator.id, "UTC", 0, 10) + assertEquals(count, roots.singleOrNull()?.replyCount ?: 0, "embedded root reply count") + Replies(items.map { it.id }.toSet(), count, null) + } + Surface.V2_COMMUNITY -> Replies( + communityQuery.findCommunityReplies(rootId, viewerId, 0, 10, Lang.KO).map { it.commentId }.toSet(), + communityQuery.countCommunityReplies(rootId, viewerId), + communityQuery.findLatestRepliesByCommentIds(listOf(rootId), viewerId, Lang.KO).map { it.commentId }.toSet() + ) + } + + enum class Surface { CONTENT, LEGACY_COMMUNITY, V2_COMMUNITY } + enum class Viewer { FAN, CREATOR, REPLY_WRITER, OUTSIDER } + data class Visibility(val parentSecret: Boolean, val replySecret: Boolean, val allowed: Set) + private data class Replies(val ids: Set, val count: Int, val previewIds: Set?) + + companion object { + @JvmStatic + fun visibilityCases(): Stream { + val owners = setOf(Viewer.FAN, Viewer.CREATOR) + val cases = listOf( + Visibility(false, false, Viewer.values().toSet()), + Visibility(false, true, owners + Viewer.REPLY_WRITER), + Visibility(true, false, owners), + Visibility(true, true, owners) + ) + return Surface.values().flatMap { surface -> + cases.flatMap { visibility -> Viewer.values().map { Arguments.of(surface, visibility, it) } } + }.stream() + } + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadSecretWriteIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadSecretWriteIntegrationTest.kt new file mode 100644 index 00000000..bd7e5e44 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/CommentThreadSecretWriteIntegrationTest.kt @@ -0,0 +1,144 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.can.use.CanUsage +import kr.co.vividnext.sodalive.can.use.UseCan +import kr.co.vividnext.sodalive.common.SodaException +import kr.co.vividnext.sodalive.content.AudioContent +import kr.co.vividnext.sodalive.content.comment.AudioContentComment +import kr.co.vividnext.sodalive.content.order.Order +import kr.co.vividnext.sodalive.content.order.OrderType +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.springframework.transaction.annotation.Transactional + +@Transactional +class CommentThreadSecretWriteIntegrationTest : CommentThreadIntegrationSupport() { + @ParameterizedTest + @CsvSource("CONTENT,false", "CONTENT,true", "COMMUNITY,false", "COMMUNITY,true") + @DisplayName("구매한 일반 팬의 비밀 요청과 비밀 부모 답글은 비밀로 저장되고 제3자 목록과 개수에서 숨긴다") + fun shouldPersistFanReplySecrecyAndHideItFromOutsiders(kind: Kind, parentSecret: Boolean) { + savePurchase(kind) + val rootId = saveRoot(kind, parentSecret) + flushAndClear() + + writeFanReply(kind, rootId, requestedSecret = !parentSecret) + flushAndClear() + + when (kind) { + Kind.CONTENT -> { + val saved = entityManager.createQuery( + "select r from AudioContentComment r where r.parent.id = :rootId", + AudioContentComment::class.java + ).setParameter("rootId", rootId).resultList.single() + assertTrue(saved.isSecret) + assertEquals( + emptyList(), + contentComments.getAudioContentCommentReplyList( + "https://test.cloudfront.net", + rootId, + outsider.id!!, + "UTC", + 0, + 10 + ).map { it.id } + ) + assertEquals(0, contentComments.commentReplyCountByAudioContentCommentId(rootId, outsider.id!!)) + } + Kind.COMMUNITY -> { + val saved = entityManager.createQuery( + "select r from CreatorCommunityComment r where r.parent.id = :rootId", + CreatorCommunityComment::class.java + ).setParameter("rootId", rootId).resultList.single() + assertTrue(saved.isSecret) + assertEquals( + emptyList(), + communityComments.getCommunityCommentReplyList(rootId, outsider.id!!, "UTC", 0, 10).map { it.id } + ) + assertEquals(0, communityComments.commentReplyCountByCommentId(rootId, outsider.id!!)) + } + } + } + + @ParameterizedTest + @CsvSource("CONTENT,false", "CONTENT,true", "COMMUNITY,false", "COMMUNITY,true") + @DisplayName("구매하지 않은 일반 팬은 요청 또는 부모가 비밀인 답글을 저장할 수 없다") + fun shouldRejectEffectiveSecretFanReplyWithoutPurchaseAndInsert(kind: Kind, parentSecret: Boolean) { + val rootId = saveRoot(kind, parentSecret) + flushAndClear() + + val exception = assertThrows(SodaException::class.java) { + writeFanReply(kind, rootId, requestedSecret = !parentSecret) + } + + val entityName = when (kind) { + Kind.CONTENT -> "AudioContentComment" + Kind.COMMUNITY -> "CreatorCommunityComment" + } + val expectedKey = when (kind) { + Kind.CONTENT -> "content.comment.error.secret_requires_purchase" + Kind.COMMUNITY -> "creator.community.secret_comment_purchase_required" + } + assertEquals(expectedKey, exception.messageKey) + assertEquals( + 0L, + entityManager.createQuery( + "select count(r) from $entityName r where r.parent.id = :rootId", + java.lang.Long::class.java + ).setParameter("rootId", rootId).singleResult.toLong() + ) + } + + private fun saveRoot(kind: Kind, secret: Boolean): Long = when (kind) { + Kind.CONTENT -> contentComment(secret = secret).id!! + Kind.COMMUNITY -> communityComment(secret = secret).id!! + } + + private fun writeFanReply(kind: Kind, rootId: Long, requestedSecret: Boolean) { + when (kind) { + Kind.CONTENT -> contentService.registerComment( + member = fan, + comment = "private fan reply", + audioContentId = content.id!!, + parentId = rootId, + isSecret = requestedSecret, + languageCode = "ko" + ) + Kind.COMMUNITY -> communityService.createCommunityPostComment( + member = fan, + comment = "private fan reply", + postId = post.id!!, + parentId = rootId, + isSecret = requestedSecret, + isAdult = true + ) + } + } + + private fun savePurchase(kind: Kind) { + when (kind) { + Kind.CONTENT -> { + val paidContent = entityManager.find(AudioContent::class.java, content.id).apply { price = 100 } + Order(type = OrderType.KEEP).apply { + member = fan + creator = this@CommentThreadSecretWriteIntegrationTest.creator + audioContent = paidContent + }.also(entityManager::persist) + } + Kind.COMMUNITY -> { + val paidPost = entityManager.find(CreatorCommunity::class.java, post.id).apply { price = 100 } + UseCan(canUsage = CanUsage.PAID_COMMUNITY_POST, can = 100, rewardCan = 0).apply { + member = fan + communityPost = paidPost + }.also(entityManager::persist) + } + } + } + + enum class Kind { CONTENT, COMMUNITY } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/FanTalkThreadPrivacyIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/FanTalkThreadPrivacyIntegrationTest.kt new file mode 100644 index 00000000..2ea3e557 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/commentthread/FanTalkThreadPrivacyIntegrationTest.kt @@ -0,0 +1,93 @@ +package kr.co.vividnext.sodalive.v2.commentthread + +import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers +import kr.co.vividnext.sodalive.explorer.profile.PutWriteCheersRequest +import kr.co.vividnext.sodalive.i18n.Lang +import kr.co.vividnext.sodalive.member.Member +import kr.co.vividnext.sodalive.member.MemberRole +import kr.co.vividnext.sodalive.member.block.BlockMember +import org.junit.jupiter.api.Assertions.assertAll +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.springframework.transaction.annotation.Transactional + +@Transactional +class FanTalkThreadPrivacyIntegrationTest : CommentThreadIntegrationSupport() { + @Test + @DisplayName("레거시 팬톡은 활성 다중 답글과 일반 사용자 답글을 보존하고 삭제 답글 및 다른 채널 답글을 숨긴다") + fun shouldKeepLegacyMultipleRepliesWithoutDeletedOrForeignChannelReplies() { + val root = fanTalk() + val first = fanTalk(creator, root) + val second = fanTalk(creator, root) + val generalReply = fanTalk(replyWriter, root) + val deletedReply = fanTalk(creator, root) + fanTalk(creator, root).creator = Member( + email = "other-channel@test.com", + nickname = "other-channel", + password = "password", + role = MemberRole.CREATOR + ).also(entityManager::persist) + BlockMember().apply { member = outsider; blockedMember = replyWriter }.also(entityManager::persist) + flushAndClear() + + explorerService.modifyCheers(PutWriteCheersRequest(deletedReply.id!!, isActive = false), creator) + flushAndClear() + + val legacy = explorerQuery.getCheersList(creator.id!!, fan.id!!, "UTC", 0, 10) + val blocked = explorerQuery.getCheersList(creator.id!!, outsider.id!!, "UTC", 0, 10) + val v2 = fanTalkQuery.findCreatorReplies(creator.id!!, listOf(root.id!!), Lang.KO) + assertAll( + { assertEquals(1, legacy.totalCount) }, + { + assertEquals( + setOf(first.id, second.id, generalReply.id), + legacy.cheers.single().replyList.map { it.cheersId }.toSet() + ) + }, + { assertEquals(setOf(first.id, second.id), blocked.cheers.single().replyList.map { it.cheersId }.toSet()) }, + { assertEquals(listOf(first.id, second.id), v2.map { it.fanTalkId }) } + ) + } + + @Test + @DisplayName("삭제한 팬톡 부모의 활성 답글은 직접 부모 ID로 요청해도 V2 조회에 노출되지 않는다") + fun shouldHideRepliesOfDeletedFanTalkRootWithoutDeletingChildRows() { + val root = fanTalk() + val reply = fanTalk(creator, root) + flushAndClear() + + deleteRoot(ThreadKind.FANTALK, root.id!!) + flushAndClear() + + assertAll( + { + assertEquals( + emptyList(), + fanTalkQuery.findCreatorReplies(creator.id!!, listOf(root.id!!), Lang.KO).map { it.fanTalkId } + ) + }, + { assertEquals(0, explorerQuery.getCheersList(creator.id!!, fan.id!!, "UTC", 0, 10).totalCount) }, + { assertTrue(entityManager.find(CreatorCheers::class.java, reply.id).isActive) } + ) + } + + @Test + @DisplayName("팬톡 직접 답글 조회는 같은 채널의 활성 root 부모만 허용한다") + fun shouldHideRepliesWhoseParentBelongsToAnotherChannel() { + val root = fanTalk() + fanTalk(creator, root) + root.creator = Member( + email = "foreign-root@test.com", + nickname = "foreign-root", + password = "password", + role = MemberRole.CREATOR + ).also(entityManager::persist) + flushAndClear() + + val replies = fanTalkQuery.findCreatorReplies(creator.id!!, listOf(root.id!!), Lang.KO) + + assertEquals(emptyList(), replies.map { it.fanTalkId }) + } +}