Skip to content

Commit

Permalink
Merge pull request TeamMajorLink#87 from kchaeeun/refactor#82
Browse files Browse the repository at this point in the history
♻️ [REFACTOR] 알림 전송 시 receiver가 아닌 sender에게 알림이 가는 오류 해결
  • Loading branch information
kchaeeun authored Aug 21, 2024
2 parents 6ef42ef + abacf25 commit 8f33eab
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.example.majorLink.controller;

import com.example.majorLink.domain.Lecture;
import com.example.majorLink.domain.User;
import com.example.majorLink.dto.response.NotificationResponse;
import com.example.majorLink.global.auth.AuthUser;
import com.example.majorLink.global.jwt.JwtService;
import com.example.majorLink.repository.LectureRepository;
import com.example.majorLink.service.NotificationService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
Expand All @@ -23,6 +25,7 @@
@RequiredArgsConstructor
public class NotificationController {
private final NotificationService notificationService;
private final LectureRepository lectureRepository;
private final JwtService jwtService;

/**
Expand All @@ -36,7 +39,7 @@ public class NotificationController {
@GetMapping(value = "/subscribe/{X-AUTH-TOKEN}", produces = "text/event-stream")
public SseEmitter subscribe(
@RequestHeader(value = "Last-Event-ID", required = false, defaultValue = "") String lastEventId,
@PathVariable("X-AUTH-TOKEN") String token // 경로 변수로 토큰을 받음
@PathVariable("X-AUTH-TOKEN") String token
) {

// 토큰 유효성 검사
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ public SseEmitter subscribe(UUID userId, String lastEventId) {

@Override
public void send(User sender, Long lectureId, String content) {
Notification notification = notificationRepository.save(createNotification(sender, lectureId, content));
String userId = String.valueOf(sender.getId());

Lecture lecture = lectureRepository.findById(lectureId)
.orElseThrow(() -> new IllegalArgumentException("강의 정보가 없습니다."));
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 강의입니다."));

Notification notification = notificationRepository.save(createNotification(lecture.getUser(), lectureId, content));
UUID receiverId = lecture.getUser().getId();

Map<String, SseEmitter> sseEmitters = emitterRepository.findAllEmitterStartWithByUserId(UUID.fromString(userId));
Map<String, SseEmitter> sseEmitters = emitterRepository.findAllEmitterStartWithByUserId(receiverId); // 알림 받는 사람 아이디
sseEmitters.forEach(
(key, emitter) -> {
emitterRepository.saveEventCache(key, notification);
Expand All @@ -80,7 +80,6 @@ public void send(User sender, Long lectureId, String content) {
}

private Notification createNotification(User sender, Long lectureId, String content) {
String url = "/lecture/" + lectureId + "/details";

Lecture lecture = lectureRepository.findById(lectureId)
.orElseThrow(() -> new IllegalArgumentException("강의 정보가 없습니다."));
Expand Down
67 changes: 67 additions & 0 deletions majorLink/src/main/resources/static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Notification Test Page</title>
</head>
<body>
<input type="text" id="authToken" placeholder="Enter X-AUTH-TOKEN"/>
<button type="button" onclick="login()">로그인</button>
</body>
<script type="text/javascript">
function login() {
const authToken = document.getElementById('authToken').value.trim();
if (!authToken) {
alert('X-AUTH-TOKEN을 입력해주세요.');
return;
}

// Use URL with path variable
const eventSourceUrl = `/notification/subscribe/${encodeURIComponent(authToken)}`;

const eventSource = new EventSource(eventSourceUrl);

eventSource.onmessage = function(event) {
console.log('Received message:', event.data);

const data = JSON.parse(event.data);

(async () => {
const showNotification = () => {
const notification = new Notification('알림', {
body: data.content,
});

setTimeout(() => {
notification.close();
}, 10 * 1000);

notification.addEventListener('click', () => {
window.open(data.url, '_blank');
});
}

// 브라우저 알림 허용 권한
let granted = false;

if (Notification.permission === 'granted') {
granted = true;
} else if (Notification.permission !== 'denied') {
let permission = await Notification.requestPermission();
granted = permission === 'granted';
}

// 알림 보여주기
if (granted) {
showNotification();
}
})();
};

eventSource.onerror = function(event) {
console.error('SSE 오류:', event);
eventSource.close();
};
}
</script>
</html>

0 comments on commit 8f33eab

Please sign in to comment.