Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge dev to main #289

Merged
merged 19 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/adapters/event.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
* @property {string} VIDEO_STATE_CHANGE - video state change event
* @property {string} AUDIO_STATE_CHANGE - audio state change event
* @property {string} EXCEPTION - exception event
*
* @property {string} JOIN_LOBBY - new user joined event
* @property {string} NEW_USER_JOINED_LOBBY - new user joined event to all users in the lobby except the new user
* @property {string} EXISTING_LOBBY_USERS - existing users in the lobby
* @property {string} LEAVE_LOBBY - user trigger when user intends to leave the lobby
* @property {string} LEFT_LOBBY - user left lobby successfully in the Server Side
*/
export const SOCKET_EVENT = {
JOIN_ROOM: 'joinRoom',
Expand All @@ -44,6 +50,11 @@ export const SOCKET_EVENT = {
AUDIO_STATE_CHANGE: 'audioStateChange',
EXCEPTION: 'exception',
DISCONNECT: 'disconnect',
JOIN_LOBBY: 'joinLobby',
NEW_USER_JOINED_LOBBY: 'newUserJoinedLobby',
EXISTING_LOBBY_USERS: 'existingUsers',
LEAVE_LOBBY: 'leaveLobby',
LEFT_LOBBY: 'LeftLobby',
} as const;

export type EVENT = typeof SOCKET_EVENT[keyof typeof SOCKET_EVENT];
167 changes: 167 additions & 0 deletions src/adapters/friendSocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/* eslint-disable no-unused-vars */
import { io } from 'socket.io-client';
import directMessage, {
newMessageInterface,
message,
} from 'src/interface/directMessage.interface';
import { getDate } from '../utils/getDate';
import { API } from '../config';

const friendSocket = { socket: null };

const generateFriend = () => {
if (!friendSocket.socket)
friendSocket.socket = localStorage.getItem('access_token')
? io(`${API.SOCKET_FRIEND as string}`, {
transports: ['websocket', 'polling'],
query: { token: localStorage.getItem('access_token') },
})
: null;
};

const deleteSocket = () => {
friendSocket.socket = null;
};

const syncFriend = (
setMessage: ({
uid,
messages,
}: {
uid: number;
messages: newMessageInterface[];
}) => void,
) => {
friendSocket.socket?.on('friend:sync-all', (data: directMessage[]) => {
data.forEach((singleData) => {
if (singleData.messages.length === 0) return;
// 가장 최근에 온 순서로 정렬
const filteredMessage = singleData.messages
? singleData.messages.sort((a, b) => {
return Number(a.createdAt) - Number(b.createdAt);
})
: [];

// 채팅을 보낼 때 같은 군집으로 보낼지 여부를 결정
// 앞의 message와 비교해서 내가 저번에 보냈고, 같은 분에 속해있다면 true 아니면 false

const newMessageType: newMessageInterface[] = [];
newMessageType.push({
...filteredMessage[0],
isHide: false,
hideTime: false,
});

for (let i = 1; i < filteredMessage.length; i += 1) {
const prev = filteredMessage[i - 1];
const cur = filteredMessage[i];

const {
day: prevDay,
hour: prevHour,
min: prevMin,
} = getDate(prev.createdAt);
const {
day: curDay,
hour: curHour,
min: curMin,
} = getDate(cur.createdAt);

if (
cur.from === prev.from &&
cur.to === prev.to &&
curDay === prevDay &&
curHour === prevHour &&
curMin === prevMin
) {
newMessageType.push({ ...cur, isHide: true, hideTime: false });
newMessageType[i - 1].hideTime = true;
} else {
newMessageType.push({ ...cur, isHide: false, hideTime: false });
}
}

newMessageType.reverse();

setMessage({
uid: singleData.friend.uid,
messages: newMessageType,
});
});
});
};

const recvDirectMessage = (
setMessages: ({
uid,
messages,
}: {
uid: number;
messages: newMessageInterface[];
}) => void,
uid: number,
messages: { [key: string]: newMessageInterface[] },
) => {
friendSocket.socket?.on('directMessage', (data: message) => {
const targetUid = data.from === uid ? data.to : data.from;
const myChatRoom = messages[targetUid];

// 채팅방에 메세지가 없었을 때
if (myChatRoom.length === 0) {
setMessages({
uid: targetUid,
messages: [
{
...data,
isHide: false,
hideTime: false,
},
],
});
return;
}

const {
day: prevDay,
hour: prevHour,
min: prevMin,
} = getDate(messages[targetUid][0].createdAt);
const { day: curDay, hour: curHour, min: curMin } = getDate(data.createdAt);

if (
data.from === messages[targetUid][0].from &&
data.to === messages[targetUid][0].to &&
curDay === prevDay &&
curHour === prevHour &&
curMin === prevMin
) {
myChatRoom.unshift({ ...data, isHide: true, hideTime: false });
myChatRoom[1].hideTime = true;
} else {
myChatRoom.unshift({ ...data, isHide: false, hideTime: false });
}

setMessages({
uid: targetUid,
messages: myChatRoom,
});
});
};

const sendDirectMessage = (message: string, to: number) => {
friendSocket.socket?.emit('directMessage', {
message,
to,
createdAt: Date.now().toString(),
});
};

export default friendSocket;

export {
generateFriend,
deleteSocket,
syncFriend,
recvDirectMessage,
sendDirectMessage,
};
2 changes: 1 addition & 1 deletion src/adapters/getSocketData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import connectedUsersStore from 'src/stores/room/connectedUsersStore';
import messageStore from 'src/stores/room/messagesStore';
import lobbyMessageStore from 'src/stores/lobbyMessageStore';
import roomSocket from './roomSocket';
import lobbySocket from './lobbySocket';
import { lobbySocket } from './lobbySocket';

const getSocketData = (roomId: string) => {
const { connectedUsers: roomConnected } = connectedUsersStore();
Expand Down
67 changes: 55 additions & 12 deletions src/adapters/lobbySocket.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,64 @@
import { io } from 'socket.io-client';
import { API } from '../config';
import { SOCKET_EVENT } from './event.enum';

const lobbySocket = { socket: null };
const lobbySocket = {
socket: null,
};

const generateLobbySocket = (token) => {
lobbySocket.socket = io(`${API.SOCKET_LOBBY as string}`, {
transports: ['websocket', 'polling'],
query: { token },
});
lobbySocket.socket?.connect();
};

const generateSocket = () => {
lobbySocket.socket = localStorage.getItem('access_token')
? io(`${API.SOCKET_LOBBY as string}`, {
transports: ['websocket', 'polling'],
query: { token: localStorage.getItem('access_token') },
})
: null;
const initSocketConnection = (token) => {
if (lobbySocket.socket === null) {
generateLobbySocket(token);
}
lobbySocket.socket.connect();
};

const deleteSocket = () => {
lobbySocket.socket = null;
const emitJoinLobby = (getMe) => {
getMe().then((res) => {
lobbySocket.socket.emit(SOCKET_EVENT.JOIN_LOBBY, { uid: res.data.uid });
});
};

export default lobbySocket;
const onNewUserJoinedLobby = (func) => {
lobbySocket.socket?.on(SOCKET_EVENT.NEW_USER_JOINED_LOBBY, (data) =>
func(data),
);
};

const onExistingUsers = (func) => {
lobbySocket.socket?.on(SOCKET_EVENT.EXISTING_LOBBY_USERS, (data) =>
func(data),
);
};

export { generateSocket, deleteSocket };
const leaveLobby = () => {
lobbySocket.socket?.emit(SOCKET_EVENT.LEAVE_LOBBY);
lobbySocket.socket?.off(SOCKET_EVENT.JOIN_LOBBY);
lobbySocket.socket?.off(SOCKET_EVENT.NEW_USER_JOINED_LOBBY);
lobbySocket.socket?.off(SOCKET_EVENT.EXISTING_LOBBY_USERS);
lobbySocket.socket?.off(SOCKET_EVENT.LEFT_LOBBY);
lobbySocket.socket?.disconnect();
};

const onLeftLobby = (func) => {
lobbySocket.socket?.on(SOCKET_EVENT.LEFT_LOBBY, (data) => func(data));
};

export {
lobbySocket,
generateLobbySocket,
emitJoinLobby,
initSocketConnection,
onNewUserJoinedLobby,
onExistingUsers,
leaveLobby,
onLeftLobby,
};
19 changes: 19 additions & 0 deletions src/adapters/useDirectMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect } from 'react';
import directMessageStore from 'src/stores/directMessageStore';
import userStore from 'src/stores/userStore';
import friendSocket, { generateFriend, syncFriend } from './friendSocket';

const useDirectMessage = () => {
const { setMessages } = directMessageStore();
const { uid, isLogin } = userStore();

useEffect(() => {
generateFriend();
syncFriend(setMessages);
return () => {
friendSocket.socket?.off('friend:sync-all');
};
}, [setMessages, uid, isLogin]);
};

export default useDirectMessage;
10 changes: 6 additions & 4 deletions src/adapters/youtubeSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { API } from '../config';
import youtubeSearch from '../interface/youtubeSearch.interface';

const youtubeSocket = {
socket: io(`${API.YOUTUBE_PLAYLIST as string}`, {
transports: ['websocket', 'polling'],
query: { token: localStorage.getItem('access_token') },
}),
socket: localStorage.getItem('access_token')
? io(`${API.YOUTUBE_PLAYLIST as string}`, {
transports: ['websocket', 'polling'],
query: { token: localStorage.getItem('access_token') },
})
: null,
};

const generateYoutubeSocket = () => {
Expand Down
4 changes: 4 additions & 0 deletions src/api/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ const createRoom = (
tags: string[],
total: number,
theme: string,
isPublic: boolean,
password: string,
) => {
const room = {
moderator,
Expand All @@ -84,6 +86,8 @@ const createRoom = (
tags,
total,
theme,
isPublic,
password,
};
return authorizationRequest.post(API.ROOM, room);
};
Expand Down
4 changes: 4 additions & 0 deletions src/assets/svg/Lock.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion src/components/atoms/chatting/SendChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useState, useRef } from 'react';
import styled from 'styled-components';
import { ReactComponent as MessageSend } from '../../../assets/svg/MessageSend.svg';
import roomSocket from '../../../adapters/roomSocket';
import lobbySocket from '../../../adapters/lobbySocket';
import { lobbySocket } from '../../../adapters/lobbySocket';

export default function SendChat({
roomId,
Expand Down
Loading