Skip to content

Commit

Permalink
Merge branch 'feat/#113'
Browse files Browse the repository at this point in the history
  • Loading branch information
ch9968 committed Nov 29, 2024
2 parents fff2e76 + f4fc34c commit 975dbb0
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 91 deletions.
16 changes: 4 additions & 12 deletions bookduck/public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,13 @@ const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
console.log("백그라운드 메시지 수신:", payload);

const notificationTitle = payload.notification.title || "알림 제목 없음";
const notificationTitle = payload.data?.title || "알림 제목 없음";
const notificationOptions = {
body: payload.notification.body || "알림 내용 없음",
body: payload.data?.body || "알림 내용 없음",
};

self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener("install", (event) => {
console.log("Service Worker 설치됨");
self.skipWaiting(); // 새 Service Worker를 즉시 활성화
});

self.addEventListener("activate", (event) => {
console.log("Service Worker 활성화됨");
return self.clients.claim(); // 기존 클라이언트 제어
});
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", () => self.clients.claim());
1 change: 0 additions & 1 deletion bookduck/src/api/fcmApi.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { post } from "./example";
import { postAccessTokenIssue } from "./oauth";
export const postFcmToken = async (userId, fcmToken) => {
try {
// POST 요청으로 FCM 토큰 전송
Expand Down
3 changes: 3 additions & 0 deletions bookduck/src/components/FriendPage/CurrentFriendComponent.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { useState, useEffect } from "react";
import FriendListComponent from "../common/FriendListComponent";
import { useNavigate } from "react-router-dom";
import { get, del } from "../../api/example";
const CurrentFriendComponent = () => {
const [friendList, setFriendList] = useState([]);
const [friendCount, setFriendCount] = useState(0);
const navigate = useNavigate();
//API연결
//API-친구 목록 조회
const getFriendList = async () => {
Expand Down Expand Up @@ -41,6 +43,7 @@ const CurrentFriendComponent = () => {
isOfficial={friend.isOfficial}
text="삭제"
handleDelete={() => delFriend(friend.friendId)}
handleClick={() => navigate(`/user/${friend.userId}`)}
/>
))}
</div>
Expand Down
3 changes: 3 additions & 0 deletions bookduck/src/components/FriendPage/FriendRequestComponent.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import React, { useState, useEffect } from "react";
import { get, post, put, del } from "../../api/example";
import FriendListComponent from "../common/FriendListComponent";
import { useNavigate } from "react-router-dom";
import up from "../../assets/common/up.svg";
import down from "../../assets/common/down.svg";

const FriendRequestComponent = () => {
const navigate = useNavigate();
//상태 관리
const [receivedFriendList, setReceivedFriendList] = useState([]);
const [receivedFriendCount, setReceivedFriendCount] = useState(0);
Expand Down Expand Up @@ -135,6 +137,7 @@ const FriendRequestComponent = () => {
userName={friend.userNickname}
text="취소"
handleCancel={() => delFriendRequest(friend.requestId)}
handleClick={() => navigate(`/user/${friend.userId}`)}
/>
))}
</div>
Expand Down
1 change: 0 additions & 1 deletion bookduck/src/components/MainPage/DraggableList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React, { useEffect } from "react";
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import deleteIcon2 from "../../assets/mainPage/delete.svg";
import Card from "./Card";
import { update } from "@react-spring/web";

const DraggableList = ({ cards, setCards, isEditMode }) => {
const handleDragEnd = (result) => {
Expand Down
8 changes: 7 additions & 1 deletion bookduck/src/components/MainPage/ReadingSpaceComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ const ReadingSpaceComponent = ({
setUserId(id);
const response = await get(`/users/${id}/readingspace`);
// console.log(response);
setCards(response.cardList);
{
isMine
? setCards(response.cardList)
: setCards(
response.cardList.filter((card) => card.visibility === "PUBLIC")
);
}
} catch (error) {
console.error("리딩스페이스 조회 오류", error);
}
Expand Down
124 changes: 50 additions & 74 deletions bookduck/src/context/SSEProvider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,114 +3,90 @@ import { EventSourcePolyfill } from "event-source-polyfill";

// SSE Context 생성
const SSEContext = createContext(null);
const DEFAULT_SSE_DATA = {
isCommonAlarmChecked: null,
isAnnouncementChecked: null,
isItemUnlockedChecked: null,
isLevelUpChecked: null,
isBadgeUnlockedChecked: null,
newLevel: null,
newBadgeInfo: null,
};

// SSEProvider 컴포넌트
export const SSEProvider = ({ children }) => {
// SSE 데이터 상태 관리
const [sseData, setSseData] = useState({
isCommonAlarmChecked: null,
isAnnouncementChecked: null,
isItemUnlockedChecked: null,
isLevelUpChecked: null,
isBadgeUnlockedChecked: null,
newLevel: null,
newBadgeInfo: null,
});

// SSE 연결 함수
const initializeSSE = () => {
console.log("SSE 초기화 시작...");
const [sseData, setSseData] = useState(DEFAULT_SSE_DATA);
const [eventSource, setEventSource] = useState(null);

// LocalStorage에서 토큰 가져오기
const rawTokenData = localStorage.getItem("token");
if (!rawTokenData) {
console.error("LocalStorage에 토큰이 없습니다. SSE 초기화를 건너뜁니다.");
return null;
}
const tokenData = JSON.parse(rawTokenData || "{}");
// SSE 연결 설정
const connectToSSE = () => {
const tokenData = JSON.parse(localStorage.getItem("token") || "{}");
const accessKey = tokenData?.accessToken;

// Access Token 확인
if (!accessKey) {
console.error("Access key가 없습니다.");
console.error("Access key가 없어서 SSE 초기화가 중단되었습니다.");
return null;
}

// EventSourcePolyfill 생성
let eventSource;
try {
eventSource = new EventSourcePolyfill(
"https://api.bookduck.kro.kr/alarms/subscribe",
const newEventSource = new EventSourcePolyfill(
`${import.meta.env.VITE_API_BASE_URL}/alarms/subscribe`,
{
headers: {
Authorization: `Bearer ${accessKey}`,
},
heartbeatTimeout: 300000,
heartbeatTimeout: 300000, // 5분
withCredentials: true,
}
);
console.log("EventSourcePolyfill 객체 생성 성공");

console.log("SSE 연결 성공");

// 이벤트 핸들러 등록
newEventSource.onopen = () => console.log("SSE 연결 열림");
newEventSource.addEventListener("sse-alarm", onSSEMessageReceived);
newEventSource.onerror = onSSEError;

setEventSource(newEventSource); // 상태 저장
return newEventSource;
} catch (error) {
console.error("EventSourcePolyfill 생성에러 발생:", error);
console.error("SSE 연결예외 발생:", error);
return null;
}
};

// 연결 성공 시 로그 출력
eventSource.onopen = () => {
console.log("SSE 연결이 열렸습니다!");
};

// SSE 이벤트 수신
eventSource.addEventListener("sse-alarm", (event) => {
console.log("SSE 이벤트 수신:", event);
try {
const data = JSON.parse(event.data);
// console.log("수신된 데이터 파싱 성공:", data);
setSseData({
isCommonAlarmChecked: data.isCommonAlarmChecked,
isAnnouncementChecked: data.isAnnouncementChecked,
isItemUnlockedChecked: data.isItemUnlockedChecked,
isLevelUpChecked: data.isLevelUpChecked,
isBadgeUnlockedChecked: data.isBadgeUnlockedChecked,
newLevel: data.newLevel,
newBadgeInfo: data.newBadgeInfo,
});
} catch (error) {
console.error("SSE 데이터 파싱 오류:", error);
}
});

// 오류 처리
eventSource.onerror = (error) => {
console.error("SSE 연결 에러 발생:", error);
if (error.status) {
console.error("HTTP 상태 코드:", error.status);
}
};
// SSE 메시지 수신 처리
const onSSEMessageReceived = (event) => {
try {
const data = JSON.parse(event.data);
console.log("SSE 메시지 수신:", data);
setSseData(data);
} catch (error) {
console.error("SSE 메시지 파싱 오류:", error);
}
};

return eventSource;
// SSE 연결 에러 처리
const onSSEError = (error) => {
console.error("SSE 연결 에러:", error);
};

// SSE 초기화 및 정리
// SSE 연결 및 정리
useEffect(() => {
console.log("SSEProvider 마운트 - SSE 연결 시도");
const eventSource = initializeSSE();

// 컴포넌트 언마운트 시 SSE 연결 해제
if (!eventSource) {
connectToSSE();
}
return () => {
if (eventSource) {
eventSource.close();
console.log("SSE 연결이 종료되었습니다.");
console.log("SSE 연결 종료");
}
};
}, []);
}, [eventSource]);

return (
<SSEContext.Provider value={{ sseData }}>{children}</SSEContext.Provider>
);
};

// SSEContext를 사용하는 커스텀 훅
export const useSSE = () => {
return useContext(SSEContext);
};
export const useSSE = () => useContext(SSEContext);
4 changes: 2 additions & 2 deletions bookduck/src/pages/MainPage/MainPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ const MainPage = () => {
useEffect(() => {
// console.log("SSE 데이터 업데이트 감지:", sseData);
const shouldShowDot =
!sseData?.isCommonAlarmChecked || !sseData?.isAnnouncementChecked;
sseData?.isCommonAlarmChecked === false ||
sseData?.isAnnouncementChecked === false;

if (isDot !== shouldShowDot) {
// console.log(shouldShowDot ? "레드 닷 띄우기" : "레드 닷 없애기");
setIsDot(shouldShowDot);
}
}, [sseData, isDot]);
Expand Down

0 comments on commit 975dbb0

Please sign in to comment.