-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNotificationService.java
More file actions
232 lines (202 loc) · 9.46 KB
/
NotificationService.java
File metadata and controls
232 lines (202 loc) · 9.46 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
package com.gamzabat.algohub.feature.notification.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.gamzabat.algohub.exception.UserValidationException;
import com.gamzabat.algohub.feature.group.studygroup.domain.GroupMember;
import com.gamzabat.algohub.feature.group.studygroup.domain.StudyGroup;
import com.gamzabat.algohub.feature.group.studygroup.repository.GroupMemberRepository;
import com.gamzabat.algohub.feature.group.studygroup.repository.StudyGroupRepository;
import com.gamzabat.algohub.feature.notification.domain.Notification;
import com.gamzabat.algohub.feature.notification.domain.NotificationSetting;
import com.gamzabat.algohub.feature.notification.dto.GetNotificationResponse;
import com.gamzabat.algohub.feature.notification.enums.NotificationCategory;
import com.gamzabat.algohub.feature.notification.exception.CannotFoundNotificationException;
import com.gamzabat.algohub.feature.notification.exception.CannotFoundNotificationSettingException;
import com.gamzabat.algohub.feature.notification.exception.NotificationValidationException;
import com.gamzabat.algohub.feature.notification.repository.EmitterRepositoryImpl;
import com.gamzabat.algohub.feature.notification.repository.NotificationRepository;
import com.gamzabat.algohub.feature.notification.repository.NotificationSettingRepository;
import com.gamzabat.algohub.feature.problem.domain.Problem;
import com.gamzabat.algohub.feature.solution.domain.Solution;
import com.gamzabat.algohub.feature.user.domain.User;
import com.gamzabat.algohub.feature.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {
private final EmitterRepositoryImpl emitterRepository;
private final NotificationRepository notificationRepository;
private final NotificationSettingRepository notificationSettingRepository;
private final StudyGroupRepository studyGroupRepository;
private final GroupMemberRepository groupMemberRepository;
private final UserRepository userRepository;
@Transactional
public SseEmitter subscribe(User user, String lastEventId) {
String email = user.getEmail();
String emitterId = makeTimeIncludedId(email);
SseEmitter emitter;
if (emitterRepository.findAllEmitterStartWithByEmail(email) != null)
emitterRepository.deleteAllEmitterStartWithId(email);
emitter = emitterRepository.save(emitterId, new SseEmitter(Long.MAX_VALUE));
emitter.onCompletion(() -> emitterRepository.deleteById(emitterId));
emitter.onTimeout(() -> emitterRepository.deleteById(emitterId));
emitter.onError((e) -> emitterRepository.deleteById(emitterId));
emitter.onError((e) -> emitterRepository.deleteById(emitterId));
String eventId = makeTimeIncludedId(email);
sendNotification(emitter, eventId, emitterId, "EventStream Created : [userId = " + email + "]");
if (hasLostData(lastEventId))
sendLostData(lastEventId, email, emitterId, emitter);
return emitter;
}
private String makeTimeIncludedId(String email) {
return email + "_" + System.currentTimeMillis();
}
@Transactional
public void sendNotification(SseEmitter emitter, String eventId, String emitterId, Object data) {
try {
emitter.send(SseEmitter.event()
.id(eventId)
.name("sse")
.data(data, MediaType.APPLICATION_JSON));
} catch (IOException e) {
emitterRepository.deleteById(emitterId);
emitter.completeWithError(e);
}
}
private boolean hasLostData(String lastEventId) {
return !lastEventId.isEmpty();
}
private void sendLostData(String lastEventId, String email, String emitterId, SseEmitter emitter) {
Map<String, Object> eventCaches = emitterRepository.findAllEventCacheStartWithByEmail(email);
eventCaches.entrySet().stream()
.filter(entry -> lastEventId.compareTo(entry.getKey()) < 0)
.forEach(entry -> sendNotification(emitter, entry.getKey(), emitterId, entry.getValue()));
}
@Transactional
public void send(String receiver, String message, StudyGroup studyGroup, Problem problem, Solution solution,
String subContent) {
Notification notification = createNotification(receiver, message, studyGroup, subContent, problem, solution);
notificationRepository.save(notification);
Map<String, SseEmitter> sseEmitter = emitterRepository.findAllEmitterStartWithByEmail(receiver);
sseEmitter.forEach(
(key, emitter) -> {
emitterRepository.saveEventCache(key, notification);
sendToClient(emitter, key, notification);
}
);
}
private void sendList(List receiverList, String message, StudyGroup studyGroup, String subContent, Problem problem,
Solution solution) {
List<Notification> notifications = new ArrayList<>();
Map<String, SseEmitter> sseEmitters;
for (int i = 0; i < receiverList.size(); i++) {
int finalI = i;
sseEmitters = new HashMap<>();
Notification notification = createNotification(receiverList.get(i).toString(), message, studyGroup,
subContent, problem, solution);
notifications.add(notification);
notificationRepository.save(notification);
sseEmitters.putAll(emitterRepository.findAllEmitterStartWithByEmail(receiverList.get(i).toString()));
sseEmitters.forEach(
(key, emitter) -> {
emitterRepository.saveEventCache(key, notifications.get(finalI));
sendToClient(emitter, key, notifications.get(finalI));
}
);
}
}
private Notification createNotification(String receiver, String message, StudyGroup studyGroup, String subContent,
Problem problem, Solution solution) {
return Notification.builder()
.user(
userRepository.findByEmail(receiver).orElseThrow(() -> new UserValidationException("존재 하지 않는 회원 입니다.")))
.message(message)
.studyGroup(studyGroup)
.problem(problem)
.solution(solution)
.subContent(subContent)
.isRead(false)
.build();
}
private void sendToClient(SseEmitter emitter, String id, Notification notification) {
try {
emitter.send(SseEmitter.event()
.id(id)
.name("sse")
.data(GetNotificationResponse.toDTO(notification), MediaType.APPLICATION_JSON));
} catch (Exception e) {
emitterRepository.deleteById(id);
emitter.completeWithError(e);
}
}
@Transactional(readOnly = true)
public List<GetNotificationResponse> getNotifications(User user) {
List<Notification> notifications = notificationRepository.findAllByUser(user);
notifications.sort(Comparator.comparingLong(Notification::getId).reversed());
return notifications.stream().map(GetNotificationResponse::toDTO).toList();
}
@Transactional
public void readAllNotifications(User user) {
List<Notification> notifications = notificationRepository.findAllByUserAndIsRead(user, false);
notifications.forEach(Notification::updateIsRead);
log.info("success to read all notifications.");
}
@Transactional
public void readNotification(User user, Long notificationId) {
Notification notification = notificationRepository.findById(notificationId)
.orElseThrow(() -> new CannotFoundNotificationException("존재하지 않는 알림입니다."));
if (!notification.getUser().getId().equals(user.getId()))
throw new NotificationValidationException(HttpStatus.FORBIDDEN.value(), "알림의 주인이 일치하지 않습니다.");
notification.updateIsRead();
log.info("success to read notification. notification_id = {}", notificationId);
}
@Transactional
public void sendNotificationToMembers(StudyGroup group, List<GroupMember> receiver, Problem problem,
Solution solution,
NotificationCategory category, String message) {
List<String> users = new ArrayList<>();
for (GroupMember member : receiver) {
NotificationSetting setting = notificationSettingRepository.findByMember(member)
.orElseThrow(() -> {
log.error("cannot find notification setting for member. user_id = {}, group_id =g {}",
member.getUser().getId(), group.getId());
return new CannotFoundNotificationSettingException("해당 그룹에 가입 되지 않은 유저입니다.");
});
if (setting.isAllNotifications() && isSettingOn(setting, category))
users.add(member.getUser().getEmail());
}
try {
sendList(users, message, group, null, problem, solution);
} catch (Exception e) {
log.warn("failed to send notification", e);
}
}
private boolean isSettingOn(NotificationSetting setting, NotificationCategory category) {
return switch (category) {
case NotificationCategory.PROBLEM_STARTED -> setting.isNewProblem();
case NotificationCategory.PROBLEM_DEADLINE_REACHED -> setting.isDeadlineReached();
case NotificationCategory.NEW_COMMENT_POSTED -> setting.isNewComment();
case NotificationCategory.NEW_MEMBER_JOINED -> setting.isNewMember();
case NotificationCategory.NEW_SOLUTION_POSTED -> setting.isNewSolution();
};
}
@Transactional
public void deleteNotification(User user, Long notificationId) {
Notification notification = notificationRepository.findById(notificationId)
.orElseThrow(() -> new CannotFoundNotificationException("존재하지 않는 알림입니다."));
if (!notification.getUser().getId().equals(user.getId()))
throw new NotificationValidationException(HttpStatus.FORBIDDEN.value(), "알림을 삭제할 권한이 없습니다.");
notificationRepository.delete(notification);
}
}