Commit 9886e7d1 authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

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

parents 84926f50 5de58303
......@@ -7,6 +7,7 @@ import catchErrors from '../utils/catchErrors';
function Chat(props) {
const [sender, setSender] = useState([])
const [roomName, setRoomName] = useState('')
const [inner, setInner] = useState([''])
const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지
......@@ -16,6 +17,7 @@ function Chat(props) {
const [user, setUser] = useState('')
const [error, setError] = useState('');
const userId = isAuthenticated()
async function getProfile(userId) {
try {
......@@ -26,6 +28,16 @@ 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) {
e.preventDefault()
setInner(e.target.value)
......@@ -43,6 +55,12 @@ function Chat(props) {
setInner('')
setDisabled(true)
}
function handleClick() {
setChat([])
props.handleChatc()
}
useEffect(() => {
getProfile(userId)
}, [userId])
......@@ -59,12 +77,24 @@ function Chat(props) {
setChat([...chat, props.recievedMsg])
}, [props.recievedMsg])
useEffect(() => {
getRoomName(props.roomCode)
}, [props.roomCode])
const time = new Date().toLocaleTimeString()
return (
<>
<Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
<h2>해당 방에 대한 참여코드는 {props.roomCode} 입니다.</h2>
{/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */}
<Row class="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}>
<Col md="auto">
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
</Col>
<Col>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
<Row > {props.roomCode} </Row>
</Col>
</Row>
<p>{props.newUser}님이 입장하셨습니다.</p>
{chat.map((value, index) => {
if (!(value == '')) {
if (!(sender[index] === user.nickname)) {
......@@ -98,8 +128,7 @@ function Chat(props) {
})
}
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<Button variant="light" onClick={handleClick} >{`<`}</Button>
</Container >
<Form onSubmit={sendMsgCH} fluid>
......
......@@ -8,7 +8,7 @@ function ClosedList(props) {
useEffect(() => {
getClosedList();
}, []);
}, [props.roomCode]);
async function getClosedList() {
const userid = sessionStorage.getItem('userId')
......@@ -18,16 +18,16 @@ function ClosedList(props) {
function enterChatRoomCH(e) {
const roomCode = e.target.name
const roomName = e.target.value
props.enterChatRoom(roomCode)
props.setRoomCode(roomCode)
}
return (
<div>
{list.map((item, index) =>
<ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}>
{item.roomName}
</ListGroup.Item>
</ListGroup>
......
......@@ -8,6 +8,9 @@ function EnterRoom(props) {
const [enterCode, setEnterCode] = useState('');
const [error, setError] = useState('');
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
function handleChange(event) {
const { name, value } = event.target
setEnterCode(value)
......@@ -19,6 +22,7 @@ function EnterRoom(props) {
try {
setError('')
let res = await axios.post('/room/enterRoom', { enterCode })
await axios.put('/room/member', { userId: userId, roomId: enterCode })
props.setRoomName(res.data)
props.enterChatRoom(enterCode)
props.handleCloseEnter()
......
......@@ -16,7 +16,7 @@ function Menu() {
<Nav className="mr-auto">
<Nav.Link href="/profile">Profile</Nav.Link>
</Nav>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light" className="ml-3">Logout</Button>
<Button className="ml-auto" onClick={() => handleLogout()} variant="light">Logout</Button>
</>
: <Nav className="ml-auto">
<Nav.Link href='/login'>로그인</Nav.Link>
......
......@@ -3,11 +3,11 @@ import { ListGroup } from 'react-bootstrap';
import axios from 'axios'
function OpenList(props) {
const [openlist, setOpenlist] = useState([]);
const [openlist, setOpenlist] = useState([])
useEffect(() => {
getOpenList();
}, []);
}, [props.roomCode]);
async function getOpenList() {
let res = await axios.get('/room/openlist')
......@@ -16,8 +16,10 @@ function OpenList(props) {
function enterChatRoomCH(e) {
console.log('e확인', e.target)
const roomCode = e.target.name
props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
// props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
props.openListroom(roomCode)
props.setRoomCode(roomCode)
// props.clearChat()
}
......
......@@ -34,6 +34,7 @@ function RoomMake(props) {
const Id = res.data.roomId
alert(`방암호는 ${Id}입니다`)
props.handleCloseModal()
props.handleChato()
setRoom(INIT_ROOM)
} catch (error){
catchErrors(error, setError)
......
......@@ -9,18 +9,32 @@ import { io } from "socket.io-client"; //모듈 가져오기
import Chat from "../Components/Chat";
import RoomMake from "../Components/RoomMake"
import EnterRoom from "../Components/EnterRoom"
import axios from 'axios';
const socket = io();
const INIT_ROOM = {
roomName: '',
interest: '',
roomId: '',
member: '',
}
function Home() {
const userName = sessionStorage.getItem('name')
const [showModal, setShowModal] = useState(false);
const [showEnter, setEnter] = useState(false);
const [chat, setChat] = useState(false);
const [open, setOpen] = useState(false);
const [room, setRoom] = useState(INIT_ROOM)
const [show, setShow] = useState(true)
//소켓
const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('')
const [roomCode, setRoomCode] = useState('')
const [newUser, setNewUser] = useState('')
const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('')
......@@ -28,8 +42,13 @@ function Home() {
const [singleImg, setSingleImg] = useState('')
const [recievedImg, setRecievedImg] = useState('')
//방참가
//SOCKET 관련 시작
function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`)
}
const [roomName, setRoomName] = useState('')
const handleCloseModal = () => setShowModal(false);
......@@ -39,14 +58,35 @@ function Home() {
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
socket.on("sendUser", (data) => {
setNewUser(data)
})
//오픈채팅방에서 참가하기
async function openListroom(roomId) {
console.log(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])
setShow(false)
}
//SOCKET 관련 시작
function enterChatRoom(rName) { //방 입장하기
socket.emit('joinRoom', rName)
console.log(`joinRoom : ${rName} 입장`)
async function attendListRoom() {
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
const roomId = room.roomId
const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
if (tf.data) {
alert('참가되었습니다.')
} else {
alert('이미 참가된 방입니다.')
}
}
function enterButton() {
setOpen(false)
}
const sendMsg = (e) => {
e.preventDefault()
}
......@@ -56,7 +96,11 @@ function Home() {
if (!(singleChat == '')) {
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: { msg: singleChat, sender: singleUser, img: singleImg },
sendInfo: {
msg: singleChat,
sender: singleUser,
img: singleImg
}
})
setSingleChat([''])
}
......@@ -71,9 +115,6 @@ function Home() {
})
}, [])
return (
<>
<Menu />
......@@ -81,29 +122,46 @@ function Home() {
<Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
<ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} />
</Tab>
<Tab eventKey="open" title="공개방" onClick={handleChato}>
<OpenList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
<OpenList enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} />
</Tab>
</Tabs>
</Col>
<Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleImg={singleImg} setSingleImg={setSingleImg} recievedImg={recievedImg} singleUser={singleUser} setSingleUser={setSingleUser} recievedUser={recievedUser} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomCode={roomCode} /> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>
생성
</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>
참가
</Button>
{show ? <>
{chat ?
<Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} newUser={newUser} setSingleChat={setSingleChat} roomCode={roomCode} singleImg={singleImg} setSingleImg={setSingleImg} recievedImg={recievedImg} singleUser={singleUser} setSingleUser={setSingleUser} recievedUser={recievedUser} />
: <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
</div>}
</> : <>
{open ?
<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="mt-5 p-5 shadow w-75">
<h2 className="d-flex justify-content-center mb-3">현재 {room.roomName} 입니다.</h2>
<h5> 관심분야 : {room.interest}</h5>
<h5> 참여인원 : {room.member.length}</h5>
<h5 className="mb-3"> 방코드(방코드를 통해서도 참여할 있습니다.) : {room.roomId}</h5>
<Row className='justify-content-center'>
<Button variant="outline-warning" size="sm" className="mr-4" onClick={enterButton}>뒤로가기</Button>
<Button variant="outline-warning" size="sm" className="ml-4" type='submit' onClick={attendListRoom}>참가</Button>
</Row>
</div>
</div>
</div> :
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
<Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
</div>}
</>}
</Col>
</Row>
<RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
<EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomName={setRoomName} />
<EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName} />
</>
);
}
......
......@@ -7,8 +7,7 @@ const nanoid = customAlphabet('1234567890abcdef', 10)
const makeRoom = async (req, res) => {
console.log(req.body)
const { roomName, interest, isOpen, member } = req.body;
console.log('콘솔확인',roomName, interest, isOpen, member)
console.log('콘솔확인', roomName, interest, isOpen, member)
const roomId = nanoid()
const room = await Room.findOne({ roomId })
while (room) {
......@@ -39,7 +38,7 @@ const makeRoom = async (req, res) => {
const getClosedList = async (req, res) => {
try {
console.log('req확인',req.query._id)
console.log('req확인', req.query._id)
let list = await Room.find({ member: [req.query._id] })
console.log('c_list가져오기', list)
return res.json(list)
......@@ -51,11 +50,57 @@ const getClosedList = async (req, res) => {
const getOpenList = async (req, res) => {
try {
let list = await Room.find({ isOpen: true })
console.log('o_list가져오기', list)
console.log('o_list가져오기', list.roomName)
return res.json(list)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
}
}
export default { makeRoom, getClosedList, getOpenList }
const getRoomName = async (req, res) => {
const roomId = req.query.roomCode
console.log(req.query.roomCode)
try {
let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
console.log(roominfo.roomName)
return res.json(roominfo.roomName)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
}
}
const changemember = async (req, res) => {
const { userId, roomId } = req.body
console.log(roomId)
let room = await Room.findOne({ roomId: roomId }).select('member')
const isPresent = room.member.indexOf(userId)
try {
if (isPresent<0) {
const memberId = room.member.push(userId)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log('room.member 업데이트 완료')
return res.json(true)
}
else {
return res.json(false)
}
res.end()
} catch (error) {
res.status(500).send('멤버 업데이트 실패')
}
}
const roomInf = async (req, res) => {
try {
console.log(req.query.roomId)
// let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec()
let roomInf = await Room.find({ roomId: req.query.roomId })
console.log('room_member로 정보 가져오기:', roomInf)
return res.json(roomInf)
} catch (error) {
alert('올바르지 못한 접근입니다.')
}
}
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf }
......@@ -5,7 +5,6 @@ const roomEnter = async (req, res) => {
// console.log(req)
try {
console.log(roomId)
const room = await Room.findOne({ roomId })
if (!room) {
return res.status(404).send(`참여코드가 존재하지 않습니다.`)
......
......@@ -4,16 +4,18 @@ const { String } = mongoose.Schema.Types
const ChatSchema = new mongoose.Schema({
room: {
type: ObjectId,
type: mongoose.ObjectId,
required: true,
ref: 'Room',
},
username: {
type: String,
required: true,
ref: 'User',
},
message: String,
message: {
type: String,
required: true
},
}, {
timestamps: true
})
......
......@@ -16,7 +16,7 @@ const RoomSchema = new mongoose.Schema({
interest: {
type: String,
required: true,
select: false
// select: false
},
isOpen: {
type: Boolean,
......
......@@ -6,9 +6,19 @@ const router = express.Router()
router.route('/room/makeRoom')
.post(roomCtrl.makeRoom)
router.route('/room/changeMem')
.put(roomCtrl.changemember)
.get(roomCtrl.roomInf)
router.route('/room/closedlist')
.get(roomCtrl.getClosedList)
router.route('/room/openlist')
.get(roomCtrl.getOpenList)
router.route('/room/member')
.put(roomCtrl.changemember)
router.route('/room/getRoomName')
.get(roomCtrl.getRoomName)
export default router
\ No newline at end of file
......@@ -8,6 +8,8 @@ import bodyParser from "body-parser";
import http from "http";
import { Server } from 'socket.io';
import cors from "cors"
import Room from './models/Room.js'
import Chat from "./models/Chat.js"
connectDb()
......@@ -20,17 +22,33 @@ const io = new Server(server)
io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
console.log('join_data확인',data)
let roomInfo=data;
socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
console.log('join_data확인', data)
let roomInfo = data;
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
});
socket.on('chat', (data) => {
socket.on('newUser', (data) => {
console.log('newUser', data)
let userInfo = data.userInfo;
io.to(data.rmIf).emit('sendUser', userInfo)
})
socket.on('chat', async (data) => {
console.log('roomname확인', data)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo ); // sender 제외 특정 방으로
});
const room = await Room.findOne({ roomId: data.roomInfo })
console.log('room이 떴나', room)
const chat = await new Chat({
room: room._id,
username: data.sendInfo.sender,
message: data.sendInfo.msg
}).save()
console.log('resChat확인', chat)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로
});
socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id)
......
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