feat(live-room): 라이브룸 채팅 삭제 기능 구현

This commit is contained in:
Yu Sung
2026-03-20 10:51:22 +09:00
parent 793b5dd95a
commit 8eca5df62b
9 changed files with 433 additions and 27 deletions

View File

@@ -787,6 +787,7 @@ enum I18n {
static var chatFreezeOnStatusMessage: String { pick(ko: "채팅창을 얼렸습니다.", en: "Chat has been frozen.", ja: "チャットが凍結されました。") }
static var chatFreezeOffStatusMessage: String { pick(ko: "채팅창 얼림이 해제되었습니다.", en: "Chat freeze has been lifted.", ja: "チャット凍結が解除されました。") }
static var chatFreezeBlockedMessage: String { pick(ko: "채팅창이 얼려져 있어 채팅할 수 없습니다.", en: "You cannot chat while chat is frozen.", ja: "チャットが凍結中のため送信できません。") }
static var chatDeleteTitle: String { pick(ko: "채팅 삭제", en: "Delete chat", ja: "チャット削除") }
}
enum LiveNow {

View File

@@ -16,6 +16,7 @@ protocol LiveRoomChat {
}
struct LiveRoomNormalChat: LiveRoomChat {
let chatId: String
let userId: Int
let profileUrl: String
let nickname: String
@@ -37,6 +38,7 @@ struct LiveRoomDonationChat: LiveRoomChat {
}
struct LiveRoomRouletteDonationChat: LiveRoomChat {
let memberId: Int
let profileUrl: String
let nickname: String
let rouletteResult: String

View File

@@ -12,6 +12,7 @@ struct LiveRoomChatItemView: View {
let chatMessage: LiveRoomNormalChat
let onClickProfile: () -> Void
let onLongPressChat: (() -> Void)?
private var rankValue: Int {
chatMessage.rank + 1
@@ -132,6 +133,9 @@ struct LiveRoomChatItemView: View {
Color.black.opacity(0.6)
)
.cornerRadius(3.3)
.onLongPressGesture {
onLongPressChat?()
}
}
.frame(width: screenSize().width - 86, alignment: .leading)
.padding(.leading, 20)

View File

@@ -10,7 +10,7 @@ import Foundation
struct LiveRoomChatRawMessage: Codable {
enum LiveRoomChatRawMessageType: String, Codable {
case DONATION, SECRET_DONATION, EDIT_ROOM_INFO, SET_MANAGER, TOGGLE_ROULETTE, TOGGLE_CHAT_FREEZE, ROULETTE_DONATION
case HEART_DONATION, BIG_HEART_DONATION
case HEART_DONATION, BIG_HEART_DONATION, NORMAL_CHAT, DELETE_CHAT, DELETE_CHAT_BY_USER
}
let type: LiveRoomChatRawMessageType
@@ -21,4 +21,6 @@ struct LiveRoomChatRawMessage: Codable {
let donationMessage: String?
var isActiveRoulette: Bool? = nil
var isChatFrozen: Bool? = nil
var chatId: String? = nil
var targetUserId: Int? = nil
}

View File

@@ -66,6 +66,6 @@ struct LiveRoomRouletteDonationChatItemView: View {
struct LiveRoomRouletteDonationChatItemView_Previews: PreviewProvider {
static var previews: some View {
LiveRoomRouletteDonationChatItemView(chatMessage: LiveRoomRouletteDonationChat(profileUrl: "", nickname: "유저일", rouletteResult: "옵션1"))
LiveRoomRouletteDonationChatItemView(chatMessage: LiveRoomRouletteDonationChat(memberId: 0, profileUrl: "", nickname: "유저일", rouletteResult: "옵션1"))
}
}

View File

@@ -318,6 +318,10 @@ final class LiveRoomViewModel: NSObject, ObservableObject {
return isChatFrozen && liveRoomInfo.creatorId != UserDefaults.int(forKey: .userId)
}
private var isCreator: Bool {
liveRoomInfo?.creatorId == UserDefaults.int(forKey: .userId)
}
func stopV2VTranslationIfJoined(clearCaptionText: Bool = true) {
guard isV2VJoined else { return }
stopV2VTranslation(clearCaptionText: clearCaptionText)
@@ -695,21 +699,162 @@ final class LiveRoomViewModel: NSObject, ObservableObject {
} else if isNoChatting {
self.popupContent = "\(remainingNoChattingTime)초 동안 채팅하실 수 없습니다"
self.isShowPopup = true
} else if chatMessage.count > 0 {
agora.sendMessageToGroup(textMessage: chatMessage) { _, error in
} else if !chatMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
let chatId = UUID().uuidString
let chatRawMessage = LiveRoomChatRawMessage(
type: .NORMAL_CHAT,
message: chatMessage,
can: 0,
donationMessage: nil,
chatId: chatId
)
agora.sendRawMessageToGroup(rawMessage: chatRawMessage) { _, error in
if error == nil {
let (nickname, profileUrl) = self.getUserNicknameAndProfileUrl(accountId: UserDefaults.int(forKey: .userId))
let rank = self.getUserRank(userId: UserDefaults.int(forKey: .userId))
self.messages.append(LiveRoomNormalChat(userId: UserDefaults.int(forKey: .userId), profileUrl: profileUrl, nickname: nickname, rank: rank, chat: chatMessage))
self.messages.append(
LiveRoomNormalChat(
chatId: chatId,
userId: UserDefaults.int(forKey: .userId),
profileUrl: profileUrl,
nickname: nickname,
rank: rank,
chat: chatMessage
)
)
self.invalidateChat()
}
onSuccess()
}
}
}
}
func deleteChat(_ chat: LiveRoomNormalChat) {
guard isCreator else {
return
}
agora.sendRawMessageToGroup(
rawMessage: LiveRoomChatRawMessage(
type: .DELETE_CHAT,
message: chat.chat,
can: 0,
donationMessage: nil,
chatId: chat.chatId,
targetUserId: chat.userId
),
completion: { [unowned self] _, error in
if error == nil {
let previousCount = self.messages.count
self.applyDeleteChat(chatId: chat.chatId)
if previousCount == self.messages.count {
self.applyDeleteChatFallback(userId: chat.userId, message: chat.chat)
}
if previousCount != self.messages.count {
self.invalidateChat()
}
} else {
self.showDeleteSyncError()
}
},
fail: { [unowned self] in
self.showDeleteSyncError()
}
)
}
func deleteChatsByUserId(userId: Int) {
guard isCreator else {
return
}
agora.sendRawMessageToGroup(
rawMessage: LiveRoomChatRawMessage(
type: .DELETE_CHAT_BY_USER,
message: "",
can: 0,
donationMessage: nil,
targetUserId: userId
),
completion: { [unowned self] _, error in
if error == nil {
let previousCount = self.messages.count
self.applyDeleteUserChats(userId: userId)
if previousCount != self.messages.count {
self.invalidateChat()
}
} else {
self.showDeleteSyncError()
}
},
fail: { [unowned self] in
self.showDeleteSyncError()
}
)
}
private func showDeleteSyncError() {
errorMessage = I18n.Common.commonError
isShowErrorPopup = true
}
private func applyDeleteChat(chatId: String) {
messages.removeAll { chat in
guard chat.type == .CHAT,
let normalChat = chat as? LiveRoomNormalChat else {
return false
}
return normalChat.chatId == chatId
}
}
private func applyDeleteChatFallback(userId: Int, message: String) {
if let index = messages.firstIndex(where: { chat in
guard chat.type == .CHAT,
let normalChat = chat as? LiveRoomNormalChat else {
return false
}
return normalChat.userId == userId && normalChat.chat == message
}) {
messages.remove(at: index)
}
}
private func applyDeleteUserChats(userId: Int) {
messages.removeAll { chat in
switch chat.type {
case .CHAT:
guard let normalChat = chat as? LiveRoomNormalChat else {
return false
}
return normalChat.userId == userId
case .DONATION:
guard let donationChat = chat as? LiveRoomDonationChat else {
return false
}
return donationChat.memberId == userId
case .ROULETTE_DONATION:
guard let rouletteChat = chat as? LiveRoomRouletteDonationChat else {
return false
}
return rouletteChat.memberId == userId
case .JOIN:
return false
}
}
}
func donation(can: Int, message: String = "", isSecret: Bool = false) {
if isSecret && can < 10 {
@@ -1204,8 +1349,10 @@ final class LiveRoomViewModel: NSObject, ObservableObject {
}
func kickOut() {
if UserDefaults.int(forKey: .userId) == liveRoomInfo?.creatorId {
repository.kickOut(roomId: AppState.shared.roomId, userId: kickOutId)
let targetUserId = kickOutId
if UserDefaults.int(forKey: .userId) == liveRoomInfo?.creatorId, targetUserId > 0 {
repository.kickOut(roomId: AppState.shared.roomId, userId: targetUserId)
.sink { result in
switch result {
case .finished:
@@ -1213,19 +1360,37 @@ final class LiveRoomViewModel: NSObject, ObservableObject {
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { _ in
} receiveValue: { [unowned self] response in
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
if decoded.success {
let nickname = self.getUserNicknameAndProfileUrl(accountId: targetUserId).nickname
self.agora.sendMessageToPeer(peerId: String(targetUserId), rawMessage: LiveRoomRequestType.KICK_OUT.rawValue.data(using: .utf8)!) { [unowned self] _, _ in
self.popupContent = "\(nickname)님을 내보냈습니다."
self.isShowPopup = true
}
self.deleteChatsByUserId(userId: targetUserId)
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = I18n.Common.commonError
}
self.isShowErrorPopup = true
}
} catch {
self.errorMessage = I18n.Common.commonError
self.isShowErrorPopup = true
}
}
.store(in: &subscription)
let nickname = getUserNicknameAndProfileUrl(accountId: kickOutId).nickname
agora.sendMessageToPeer(peerId: String(kickOutId), rawMessage: LiveRoomRequestType.KICK_OUT.rawValue.data(using: .utf8)!) { [unowned self] _, error in
self.popupContent = "\(nickname)님을 내보냈습니다."
self.isShowPopup = true
}
}
if let index = muteSpeakers.firstIndex(of: UInt(kickOutId)) {
if let index = muteSpeakers.firstIndex(of: UInt(targetUserId)) {
muteSpeakers.remove(at: index)
}
@@ -2075,6 +2240,7 @@ final class LiveRoomViewModel: NSObject, ObservableObject {
let (nickname, profileUrl) = self.getUserNicknameAndProfileUrl(accountId: UserDefaults.int(forKey: .userId))
self.messages.append(
LiveRoomRouletteDonationChat(
memberId: UserDefaults.int(forKey: .userId),
profileUrl: profileUrl,
nickname: nickname,
rouletteResult: rouletteSelectedItem
@@ -2939,6 +3105,7 @@ extension LiveRoomViewModel: AgoraRtmClientDelegate {
} else if decoded.type == .ROULETTE_DONATION {
self.messages.append(
LiveRoomRouletteDonationChat(
memberId: Int(publisher)!,
profileUrl: profileUrl,
nickname: nickname,
rouletteResult: decoded.message
@@ -2958,6 +3125,47 @@ extension LiveRoomViewModel: AgoraRtmClientDelegate {
} else {
DEBUG_LOG("Ignore TOGGLE_CHAT_FREEZE from non-creator publisher=\(publisher)")
}
} else if decoded.type == .NORMAL_CHAT {
let memberId = Int(publisher) ?? 0
let rank = self.getUserRank(userId: memberId)
if let chatId = decoded.chatId,
!decoded.message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!self.blockedMemberIdList.contains(memberId) {
self.messages.append(
LiveRoomNormalChat(
chatId: chatId,
userId: memberId,
profileUrl: profileUrl,
nickname: nickname,
rank: rank,
chat: decoded.message
)
)
}
} else if decoded.type == .DELETE_CHAT {
if Int(publisher) == self.liveRoomInfo?.creatorId {
if let chatId = decoded.chatId {
let previousCount = self.messages.count
self.applyDeleteChat(chatId: chatId)
if previousCount == self.messages.count,
let targetUserId = decoded.targetUserId,
!decoded.message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
self.applyDeleteChatFallback(userId: targetUserId, message: decoded.message)
}
}
} else {
DEBUG_LOG("Ignore DELETE_CHAT from non-creator publisher=\(publisher)")
}
} else if decoded.type == .DELETE_CHAT_BY_USER {
if Int(publisher) == self.liveRoomInfo?.creatorId {
if let targetUserId = decoded.targetUserId {
self.applyDeleteUserChats(userId: targetUserId)
}
} else {
DEBUG_LOG("Ignore DELETE_CHAT_BY_USER from non-creator publisher=\(publisher)")
}
} else if decoded.type == .EDIT_ROOM_INFO || decoded.type == .SET_MANAGER {
self.getRoomInfo()
} else if decoded.type == .HEART_DONATION {
@@ -2970,6 +3178,7 @@ extension LiveRoomViewModel: AgoraRtmClientDelegate {
self.addBigHeartAnimation()
}
} catch {
ERROR_LOG(error.localizedDescription)
}
}
}
@@ -2977,9 +3186,19 @@ extension LiveRoomViewModel: AgoraRtmClientDelegate {
if let message = textMessage {
let memberId = Int(publisher) ?? 0
let rank = getUserRank(userId: memberId)
let chatId = UUID().uuidString
if !message.trimmingCharacters(in: .whitespaces).isEmpty && !blockedMemberIdList.contains(memberId) {
messages.append(LiveRoomNormalChat(userId: memberId, profileUrl: profileUrl, nickname: nickname, rank: rank, chat: message))
messages.append(
LiveRoomNormalChat(
chatId: chatId,
userId: memberId,
profileUrl: profileUrl,
nickname: nickname,
rank: rank,
chat: message
)
)
}
}

View File

@@ -10,7 +10,9 @@ import SwiftUI
struct LiveRoomChatView: View {
let messages: [LiveRoomChat]
let isCreator: Bool
let getUserProfile: (Int) -> Void
let onLongPressChat: (LiveRoomNormalChat) -> Void
var body: some View {
LazyVStack(alignment: .leading, spacing: 18) {
@@ -36,7 +38,8 @@ struct LiveRoomChatView: View {
if chatMessage.userId != UserDefaults.int(forKey: .userId) {
getUserProfile(chatMessage.userId)
}
}
},
onLongPressChat: isCreator ? { onLongPressChat(chatMessage) } : nil
)
}
}
@@ -49,19 +52,23 @@ struct LiveRoomChatView_Previews: PreviewProvider {
LiveRoomChatView(
messages: [
LiveRoomRouletteDonationChat(
memberId: 0,
profileUrl: "https://cf.sodalive.net/profile/26/26-profile-ddf78b4d-0300-4c50-9c84-5d8a95fd5fe2-4892-1705256364320",
nickname: "jkljkljkl",
rouletteResult: "sdfjkldfsjkl",
type: .ROULETTE_DONATION
),
LiveRoomRouletteDonationChat(
memberId: 1,
profileUrl: "https://cf.sodalive.net/profile/26/26-profile-ddf78b4d-0300-4c50-9c84-5d8a95fd5fe2-4892-1705256364320",
nickname: "jkljkljkl",
rouletteResult: "sdfjkldfsjkl",
type: .ROULETTE_DONATION
)
],
getUserProfile: { _ in }
isCreator: false,
getUserProfile: { _ in },
onLongPressChat: { _ in }
)
}
}

View File

@@ -30,6 +30,8 @@ struct LiveRoomViewV2: View {
@State private var wavePhase: CGFloat = 0
@State private var isShowFollowNotifyDialog: Bool = false
@State private var guestFollowButtonTypeOverride: FollowButtonImageType? = nil
@State private var selectedChatForDelete: LiveRoomNormalChat? = nil
@State private var isShowChatDeleteDialog: Bool = false
let heartWaveTimer = Timer.publish(every: 1/60, on: .main, in: .common).autoconnect()
private var appliedKeyboardHeight: CGFloat {
@@ -213,11 +215,19 @@ struct LiveRoomViewV2: View {
scrollObservableView
if !viewModel.changeIsAdult || UserDefaults.bool(forKey: .auth) {
LiveRoomChatView(messages: viewModel.messages) {
if $0 != UserDefaults.int(forKey: .userId) {
viewModel.getUserProfile(userId: $0)
LiveRoomChatView(
messages: viewModel.messages,
isCreator: liveRoomInfo.creatorId == UserDefaults.int(forKey: .userId),
getUserProfile: {
if $0 != UserDefaults.int(forKey: .userId) {
viewModel.getUserProfile(userId: $0)
}
},
onLongPressChat: { chat in
selectedChatForDelete = chat
isShowChatDeleteDialog = true
}
}
)
.frame(width: screenSize().width)
.rotationEffect(Angle(degrees: 180))
.valueChanged(value: viewModel.messageChangeFlag) { _ in
@@ -605,6 +615,24 @@ struct LiveRoomViewV2: View {
}
)
}
if isShowChatDeleteDialog, let selectedChat = selectedChatForDelete {
SodaDialog(
title: I18n.LiveRoom.chatDeleteTitle,
desc: "\(selectedChat.nickname): \(selectedChat.chat)",
confirmButtonTitle: I18n.Common.delete,
confirmButtonAction: {
viewModel.deleteChat(selectedChat)
selectedChatForDelete = nil
isShowChatDeleteDialog = false
},
cancelButtonTitle: I18n.Common.cancel,
cancelButtonAction: {
selectedChatForDelete = nil
isShowChatDeleteDialog = false
}
)
}
}
ZStack {
@@ -979,6 +1007,11 @@ struct LiveRoomViewV2: View {
guestFollowButtonTypeOverride = nil
}
}
.onChange(of: isShowChatDeleteDialog) { isShowing in
if isShowing {
hideKeyboard()
}
}
}
private func estimatedHeight(for text: String, width: CGFloat) -> CGFloat {