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 = {
time: ''
}
function Chat(props) {
const [roomName, setRoomName] = useState('')
const [sender, setSender] = useState([])
//const [roomName, setRoomName] = useState('')
const [inner, setInner] = useState([''])
const [chat, setChat] = useState([INIT_CHAT]) //object로 key는 보낸사람 value는 메세지
......@@ -24,8 +26,10 @@ function Chat(props) {
const [user, setUser] = useState('')
const [error, setError] = useState('');
const [exit, setExit] = useState(false);
const userId = isAuthenticated()
async function getProfile(userId) {
try {
const response = await axios.get(`/users/${userId}`)
......@@ -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) {
e.preventDefault()
setInner(e.target.value)
setDisabled(false)
console.log(chat)
//console.log(chat)
}
function sendMsgCH(e) {
......@@ -59,22 +53,21 @@ function Chat(props) {
props.setSingleImg(user.profileimg)
props.setSingleUser(user.nickname)
props.setSingleChat(inner)
props.sendMsg(e)
setInner('')
setDisabled(true)
}
function handleClick() {
props.closeChatRoom(props.roomCode)
props.setRecievedMsg('')
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
console.log('나간시간', realTime, usualTime)
setChat([''])
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
}
function settingtime(hour) {
......@@ -91,11 +84,11 @@ function Chat(props) {
return newhour
}
//이전 채팅 내용에 대한 것 불러오기
//프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
async function getPreviousChat() {
const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
console.log(respond)
const info = respond.data
let intochat = []
......@@ -107,6 +100,13 @@ function Chat(props) {
setChat(intochat)
}
async function exitAndCloseRoom() {
props.exitRoom(props.roomCode)
setExit(false)
props.handleChatc()
}
useEffect(() => {
getProfile(userId)
}, [userId])
......@@ -120,7 +120,6 @@ function Chat(props) {
}, [props.recievedMsg])
useEffect(() => {
getRoomName(props.roomCode)
getPreviousChat()
// console.log('겟 룸네임', chat)
}, [props.roomCode])
......@@ -129,18 +128,26 @@ function Chat(props) {
return (
<>
<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">
<Button variant="light" onClick={handleClick} >{`<`}</Button>
</Col>
<Col>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
<Row > {props.roomCode}</Row>
<Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
<Row > {props.roomCode} </Row>
</Col>
<Col md="auto">
<Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
</Col>
</Row>
{exit ?
<Row>
<Col>퇴장하시겠습니까?</Col>
<Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
</Row>
<p>{props.newUser}님이 입장하셨습니다.</p>
: null}
{chat.map((value, index) => {
if (!(value.msg == '')) {
if (!(value.msg === '')) {
if (!(value.sender === user.nickname)) {
return (
<Row key={index} className='m-1' >
......@@ -156,8 +163,12 @@ function Chat(props) {
</Col>
</Row>
)
} else {
} else if (sender[index] === "") {
return (
{ value }
)
} else {
return ( //내가 보낸 메시지
<Row key={index} className='m-1 justify-content-end'>
<Row className='d-flex flex-wrap-nowrap' >
<Col className='mr-1'>{value.time}</Col>
......@@ -175,7 +186,7 @@ function Chat(props) {
</Container >
<Form onSubmit={sendMsgCH} fluid>
<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>
......
import React, { useState, useEffect } from 'react'
import { Badge, Button, ListGroup } from 'react-bootstrap';
import { Badge, ListGroup } from 'react-bootstrap';
import axios from 'axios'
function ClosedList(props) {
const realTime = new Date().toISOString()
function enterChatRoomCH(e) {
if (props.roomCode) {
props.closeChatRoom(props.roomCode)
}
const roomCode = e.target.name
const roomName = e.target.value
props.enterChatRoom(roomCode)
props.setRoomCode(roomCode)
props.setRoomName(roomName)
// console.log('rrrrrrrrrrrrrrr',props.closedlist)
// console.log('1111111111111111111',props.leaveInfo, typeof(props.leaveInfo))
......@@ -53,8 +55,8 @@ function ClosedList(props) {
// setUnreadnumber(arr)
// // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length)
// }
// }
return (
<div>
......@@ -65,8 +67,9 @@ function ClosedList(props) {
{<Badge className='ml-2' pill variant='danger'>7</Badge>}
</ListGroup.Item>
</ListGroup>
)}
</div>
)
}
</div >
)
}
......
......@@ -8,8 +8,7 @@ function EnterRoom(props) {
const [enterCode, setEnterCode] = useState('');
const [error, setError] = useState('');
const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
const userId = sessionStorage.getItem('userId');
function handleChange(event) {
const { name, value } = event.target
......@@ -23,13 +22,17 @@ function EnterRoom(props) {
setError('')
let res = await axios.post('/room/enterRoom', { 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.setRoomCode(enterCode)
props.setSysmsg(`${userNick}님이 들어왔습니다.`)
props.enterChatRoom(enterCode)
props.handleCloseEnter()
props.handleChato()
setEnterCode('')
} catch (error){
} catch (error) {
catchErrors(error, setError)
}
}
......
......@@ -5,6 +5,10 @@ import axios from 'axios'
function OpenList(props) {
function enterChatRoomCH(e) {
if (props.roomCode){
props.closeChatRoom(props.roomCode)
}
console.log('e확인', e.target)
const roomCode = e.target.name
// props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
......
import React, { useState, useEffect } from 'react'
import React, { useState } from 'react'
import axios from 'axios';
import { Row, Col, Modal, Button, Form, Alert } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors';
......@@ -11,19 +11,13 @@ const INIT_ROOM = {
function RoomMake(props) {
const [room, setRoom] = useState(INIT_ROOM);
const [disabled, setDisabled] = useState(true);
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');
function handleChange(event) {
const { name, value } = event.target
setRoom({ ...room, [name]: value , member})
console.log(room)
setRoom({ ...room, [name]: value, member })
// console.log(room)
}
async function handleSubmit(event) {
......@@ -36,7 +30,7 @@ function RoomMake(props) {
props.handleCloseModal()
props.handleChato()
setRoom(INIT_ROOM)
} catch (error){
} catch (error) {
catchErrors(error, setError)
}
}
......
import React, { useState, useEffect } from 'react';
import { Row, Col, Button } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import { Row, Col, Button, Tabs, Tab } from 'react-bootstrap';
import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList';
import Menu from '../Components/Menu';
......@@ -29,6 +27,7 @@ const INIT_LIST = [{
function Home() {
const userName = sessionStorage.getItem('name')
const userId = sessionStorage.getItem('userId')
const [showModal, setShowModal] = useState(false);
const [showEnter, setShowEnter] = useState(false);
......@@ -41,7 +40,8 @@ function Home() {
const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('')
const [roomCode, setRoomCode] = useState('')
const [newUser, setNewUser] = useState('')
const [sysmsg, setSysmsg] = useState('')
const [roomName, setRoomName] = useState('')
const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('')
......@@ -53,29 +53,33 @@ function Home() {
const [recievedTime, setRecievedTime] = useState('')
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 [openlist, setOpenlist] = useState([])
//SOCKET 관련 시작
function enterChatRoom(rCode) { //방 입장하기
async function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`)
console.log('123123방입ㄴ장')
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
}
const [roomName, setRoomName] = useState('')
const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true);
const handleCloseEnter = () => setShowEnter(false);
const handleShowEnter = () => setShowEnter(true);
const handleChato = () => setChat(true);
const handleChatc = () => setChat(false);
function closeChatRoom(rCode) {
socket.emit('closeRoom', rCode)
console.log(`${rCode}방 보기 중단`)
}
socket.on("sendUser", (data) => {
setNewUser(data)
})
async function exitRoom(roomId) {
await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
console.log(`${roomId}${userId} 탈퇴`)
setRoomCode("")
}
async function getClosedList() {
const userid = sessionStorage.getItem('userId')
......@@ -93,20 +97,19 @@ function Home() {
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])
setOpen(true)
setShow(false)
}
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 })
const response = await axios.get('/users/check', { params: { '_id': userId } })
const userNick = response.data.nickname;
if (tf.data) {
alert('참가되었습니다.')
setSysmsg(`${userNick}님이 들어왔습니다.`)
} else {
alert('이미 참가된 방입니다.')
}
......@@ -125,7 +128,7 @@ function Home() {
}, [roomCode]);
useEffect(() => {
if (!(singleChat == '')) {
if (!(singleChat === "")) {
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: {
......@@ -135,16 +138,31 @@ function Home() {
time: singleTime
}
})
setSingleChat([''])
setSingleChat("")
}
}, [singleChat])
useEffect(() => {
if (!(sysmsg === '')) {
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: {
msg: sysmsg,
sender: "system",
// time: singleTime
}
})
setSysmsg('')
}
}, [sysmsg])
useEffect(() => {
socket.on("sendedMSG", (sendInfo) => {
setRecievedTime(sendInfo.time)
setRecievedImg(sendInfo.img)
setRecievedUser(sendInfo.sender)
setRecievedMsg(sendInfo.msg)
console.log(sendInfo.msg)
})
}, [])
......@@ -153,12 +171,12 @@ function Home() {
<Menu />
<Row className="mr-0">
<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} >
<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 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>
</Tabs>
</Col>
......@@ -172,7 +190,7 @@ function Home() {
</div>
}
{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}
{open ?
<div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
......@@ -194,7 +212,7 @@ function Home() {
</Col>
</Row>
<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 { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'
//import AccessInfo from '../models/AccessInfo.js'
import Chat from "../models/Chat.js"
const nanoid = customAlphabet('1234567890abcdef', 10)
......@@ -39,9 +40,7 @@ const makeRoom = async (req, res) => {
const getClosedList = async (req, res) => {
try {
console.log('req확인', req.query._id)
let list = await Room.find({ member: req.query._id })
// console.log('c_list가져오기', list)
return res.json(list)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
......@@ -51,7 +50,6 @@ const getClosedList = async (req, res) => {
const getOpenList = async (req, res) => {
try {
let list = await Room.find({ isOpen: true })
// console.log('o_list가져오기', list)
return res.json(list)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
......@@ -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 { userId, roomId } = req.body
console.log(roomId)
......@@ -86,7 +103,22 @@ const changemember = async (req, res) => {
else {
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) {
res.status(500).send('멤버 업데이트 실패')
}
......@@ -146,4 +178,4 @@ const dbChat = async (req, res) => {
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,13 +3,13 @@ import isLength from 'validator/lib/isLength.js'
import isEmail from 'validator/lib/isEmail.js'
import bcrypt from "bcryptjs";
import multer from "multer";
import AccessInfo from "../models/AccessInfo.js"
const upload = multer({ dest: 'uploads/' })
const profileUpload = upload.fields([
{ name: 'imageUrl', maxCount: 1 },
])
const signup = async (req, res) => {
const { username, nickname, email, password } = req.body
......@@ -84,6 +84,16 @@ const getProfile = (req, res) => {
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) => {
try {
......@@ -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함
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')
router.route('/room/getRoomName')
.get(roomCtrl.getRoomName)
// router.route('/room/sysMsg')
// .get(roomCtrl.sysMsg)
// router.route('/room/unreadMessage')
// .get(roomCtrl.unreadMessage)
router.route('/room/unreadMessage')
.get(roomCtrl.unreadMessage)
router.route('/room/dbChat')
.get(roomCtrl.dbChat)
router.route('/room/deleteMem')
.put(roomCtrl.deleteUserId)
export default router
......@@ -7,6 +7,10 @@ const router = express.Router()
router.route('/users/signup')
.post(userCtrl.signup)
router.route('/users/check')
.get(userCtrl.checkUser)
router.route(`/users/:userId`)
.get(userCtrl.getProfile)
.put(userCtrl.profileUpload, userCtrl.update)
......
......@@ -28,6 +28,12 @@ io.on("connection", (socket) => { // 기본 연결
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) => {
console.log('newUser', data)
let userInfo = data.userInfo;
......@@ -48,13 +54,12 @@ io.on("connection", (socket) => { // 기본 연결
console.log('resChat확인', chat)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로
console.log('broad cst실핼')
});
socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id)
})
});
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