Skip to content

Commit

Permalink
Merge pull request #170 from boostcampwm-2021/dev
Browse files Browse the repository at this point in the history
NogariHouse Release v1.0.3
  • Loading branch information
iHoHyeon authored Dec 2, 2021
2 parents 6536f0a + 9058c9b commit c389de9
Show file tree
Hide file tree
Showing 12 changed files with 181 additions and 79 deletions.
14 changes: 13 additions & 1 deletion client/src/api/user/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
getCredentialsOption, postCredentialsOption, postOption,
getCredentialsOption, getOption, postCredentialsOption, postOption,
} from '@api/util';
import { IUserDetail } from '@src/interfaces';

Expand Down Expand Up @@ -169,3 +169,15 @@ export const getUserDetail = async (profileId: string) => {
console.log(error);
}
};

export const getSignInGuest = async () => {
try {
const response = await fetch(`${process.env.REACT_APP_API_URL}/api/user/signin/guest`, getOption());

const json: {ok: boolean, accessToken?: string} = await response.json();

return json;
} catch (error) {
console.error(error);
}
};
2 changes: 1 addition & 1 deletion client/src/components/chat/detail-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function ChatRoomDetailView() {

const addChattingLog = (chatLog: IChattingLog) => {
dispatch({ type: 'ADD_CHATTING_LOG', payload: { chatLog } });
chattingLogDiv.current!.scrollTop = chattingLogDiv.current!.scrollHeight - chattingLogDiv.current!.clientHeight;
chattingLogDiv.current!.scrollTop = 0;
};

const onIntersect = async (entries: IntersectionObserverEntry[]) => {
Expand Down
40 changes: 22 additions & 18 deletions client/src/components/room/modal/follower-select-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,28 @@ export default function FollowerSelectRoomHeader({ onClick, selectedUsers }: any
onClick();
};

const submitEventHandler = () => {
const nowDate = new Date();
const inviteInfo = {
participants: selectedUsers,
message: `${user.userName}님이 노가리 방으로 초대했습니다! \n 메세지를 눌러 참여하세요!`,
userInfo: {
userDocumentId: user.userDocumentId,
userName: user.userName,
profileUrl: user.profileUrl,
},
roomDocumentId,
date: makeDateToHourMinute(nowDate),
key: `${nowDate.getTime()}_${user.userDocumentId}`,
};
chatSocket.emit(chatSocketMessage.inviteRoom, inviteInfo);
setToastList(toastMessage.roomInviteSuccess);
setRoomView('inRoomView');
setIsOpenRoomModal(false);
const submitEventHandler = async () => {
try {
const nowDate = new Date();
const inviteInfo = {
participants: selectedUsers,
message: `${user.userName}님이 노가리 방으로 초대했습니다! \n 메세지를 눌러 참여하세요!`,
userInfo: {
userDocumentId: user.userDocumentId,
userName: user.userName,
profileUrl: user.profileUrl,
},
roomDocumentId,
date: makeDateToHourMinute(nowDate),
key: `${nowDate.getTime()}_${user.userDocumentId}`,
};
chatSocket.emit(chatSocketMessage.inviteRoom, inviteInfo);
setToastList(toastMessage.roomInviteSuccess);
setRoomView('inRoomView');
setIsOpenRoomModal(false);
} catch (error) {
setToastList(toastMessage.roomInviteDanger());
}
};

return (
Expand Down
42 changes: 21 additions & 21 deletions client/src/components/room/new-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,27 @@ function RoomModal() {
const [isAnonymous, setIsAnonymous] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);

const submitButtonHandler = () => {
const roomInfo = {
type: roomType,
title: inputRef.current?.value as string,
userId: user.userId,
userName: user.userName,
isAnonymous: (roomType !== 'closed') ? isAnonymous : false,
};
postRoomInfo(roomInfo)
.then((roomDocumentId: any) => {
setRoomDocumentId(roomDocumentId);
if (roomType === 'closed') setIsOpenModal(true);
else if (isAnonymous) setRoomView('selectModeView');
else {
setRoomView('inRoomView');
}
})
.catch((err) => {
setToastList(toastMessage.roomCreateDanger());
console.error(err);
});
const submitButtonHandler = async () => {
try {
const roomInfo = {
type: roomType,
title: inputRef.current?.value as string,
userId: user.userId,
userName: user.userName,
isAnonymous: (roomType !== 'closed') ? isAnonymous : false,
};

await navigator.mediaDevices.getUserMedia({ audio: true, video: false });

const roomDocumentId = await postRoomInfo(roomInfo);
setRoomDocumentId(roomDocumentId as unknown as string);
if (roomType === 'closed') setIsOpenModal(true);
else if (isAnonymous) setRoomView('selectModeView');
else setRoomView('inRoomView');
} catch (error: any) {
if (error.name === 'NotAllowedError') setToastList(toastMessage.roomAllowMicDanger());
else setToastList(toastMessage.roomCreateDanger());
}
};

const inputHandler = () => {
Expand Down
14 changes: 0 additions & 14 deletions client/src/components/sign/common/sign-body.tsx

This file was deleted.

1 change: 1 addition & 0 deletions client/src/components/sign/common/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const SignBody = styled.div`
position: relative;
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
width: 100%;
height: calc(100vh - 100px);
Expand Down
47 changes: 46 additions & 1 deletion client/src/components/sign/signin-view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { useSetRecoilState } from 'recoil';
import { useHistory } from 'react-router-dom';

import { postSignIn } from '@api/user';
import { postSignIn, getSignInGuest } from '@api/user';
import SignHeader from '@components/sign/common/sign-header';
import SignTitle from '@components/sign/common/sign-title';
import { SignBody } from '@components/sign/common/style';
Expand All @@ -16,6 +16,7 @@ function SignInView() {
const inputEmailRef = useRef<HTMLInputElement>(null);
const inputPasswordRef = useRef<HTMLInputElement>(null);
const [isDisabled, setIsDisabled] = useState(true);
const [allowGuest, setAllowGuest] = useState(false);
const setToastList = useSetRecoilState(toastListSelector);
const history = useHistory();

Expand All @@ -41,17 +42,47 @@ function SignInView() {
}
};

const checkGuestResponse = (json :
{ok: boolean,
accessToken?:string,
}) => {
if (json.ok) {
setAccessToken(json.accessToken as string);
history.go(0);
} else {
setToastList({
type: 'warning',
title: '로그인 에러',
description: '게스트 이용이 지연되고 있습니다. 다시 시도해주세요',
});
}
};

const allowGuestChange = (email: string) => {
if (email === `${process.env.REACT_APP_ALLOW_GUEST_STRING}`) {
fetch(`${process.env.REACT_APP_API_URL}/api/user/easterEgg/guest?change=true`).then(() => setAllowGuest((now) => !now));
}
};

const signIn = () => {
const loginInfo = {
email: inputEmailRef.current?.value,
password: inputPasswordRef.current?.value,
};

allowGuestChange(loginInfo.email as string);

postSignIn(loginInfo)
.then((json) => json && checkSigninResponse(json))
.catch((err) => console.error(err));
};

const signInGuest = () => {
getSignInGuest()
.then((json) => json && checkGuestResponse(json))
.catch((err) => console.error(err));
};

const keyUpEnter = (e: any) => {
if (inputEmailRef.current?.value
&& inputPasswordRef.current?.value
Expand All @@ -67,6 +98,15 @@ function SignInView() {
};
}, []);

useEffect(() => {
const allowGuestFetch = async () => {
const res = await fetch(`${process.env.REACT_APP_API_URL}/api/user/easterEgg/guest`);
const json = await res.json();
setAllowGuest(json.allowGuest);
};
allowGuestFetch();
}, []);

return (
<>
<SignHeader />
Expand All @@ -79,6 +119,11 @@ function SignInView() {
<DefaultButton buttonType="secondary" size="medium" onClick={signIn} isDisabled={isDisabled}>
NEXT
</DefaultButton>
{allowGuest && (
<DefaultButton buttonType="secondary" size="medium" onClick={signInGuest} isDisabled={false}>
Guest MODE
</DefaultButton>
)}
</SignBody>
</>
);
Expand Down
11 changes: 8 additions & 3 deletions client/src/constants/toast-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,20 @@ export default {
title: '방 초대',
description: '초대 메세지를 보냈습니다!',
}),
roomInviteDanger: (): IToast => ({
type: 'danger',
title: '방 초대',
description: '초대 메세지 전송 실패했습니다!',
}),
roomLimitOverDanger: (): IToast => ({
type: 'danger',
title: '방 접속 실패',
description: '입장 가능 인원수가 초과되어 입장이 불가능 합니다',
}),
roomCreateSuccess: (): IToast => ({
roomEnterSuccess: (): IToast => ({
type: 'success',
title: '방 생성',
description: '성공적으로 방이 생성됐습니다!',
title: '방 접속',
description: '성공적으로 방에 접속했습니다!',
}),
roomCreateDanger: (): IToast => ({
type: 'danger',
Expand Down
30 changes: 16 additions & 14 deletions client/src/hooks/useRtc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,31 +125,33 @@ export const useRtc = <T extends IRTC>(): [
const init = async () => {
try {
await getLocalStream();
if (!myStreamRef.current) throw new Error('NOT_ALLOW_MIC');
socket.emit(roomSocketMessage.join, {
roomDocumentId, userDocumentId: user.userDocumentId, socketId: socket!.id, isAnonymous,
});
setToastList(toastMessage.roomCreateSuccess());
setToastList(toastMessage.roomEnterSuccess());
} catch (error) {
console.error(error);
setToastList(toastMessage.roomAllowMicDanger());
setToastList(toastMessage.roomCreateDanger());
setRoomView('createRoomView');
}
};

init();

socket.on(roomSocketMessage.join, async (participantsInfo: Array<T>) => {
participantsInfo.forEach(async (participant: T) => {
if (!myStreamRef.current) return;
const peerConnection = setPeerConnection(participant, socket);
if (!(peerConnection && socket)) return;
peerConnectionsRef.current = { ...peerConnectionsRef.current, [participant.socketId as string]: peerConnection };
const offer = await peerConnection.createOffer();
peerConnection.setLocalDescription(offer);

socket.emit(roomSocketMessage.offer, offer, participant.socketId);
});
try {
participantsInfo.forEach(async (participant: T) => {
if (!myStreamRef.current) return;
const peerConnection = setPeerConnection(participant, socket);
if (!(peerConnection && socket)) return;
peerConnectionsRef.current = { ...peerConnectionsRef.current, [participant.socketId as string]: peerConnection };
const offer = await peerConnection.createOffer();
peerConnection.setLocalDescription(offer);

socket.emit(roomSocketMessage.offer, offer, participant.socketId);
});
} catch (error) {
console.error(error);
}
});

// eslint-disable-next-line @typescript-eslint/no-shadow
Expand Down
24 changes: 24 additions & 0 deletions server/src/api/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import imageUpload from '@middlewares/image-upload';

const userRouter = Router();

let allowGuest = false;

export default (app: Router) => {
app.use('/user', userRouter);

Expand Down Expand Up @@ -128,6 +130,22 @@ export default (app: Router) => {
}
});

userRouter.get('/signin/guest', async (req: Request, res: Response) => {
const result = await authService.getGuestInfo();
if (result.ok) {
const { email, password } = result as { email: string, password: string };
const authResult = await authService.signIn(email, password);
if (authResult?.ok) {
res.status(200).json({
accessToken: authResult.accessToken,
ok: authResult.ok,
});
}
return;
}
res.json({ ok: false });
});

userRouter.post('/signup/mail', async (req: Request, res: Response) => {
const { email } = req.body;

Expand Down Expand Up @@ -188,4 +206,10 @@ export default (app: Router) => {
res.json({ ok: false, isUnique: false });
}
});

userRouter.get('/easterEgg/guest', (req: Request, res: Response) => {
const { change } = req.query;
if (change) allowGuest = !allowGuest;
res.json({ allowGuest });
});
};
20 changes: 19 additions & 1 deletion server/src/services/user/auth-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,27 @@ class AuthService {

async signup(info: ISignupUserInfo) {
try {
await Users.insertMany([info]);
const newUsers = await Users.insertMany([info]);
return newUsers[0];
} catch (error) {
console.error(error);
throw Error('signup error');
}
}

async getGuestInfo() {
try {
const guestInfo = {
loginType: 'normal',
userId: `guest${String(Math.floor(Math.random() * 9999))}`,
password: 'nogariguest',
userName: `guest${String(Math.floor(Math.random() * 9999))}`,
userEmail: `guest${String(Math.floor(Math.random() * 9999))}@nogari.dev`,
};
const newInfo = await this.signup(guestInfo);
return { ok: true, email: newInfo.userEmail, password: 'nogariguest' };
} catch (e) {
return { ok: false };
}
}

Expand Down
Loading

0 comments on commit c389de9

Please sign in to comment.