forked from solid-connection/solid-connect-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatService.java
More file actions
301 lines (246 loc) · 13.8 KB
/
ChatService.java
File metadata and controls
301 lines (246 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package com.example.solidconnection.chat.service;
import static com.example.solidconnection.common.exception.ErrorCode.CHAT_PARTICIPANT_NOT_FOUND;
import static com.example.solidconnection.common.exception.ErrorCode.CHAT_PARTNER_NOT_FOUND;
import static com.example.solidconnection.common.exception.ErrorCode.INVALID_CHAT_ROOM_STATE;
import static com.example.solidconnection.common.exception.ErrorCode.USER_NOT_FOUND;
import com.example.solidconnection.chat.domain.ChatAttachment;
import com.example.solidconnection.chat.domain.ChatMessage;
import com.example.solidconnection.chat.domain.ChatParticipant;
import com.example.solidconnection.chat.domain.ChatRoom;
import com.example.solidconnection.chat.dto.ChatAttachmentResponse;
import com.example.solidconnection.chat.dto.ChatImageSendRequest;
import com.example.solidconnection.chat.dto.ChatMessageResponse;
import com.example.solidconnection.chat.dto.ChatMessageSendRequest;
import com.example.solidconnection.chat.dto.ChatMessageSendResponse;
import com.example.solidconnection.chat.dto.ChatParticipantResponse;
import com.example.solidconnection.chat.dto.ChatRoomData;
import com.example.solidconnection.chat.dto.ChatRoomListResponse;
import com.example.solidconnection.chat.dto.ChatRoomResponse;
import com.example.solidconnection.chat.repository.ChatMessageRepository;
import com.example.solidconnection.chat.repository.ChatParticipantRepository;
import com.example.solidconnection.chat.repository.ChatReadStatusRepository;
import com.example.solidconnection.chat.repository.ChatRoomRepository;
import com.example.solidconnection.common.dto.SliceResponse;
import com.example.solidconnection.common.exception.CustomException;
import com.example.solidconnection.mentor.repository.MentorRepository;
import com.example.solidconnection.siteuser.domain.SiteUser;
import com.example.solidconnection.siteuser.repository.SiteUserRepository;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service
public class ChatService {
private final ChatRoomRepository chatRoomRepository;
private final ChatMessageRepository chatMessageRepository;
private final ChatParticipantRepository chatParticipantRepository;
private final ChatReadStatusRepository chatReadStatusRepository;
private final SiteUserRepository siteUserRepository;
private final MentorRepository mentorRepository;
private final SimpMessageSendingOperations simpMessageSendingOperations;
public ChatService(ChatRoomRepository chatRoomRepository,
ChatMessageRepository chatMessageRepository,
ChatParticipantRepository chatParticipantRepository,
ChatReadStatusRepository chatReadStatusRepository,
SiteUserRepository siteUserRepository,
MentorRepository mentorRepository,
@Lazy SimpMessageSendingOperations simpMessageSendingOperations) {
this.chatRoomRepository = chatRoomRepository;
this.chatMessageRepository = chatMessageRepository;
this.chatParticipantRepository = chatParticipantRepository;
this.chatReadStatusRepository = chatReadStatusRepository;
this.siteUserRepository = siteUserRepository;
this.mentorRepository = mentorRepository;
this.simpMessageSendingOperations = simpMessageSendingOperations;
}
@Transactional(readOnly = true)
public ChatRoomListResponse getChatRooms(long siteUserId) {
List<ChatRoom> chatRooms = chatRoomRepository.findOneOnOneChatRoomsByUserIdWithParticipants(siteUserId);
if (chatRooms.isEmpty()) {
return ChatRoomListResponse.of(Collections.emptyList());
}
ChatRoomData chatRoomData = getChatRoomData(chatRooms, siteUserId);
List<ChatRoomResponse> responses = chatRooms.stream()
.map(chatRoom -> createChatRoomResponse(chatRoom, siteUserId, chatRoomData))
.toList();
return ChatRoomListResponse.of(responses);
}
private ChatRoomData getChatRoomData(List<ChatRoom> chatRooms, long siteUserId) {
List<Long> chatRoomIds = chatRooms.stream().map(ChatRoom::getId).toList();
List<Long> partnerUserIds = chatRooms.stream()
.map(chatRoom -> findPartner(chatRoom, siteUserId).getSiteUserId())
.toList();
return ChatRoomData.from(
chatMessageRepository.findLatestMessagesByChatRoomIds(chatRoomIds),
chatMessageRepository.countUnreadMessagesBatch(chatRoomIds, siteUserId),
siteUserRepository.findAllByIdIn(partnerUserIds)
);
}
private ChatRoomResponse createChatRoomResponse(ChatRoom chatRoom, long siteUserId, ChatRoomData chatRoomData) {
ChatMessage latestMessage = chatRoomData.latestMessages().get(chatRoom.getId());
ChatParticipant partner = findPartner(chatRoom, siteUserId);
SiteUser partnerUser = chatRoomData.partnerUsers().get(partner.getSiteUserId());
if (partnerUser == null) {
throw new CustomException(USER_NOT_FOUND);
}
return ChatRoomResponse.of(
chatRoom.getId(),
latestMessage != null ? latestMessage.getContent() : "",
latestMessage != null ? latestMessage.getCreatedAt() : null,
ChatParticipantResponse.of(partnerUser.getId(), partnerUser.getNickname(), partnerUser.getProfileImageUrl()),
chatRoomData.unreadCounts().getOrDefault(chatRoom.getId(), 0L)
);
}
@Transactional(readOnly = true)
public SliceResponse<ChatMessageResponse> getChatMessages(long siteUserId, long roomId, Pageable pageable) {
validateChatRoomParticipant(siteUserId, roomId);
Slice<ChatMessage> chatMessages = chatMessageRepository.findByRoomIdWithPaging(roomId, pageable);
Map<Long, ChatParticipant> participantIdToParticipant = buildParticipantIdToParticipantMap(chatMessages);
List<ChatMessageResponse> content = buildChatMessageResponses(chatMessages, participantIdToParticipant);
return SliceResponse.of(content, chatMessages);
}
// senderId(chatParticipantId)로 chatParticipant 맵 생성
private Map<Long, ChatParticipant> buildParticipantIdToParticipantMap(Slice<ChatMessage> chatMessages) {
Set<Long> participantIds = chatMessages.getContent().stream()
.map(ChatMessage::getSenderId)
.collect(Collectors.toSet());
return chatParticipantRepository.findAllById(participantIds).stream()
.collect(Collectors.toMap(ChatParticipant::getId, Function.identity()));
}
private List<ChatMessageResponse> buildChatMessageResponses(
Slice<ChatMessage> chatMessages,
Map<Long, ChatParticipant> participantIdToParticipant
) {
return chatMessages.getContent().stream()
.map(message -> {
ChatParticipant senderParticipant = participantIdToParticipant.get(message.getSenderId());
if (senderParticipant == null) {
throw new CustomException(CHAT_PARTICIPANT_NOT_FOUND);
}
long externalSenderId = senderParticipant.getSiteUserId();
return toChatMessageResponse(message, externalSenderId);
})
.toList();
}
@Transactional(readOnly = true)
public ChatParticipantResponse getChatPartner(long siteUserId, Long roomId) {
ChatRoom chatRoom = chatRoomRepository.findById(roomId)
.orElseThrow(() -> new CustomException(INVALID_CHAT_ROOM_STATE));
ChatParticipant partnerParticipant = findPartner(chatRoom, siteUserId);
SiteUser siteUser = siteUserRepository.findById(partnerParticipant.getSiteUserId())
.orElseThrow(() -> new CustomException(USER_NOT_FOUND));
return ChatParticipantResponse.of(siteUser.getId(), siteUser.getNickname(), siteUser.getProfileImageUrl());
}
private ChatParticipant findPartner(ChatRoom chatRoom, long siteUserId) {
if (chatRoom.isGroup()) {
throw new CustomException(INVALID_CHAT_ROOM_STATE);
}
return chatRoom.getChatParticipants().stream()
.filter(participant -> participant.getSiteUserId() != siteUserId)
.findFirst()
.orElseThrow(() -> new CustomException(CHAT_PARTNER_NOT_FOUND));
}
public void validateChatRoomParticipant(long siteUserId, long roomId) {
boolean isParticipant = chatParticipantRepository.existsByChatRoomIdAndSiteUserId(roomId, siteUserId);
if (!isParticipant) {
throw new CustomException(CHAT_PARTICIPANT_NOT_FOUND);
}
}
private ChatMessageResponse toChatMessageResponse(ChatMessage message, long externalSenderId) {
List<ChatAttachmentResponse> attachments = message.getChatAttachments().stream()
.map(attachment -> ChatAttachmentResponse.of(
attachment.getId(),
attachment.getIsImage(),
attachment.getUrl(),
attachment.getThumbnailUrl(),
attachment.getCreatedAt()
))
.toList();
return ChatMessageResponse.of(
message.getId(),
message.getContent(),
externalSenderId,
message.getCreatedAt(),
attachments
);
}
@Transactional
public void markChatMessagesAsRead(long siteUserId, long roomId) {
ChatParticipant participant = chatParticipantRepository
.findByChatRoomIdAndSiteUserId(roomId, siteUserId)
.orElseThrow(() -> new CustomException(CHAT_PARTICIPANT_NOT_FOUND));
chatReadStatusRepository.upsertReadStatus(roomId, participant.getId());
}
@Transactional
public void sendChatMessage(ChatMessageSendRequest chatMessageSendRequest, long siteUserId, long roomId) {
long senderId = chatParticipantRepository.findByChatRoomIdAndSiteUserId(roomId, siteUserId)
.orElseThrow(() -> new CustomException(CHAT_PARTICIPANT_NOT_FOUND))
.getId();
ChatMessage chatMessage = new ChatMessage(
chatMessageSendRequest.content(),
senderId,
chatRoomRepository.findById(roomId)
.orElseThrow(() -> new CustomException(INVALID_CHAT_ROOM_STATE))
);
chatMessageRepository.save(chatMessage);
ChatMessageSendResponse chatMessageResponse = ChatMessageSendResponse.of(chatMessage, siteUserId);
simpMessageSendingOperations.convertAndSend("/topic/chat/" + roomId, chatMessageResponse);
}
@Transactional
public void sendChatImage(ChatImageSendRequest chatImageSendRequest, long siteUserId, long roomId) {
long senderId = chatParticipantRepository.findByChatRoomIdAndSiteUserId(roomId, siteUserId)
.orElseThrow(() -> new CustomException(CHAT_PARTICIPANT_NOT_FOUND))
.getId();
ChatRoom chatRoom = chatRoomRepository.findById(roomId)
.orElseThrow(() -> new CustomException(INVALID_CHAT_ROOM_STATE));
ChatMessage chatMessage = new ChatMessage("", senderId, chatRoom);
// 이미지 판별을 위한 확장자 리스트
List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png", "webp");
for (String imageUrl : chatImageSendRequest.imageUrls()) {
String extension = StringUtils.getFilenameExtension(imageUrl);
boolean isImage = extension != null && imageExtensions.contains(extension.toLowerCase());
String thumbnailUrl = isImage ? generateThumbnailUrl(imageUrl) : null;
ChatAttachment attachment = new ChatAttachment(isImage, imageUrl, thumbnailUrl, null);
chatMessage.addAttachment(attachment);
}
chatMessageRepository.save(chatMessage);
ChatMessageSendResponse chatMessageResponse = ChatMessageSendResponse.of(chatMessage, siteUserId);
simpMessageSendingOperations.convertAndSend("/topic/chat/" + roomId, chatMessageResponse);
}
private String generateThumbnailUrl(String originalUrl) {
try {
String fileName = originalUrl.substring(originalUrl.lastIndexOf('/') + 1);
String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = fileName.substring(fileName.lastIndexOf('.'));
String thumbnailFileName = nameWithoutExt + "_thumb" + extension;
return originalUrl.replace("chat/files/", "chat/thumbnails/")
.replace(fileName, thumbnailFileName);
} catch (Exception e) {
return originalUrl;
}
}
@Transactional
public Long createMentoringChatRoom(Long mentoringId, Long mentorId, Long menteeId) {
ChatRoom existingChatRoom = chatRoomRepository.findByMentoringId(mentoringId);
if (existingChatRoom != null) {
return existingChatRoom.getId();
}
// 새 채팅방 생성
ChatRoom chatRoom = new ChatRoom(mentoringId, false);
chatRoom = chatRoomRepository.save(chatRoom);
ChatParticipant mentorParticipant = new ChatParticipant(mentorId, chatRoom);
ChatParticipant menteeParticipant = new ChatParticipant(menteeId, chatRoom);
chatParticipantRepository.saveAll(List.of(mentorParticipant, menteeParticipant));
return chatRoom.getId();
}
}