Commit 4c23bf1f authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

Merge remote-tracking branch 'origin/young' into yeonwoo

parents 04d0fdb6 9d342b6c
...@@ -12,7 +12,9 @@ const INIT_CHAT = { ...@@ -12,7 +12,9 @@ const INIT_CHAT = {
time: '' time: ''
} }
function Chat(props) { function Chat(props) {
const [roomName, setRoomName] = useState('') const [sender, setSender] = useState([])
//const [roomName, setRoomName] = useState('')
const [inner, setInner] = useState(['']) const [inner, setInner] = useState([''])
const [chat, setChat] = useState([INIT_CHAT]) //object로 key는 보낸사람 value는 메세지 const [chat, setChat] = useState([INIT_CHAT]) //object로 key는 보낸사람 value는 메세지
...@@ -24,8 +26,10 @@ function Chat(props) { ...@@ -24,8 +26,10 @@ function Chat(props) {
const [user, setUser] = useState('') const [user, setUser] = useState('')
const [error, setError] = useState(''); const [error, setError] = useState('');
const [exit, setExit] = useState(false);
const userId = isAuthenticated() const userId = isAuthenticated()
async function getProfile(userId) { async function getProfile(userId) {
try { try {
const response = await axios.get(`/users/${userId}`) const response = await axios.get(`/users/${userId}`)
...@@ -35,21 +39,11 @@ function Chat(props) { ...@@ -35,21 +39,11 @@ function Chat(props) {
} }
} }
async function getRoomName(roomCode) {
try {
let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
console.log(res.data)
setRoomName(res.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
setInner(e.target.value) setInner(e.target.value)
setDisabled(false) setDisabled(false)
console.log(chat) //console.log(chat)
} }
function sendMsgCH(e) { function sendMsgCH(e) {
...@@ -59,22 +53,21 @@ function Chat(props) { ...@@ -59,22 +53,21 @@ function Chat(props) {
props.setSingleImg(user.profileimg) props.setSingleImg(user.profileimg)
props.setSingleUser(user.nickname) props.setSingleUser(user.nickname)
props.setSingleChat(inner) props.setSingleChat(inner)
props.sendMsg(e) props.sendMsg(e)
setInner('') setInner('')
setDisabled(true) setDisabled(true)
} }
function handleClick() { function handleClick() {
props.closeChatRoom(props.roomCode)
props.setRecievedMsg('') props.setRecievedMsg('')
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
console.log('나간시간', realTime, usualTime)
setChat(['']) setChat([''])
props.handleChatc() props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }]) props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
} }
function settingtime(hour) { function settingtime(hour) {
...@@ -91,11 +84,11 @@ function Chat(props) { ...@@ -91,11 +84,11 @@ function Chat(props) {
return newhour return newhour
} }
//이전 채팅 내용에 대한 것 불러오기 //이전 채팅 내용에 대한 것 불러오기
//프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식 //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
async function getPreviousChat() { async function getPreviousChat() {
const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } }) const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
console.log(respond)
const info = respond.data const info = respond.data
let intochat = [] let intochat = []
...@@ -107,6 +100,13 @@ function Chat(props) { ...@@ -107,6 +100,13 @@ function Chat(props) {
setChat(intochat) setChat(intochat)
} }
async function exitAndCloseRoom() {
props.exitRoom(props.roomCode)
setExit(false)
props.handleChatc()
}
useEffect(() => { useEffect(() => {
getProfile(userId) getProfile(userId)
}, [userId]) }, [userId])
...@@ -120,7 +120,6 @@ function Chat(props) { ...@@ -120,7 +120,6 @@ function Chat(props) {
}, [props.recievedMsg]) }, [props.recievedMsg])
useEffect(() => { useEffect(() => {
getRoomName(props.roomCode)
getPreviousChat() getPreviousChat()
// console.log('겟 룸네임', chat) // console.log('겟 룸네임', chat)
}, [props.roomCode]) }, [props.roomCode])
...@@ -129,18 +128,26 @@ function Chat(props) { ...@@ -129,18 +128,26 @@ function Chat(props) {
return ( return (
<> <>
<Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}> <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
<Row className="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}> <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
<Col md="auto"> <Col md="auto">
<Button variant="light" onClick={handleClick} >{`<`}</Button> <Button variant="light" onClick={handleClick} >{`<`}</Button>
</Col> </Col>
<Col> <Col>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row> <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
<Row > {props.roomCode}</Row> <Row > {props.roomCode} </Row>
</Col>
<Col md="auto">
<Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
</Col> </Col>
</Row> </Row>
<p>{props.newUser}님이 입장하셨습니다.</p> {exit ?
<Row>
<Col>퇴장하시겠습니까?</Col>
<Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
</Row>
: null}
{chat.map((value, index) => { {chat.map((value, index) => {
if (!(value.msg == '')) { if (!(value.msg === '')) {
if (!(value.sender === user.nickname)) { if (!(value.sender === user.nickname)) {
return ( return (
<Row key={index} className='m-1' > <Row key={index} className='m-1' >
...@@ -156,8 +163,12 @@ function Chat(props) { ...@@ -156,8 +163,12 @@ function Chat(props) {
</Col> </Col>
</Row> </Row>
) )
} else { } else if (sender[index] === "") {
return ( return (
{ value }
)
} else {
return ( //내가 보낸 메시지
<Row key={index} className='m-1 justify-content-end'> <Row key={index} className='m-1 justify-content-end'>
<Row className='d-flex flex-wrap-nowrap' > <Row className='d-flex flex-wrap-nowrap' >
<Col className='mr-1'>{value.time}</Col> <Col className='mr-1'>{value.time}</Col>
...@@ -175,7 +186,7 @@ function Chat(props) { ...@@ -175,7 +186,7 @@ function Chat(props) {
</Container > </Container >
<Form onSubmit={sendMsgCH} fluid> <Form onSubmit={sendMsgCH} fluid>
<Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'> <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
<Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} /> <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%'}} />
<Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}> <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
전송 전송
</Button> </Button>
......
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { Badge, Button, ListGroup } from 'react-bootstrap'; import { Badge, ListGroup } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
function ClosedList(props) { function ClosedList(props) {
const realTime = new Date().toISOString()
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
if (props.roomCode) {
props.closeChatRoom(props.roomCode)
}
const roomCode = e.target.name const roomCode = e.target.name
const roomName = e.target.value const roomName = e.target.value
props.enterChatRoom(roomCode) props.enterChatRoom(roomCode)
props.setRoomCode(roomCode) props.setRoomCode(roomCode)
props.setRoomName(roomName)
// console.log('rrrrrrrrrrrrrrr',props.closedlist) // console.log('rrrrrrrrrrrrrrr',props.closedlist)
// console.log('1111111111111111111',props.leaveInfo, typeof(props.leaveInfo)) // console.log('1111111111111111111',props.leaveInfo, typeof(props.leaveInfo))
...@@ -53,8 +55,8 @@ function ClosedList(props) { ...@@ -53,8 +55,8 @@ function ClosedList(props) {
// setUnreadnumber(arr) // setUnreadnumber(arr)
// // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length) // // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length)
// }
// }
return ( return (
<div> <div>
...@@ -65,9 +67,10 @@ function ClosedList(props) { ...@@ -65,9 +67,10 @@ function ClosedList(props) {
{<Badge className='ml-2' pill variant='danger'>7</Badge>} {<Badge className='ml-2' pill variant='danger'>7</Badge>}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
)} )
</div> }
</div >
) )
} }
export default ClosedList export default ClosedList
\ No newline at end of file
...@@ -8,28 +8,31 @@ function EnterRoom(props) { ...@@ -8,28 +8,31 @@ function EnterRoom(props) {
const [enterCode, setEnterCode] = useState(''); const [enterCode, setEnterCode] = useState('');
const [error, setError] = useState(''); const [error, setError] = useState('');
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴 const userId = sessionStorage.getItem('userId');
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setEnterCode(value) setEnterCode(value)
console.log(enterCode) console.log(enterCode)
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
try { try {
setError('') setError('')
let res = await axios.post('/room/enterRoom', { enterCode }) let res = await axios.post('/room/enterRoom', { enterCode })
await axios.put('/room/member', { userId: userId, roomId: enterCode }) await axios.put('/room/member', { userId: userId, roomId: enterCode })
const response = await axios.get('/users/check', { params: { '_id': userId } })
// console.log('res확인22', response.data.nickname)
const userNick = response.data.nickname;
props.setRoomName(res.data) props.setRoomName(res.data)
props.setRoomCode(enterCode) props.setRoomCode(enterCode)
props.setSysmsg(`${userNick}님이 들어왔습니다.`)
props.enterChatRoom(enterCode) props.enterChatRoom(enterCode)
props.handleCloseEnter() props.handleCloseEnter()
props.handleChato() props.handleChato()
setEnterCode('') setEnterCode('')
} catch (error){ } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
......
...@@ -5,6 +5,10 @@ import axios from 'axios' ...@@ -5,6 +5,10 @@ import axios from 'axios'
function OpenList(props) { function OpenList(props) {
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
if (props.roomCode){
props.closeChatRoom(props.roomCode)
}
console.log('e확인', e.target) console.log('e확인', e.target)
const roomCode = e.target.name const roomCode = e.target.name
// props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함 // props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
......
import React, { useState, useEffect } from 'react' import React, { useState } from 'react'
import axios from 'axios'; import axios from 'axios';
import { Row, Col, Modal, Button, Form, Alert } from 'react-bootstrap'; import { Row, Col, Modal, Button, Form, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
...@@ -11,19 +11,13 @@ const INIT_ROOM = { ...@@ -11,19 +11,13 @@ const INIT_ROOM = {
function RoomMake(props) { function RoomMake(props) {
const [room, setRoom] = useState(INIT_ROOM); const [room, setRoom] = useState(INIT_ROOM);
const [disabled, setDisabled] = useState(true);
const [error, setError] = useState(''); const [error, setError] = useState('');
useEffect(() => {
const isRoom = Object.values(room).every(el => Boolean(el))
isRoom ? setDisabled(false) : setDisabled(true)
}, [room])
const member = sessionStorage.getItem('userId'); const member = sessionStorage.getItem('userId');
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setRoom({ ...room, [name]: value , member}) setRoom({ ...room, [name]: value, member })
console.log(room) // console.log(room)
} }
async function handleSubmit(event) { async function handleSubmit(event) {
...@@ -36,7 +30,7 @@ function RoomMake(props) { ...@@ -36,7 +30,7 @@ function RoomMake(props) {
props.handleCloseModal() props.handleCloseModal()
props.handleChato() props.handleChato()
setRoom(INIT_ROOM) setRoom(INIT_ROOM)
} catch (error){ } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
......
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Row, Col, Button } from 'react-bootstrap'; import { Row, Col, Button, Tabs, Tab } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import ClosedList from '../Components/ClosedList'; import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList'; import OpenList from '../Components/OpenList';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
...@@ -29,6 +27,7 @@ const INIT_LIST = [{ ...@@ -29,6 +27,7 @@ const INIT_LIST = [{
function Home() { function Home() {
const userName = sessionStorage.getItem('name') const userName = sessionStorage.getItem('name')
const userId = sessionStorage.getItem('userId')
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [showEnter, setShowEnter] = useState(false); const [showEnter, setShowEnter] = useState(false);
...@@ -41,7 +40,8 @@ function Home() { ...@@ -41,7 +40,8 @@ function Home() {
const [singleChat, setSingleChat] = useState('') const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('') const [recievedMsg, setRecievedMsg] = useState('')
const [roomCode, setRoomCode] = useState('') const [roomCode, setRoomCode] = useState('')
const [newUser, setNewUser] = useState('') const [sysmsg, setSysmsg] = useState('')
const [roomName, setRoomName] = useState('')
const [singleUser, setSingleUser] = useState('') const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('') const [recievedUser, setRecievedUser] = useState('')
...@@ -53,29 +53,33 @@ function Home() { ...@@ -53,29 +53,33 @@ function Home() {
const [recievedTime, setRecievedTime] = useState('') const [recievedTime, setRecievedTime] = useState('')
const [leaveInfo, setLeaveInfo] = useState([{ roomName: "", leaveTime: "" }]) const [leaveInfo, setLeaveInfo] = useState([{ roomName: "", leaveTime: "" }])
const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true);
const handleCloseEnter = () => setShowEnter(false);
const handleShowEnter = () => setShowEnter(true);
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
const [closedlist, setClosedList] = useState(INIT_LIST); const [closedlist, setClosedList] = useState(INIT_LIST);
const [openlist, setOpenlist] = useState([]) const [openlist, setOpenlist] = useState([])
//SOCKET 관련 시작 //SOCKET 관련 시작
function enterChatRoom(rCode) { //방 입장하기 async function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode) socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName }) socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`) console.log(`joinRoom : ${rCode} 입장`)
console.log('123123방입ㄴ장')
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데 //여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
} }
const [roomName, setRoomName] = useState('')
const handleCloseModal = () => setShowModal(false); function closeChatRoom(rCode) {
const handleShowModal = () => setShowModal(true); socket.emit('closeRoom', rCode)
const handleCloseEnter = () => setShowEnter(false); console.log(`${rCode}방 보기 중단`)
const handleShowEnter = () => setShowEnter(true); }
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
socket.on("sendUser", (data) => { async function exitRoom(roomId) {
setNewUser(data) await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
}) console.log(`${roomId}${userId} 탈퇴`)
setRoomCode("")
}
async function getClosedList() { async function getClosedList() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
...@@ -93,20 +97,19 @@ function Home() { ...@@ -93,20 +97,19 @@ function Home() {
async function openListroom(roomId) { async function openListroom(roomId) {
console.log(roomId) console.log(roomId)
const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } }) const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } })
console.log(roomInf)
console.log(roomInf.data)
console.log(roomInf.data[0])
setRoom(roomInf.data[0]) setRoom(roomInf.data[0])
setOpen(true) setOpen(true)
setShow(false) setShow(false)
} }
async function attendListRoom() { async function attendListRoom() {
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
const roomId = room.roomId const roomId = room.roomId
const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId }) const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
const response = await axios.get('/users/check', { params: { '_id': userId } })
const userNick = response.data.nickname;
if (tf.data) { if (tf.data) {
alert('참가되었습니다.') alert('참가되었습니다.')
setSysmsg(`${userNick}님이 들어왔습니다.`)
} else { } else {
alert('이미 참가된 방입니다.') alert('이미 참가된 방입니다.')
} }
...@@ -125,7 +128,7 @@ function Home() { ...@@ -125,7 +128,7 @@ function Home() {
}, [roomCode]); }, [roomCode]);
useEffect(() => { useEffect(() => {
if (!(singleChat == '')) { if (!(singleChat === "")) {
socket.emit("chat", { socket.emit("chat", {
roomInfo: roomCode, roomInfo: roomCode,
sendInfo: { sendInfo: {
...@@ -135,16 +138,31 @@ function Home() { ...@@ -135,16 +138,31 @@ function Home() {
time: singleTime time: singleTime
} }
}) })
setSingleChat(['']) setSingleChat("")
} }
}, [singleChat]) }, [singleChat])
useEffect(() => {
if (!(sysmsg === '')) {
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: {
msg: sysmsg,
sender: "system",
// time: singleTime
}
})
setSysmsg('')
}
}, [sysmsg])
useEffect(() => { useEffect(() => {
socket.on("sendedMSG", (sendInfo) => { socket.on("sendedMSG", (sendInfo) => {
setRecievedTime(sendInfo.time) setRecievedTime(sendInfo.time)
setRecievedImg(sendInfo.img) setRecievedImg(sendInfo.img)
setRecievedUser(sendInfo.sender) setRecievedUser(sendInfo.sender)
setRecievedMsg(sendInfo.msg) setRecievedMsg(sendInfo.msg)
console.log(sendInfo.msg)
}) })
}, []) }, [])
...@@ -153,12 +171,12 @@ function Home() { ...@@ -153,12 +171,12 @@ function Home() {
<Menu /> <Menu />
<Row className="mr-0"> <Row className="mr-0">
<Col className="list" md={5}> <Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example"> <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example" >
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} > <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList closedlist={closedlist} singleChat={singleChat} recievedMsg={recievedMsg} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} /> <ClosedList closedlist={closedlist} singleChat={singleChat} recievedMsg={recievedMsg} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
</Tab> </Tab>
<Tab eventKey="open" title="공개방" onClick={handleChatc}> <Tab eventKey="open" title="공개방" onClick={handleChatc}>
<OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} /> <OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
...@@ -172,9 +190,9 @@ function Home() { ...@@ -172,9 +190,9 @@ function Home() {
</div> </div>
} }
{chat ? {chat ?
<Chat handleChatc={handleChatc} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} singleTime={singleTime} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} recievedTime={recievedTime} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} setSingleTime={setSingleTime} setRecievedMsg={setRecievedMsg} roomCode={roomCode} roomName={roomName} /> <Chat handleChatc={handleChatc} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} singleTime={singleTime} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} recievedTime={recievedTime} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} setSingleTime={setSingleTime} setRecievedMsg={setRecievedMsg} roomCode={roomCode} roomName={roomName} closeChatRoom={closeChatRoom} exitRoom={exitRoom} />
: null} : null}
{open ? {open ?
<div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark"> <div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
<div className="d-flex justify-content-center"> <div className="d-flex justify-content-center">
<div className="mt-5 p-5 shadow w-75"> <div className="mt-5 p-5 shadow w-75">
...@@ -194,7 +212,7 @@ function Home() { ...@@ -194,7 +212,7 @@ function Home() {
</Col> </Col>
</Row> </Row>
<RoomMake showModal={showModal} handleCloseModal={handleCloseModal} /> <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
<EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName} /> <EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName} sysmsg={sysmsg} setSysmsg={setSysmsg} />
</> </>
); );
} }
......
import Room from "../models/Room.js" import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid' import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
//import AccessInfo from '../models/AccessInfo.js'
import Chat from "../models/Chat.js" import Chat from "../models/Chat.js"
const nanoid = customAlphabet('1234567890abcdef', 10) const nanoid = customAlphabet('1234567890abcdef', 10)
...@@ -39,9 +40,7 @@ const makeRoom = async (req, res) => { ...@@ -39,9 +40,7 @@ const makeRoom = async (req, res) => {
const getClosedList = async (req, res) => { const getClosedList = async (req, res) => {
try { try {
console.log('req확인', req.query._id)
let list = await Room.find({ member: req.query._id }) let list = await Room.find({ member: req.query._id })
// console.log('c_list가져오기', list)
return res.json(list) return res.json(list)
} catch (error) { } catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!') res.status(500).send('리스트 불러오기를 실패하였습니다!')
...@@ -51,7 +50,6 @@ const getClosedList = async (req, res) => { ...@@ -51,7 +50,6 @@ const getClosedList = async (req, res) => {
const getOpenList = async (req, res) => { const getOpenList = async (req, res) => {
try { try {
let list = await Room.find({ isOpen: true }) let list = await Room.find({ isOpen: true })
// console.log('o_list가져오기', list)
return res.json(list) return res.json(list)
} catch (error) { } catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!') res.status(500).send('리스트 불러오기를 실패하였습니다!')
...@@ -71,6 +69,25 @@ const getRoomName = async (req, res) => { ...@@ -71,6 +69,25 @@ const getRoomName = async (req, res) => {
} }
} }
// const sysMsg = async (req, res) => {
// try {
// console.log('sysreq', req.query)
// let rmif = await Room.find({ roomId: req.query.roomCode })
// console.log('rmif', rmif)
// let rmid = await AccessInfo.find({ room: rmif._id })
// console.log('rmid', rmid)
// if (rmid.isEnt) {
// let msg = `${rmif.nickname}이 들어왔습니다`
// } else {
// }
// } catch (error) {
// res.status(500).send('')
// }
// }
const changemember = async (req, res) => { const changemember = async (req, res) => {
const { userId, roomId } = req.body const { userId, roomId } = req.body
console.log(roomId) console.log(roomId)
...@@ -86,7 +103,22 @@ const changemember = async (req, res) => { ...@@ -86,7 +103,22 @@ const changemember = async (req, res) => {
else { else {
return res.json(false) return res.json(false)
} }
res.end() } catch (error) {
res.status(500).send('멤버 업데이트 실패')
}
}
const deleteUserId = async (req, res) => {
console.log(req.body)
const { userId, roomId } = req.body
let room = await Room.findOne({ roomId: roomId }).select('member')
console.log('deletetest', room)
const memIndex = room.member.indexOf(userId)
try {
room.member.splice(memIndex, 1)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log(`${roomId}${userId}삭제완료`)
return res.json(true)
} catch (error) { } catch (error) {
res.status(500).send('멤버 업데이트 실패') res.status(500).send('멤버 업데이트 실패')
} }
...@@ -146,4 +178,4 @@ const dbChat = async (req, res) => { ...@@ -146,4 +178,4 @@ const dbChat = async (req, res) => {
res.json(chatlist) res.json(chatlist)
} }
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, dbChat } export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, dbChat, deleteUserId }
...@@ -3,17 +3,17 @@ import isLength from 'validator/lib/isLength.js' ...@@ -3,17 +3,17 @@ import isLength from 'validator/lib/isLength.js'
import isEmail from 'validator/lib/isEmail.js' import isEmail from 'validator/lib/isEmail.js'
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import multer from "multer"; import multer from "multer";
import AccessInfo from "../models/AccessInfo.js"
const upload = multer({ dest: 'uploads/' }) const upload = multer({ dest: 'uploads/' })
const profileUpload = upload.fields([ const profileUpload = upload.fields([
{ name: 'imageUrl', maxCount: 1 }, { name: 'imageUrl', maxCount: 1 },
]) ])
const signup = async (req, res) => { const signup = async (req, res) => {
const { username, nickname, email, password } = req.body const { username, nickname, email, password } = req.body
try { try {
if (!isLength(username, { min: 3, max: 10 })) { if (!isLength(username, { min: 3, max: 10 })) {
return res.status(422).send('이름은 3-10자 사이입니다') return res.status(422).send('이름은 3-10자 사이입니다')
...@@ -84,6 +84,16 @@ const getProfile = (req, res) => { ...@@ -84,6 +84,16 @@ const getProfile = (req, res) => {
res.json(req.user) res.json(req.user)
} }
const checkUser = async (req, res) => {
try {
const info = await User.findOne({ _id: req.query._id })
console.log('info 확인', info)
return res.json(info)
} catch (error) {
console.log(error)
res.status(500).send('사용자 검색 실패')
}
}
const loginNavbar = async (req, res) => { const loginNavbar = async (req, res) => {
try { try {
...@@ -94,5 +104,5 @@ const loginNavbar = async (req, res) => { ...@@ -94,5 +104,5 @@ const loginNavbar = async (req, res) => {
} }
} }
export default { signup, profileUpload, update, userById, getProfile, loginNavbar } export default { signup, profileUpload, update, userById, getProfile, loginNavbar, checkUser }
// {} : 객체로 return함 // {} : 객체로 return함
import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types
const AccessInfoSchema = new mongoose.Schema({
room: {
type: mongoose.ObjectId,
required: true,
ref: 'Room',
},
userInfo: {
type: mongoose.ObjectId,
required: true,
unique: true,
ref: 'User',
},
nickname: {
type: String,
required: true,
},
isEnt: {
type: Boolean,
required: true,
default: true, // 입장 시 true, 퇴장 시 false
}
}, {
timestamps: true
})
export default mongoose.models.AccessInfo || mongoose.model('AccessInfo', AccessInfoSchema)
\ No newline at end of file
...@@ -22,10 +22,18 @@ router.route('/room/member') ...@@ -22,10 +22,18 @@ router.route('/room/member')
router.route('/room/getRoomName') router.route('/room/getRoomName')
.get(roomCtrl.getRoomName) .get(roomCtrl.getRoomName)
// router.route('/room/sysMsg')
// .get(roomCtrl.sysMsg)
// router.route('/room/unreadMessage')
// .get(roomCtrl.unreadMessage)
router.route('/room/unreadMessage') router.route('/room/unreadMessage')
.get(roomCtrl.unreadMessage) .get(roomCtrl.unreadMessage)
router.route('/room/dbChat') router.route('/room/dbChat')
.get(roomCtrl.dbChat) .get(roomCtrl.dbChat)
export default router router.route('/room/deleteMem')
\ No newline at end of file .put(roomCtrl.deleteUserId)
export default router
...@@ -7,10 +7,14 @@ const router = express.Router() ...@@ -7,10 +7,14 @@ const router = express.Router()
router.route('/users/signup') router.route('/users/signup')
.post(userCtrl.signup) .post(userCtrl.signup)
router.route('/users/check')
.get(userCtrl.checkUser)
router.route(`/users/:userId`) router.route(`/users/:userId`)
.get(userCtrl.getProfile) .get(userCtrl.getProfile)
.put(userCtrl.profileUpload, userCtrl.update) .put(userCtrl.profileUpload, userCtrl.update)
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
......
...@@ -28,6 +28,12 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -28,6 +28,12 @@ io.on("connection", (socket) => { // 기본 연결
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴 socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
}); });
socket.on('closeRoom', (data) => {
console.log('close_data확인', data)
let roomInfo = data;
socket.leave(roomInfo); //클라이언트에서 data에 적힌 room정보를 브로드캐스팅 받지 않는다.
});
socket.on('newUser', (data) => { socket.on('newUser', (data) => {
console.log('newUser', data) console.log('newUser', data)
let userInfo = data.userInfo; let userInfo = data.userInfo;
...@@ -48,13 +54,12 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -48,13 +54,12 @@ io.on("connection", (socket) => { // 기본 연결
console.log('resChat확인', chat) console.log('resChat확인', chat)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로 socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로
console.log('broad cst실핼')
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id) console.log('disconnected from server id=', socket.id)
}) })
}); });
app.use(bodyParser.json()); app.use(bodyParser.json());
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment