Commit b6680caf authored by Choi Ga Young's avatar Choi Ga Young
Browse files

x

parent 60e7cb63
...@@ -6,8 +6,6 @@ import catchErrors from '../utils/catchErrors'; ...@@ -6,8 +6,6 @@ import catchErrors from '../utils/catchErrors';
function Chat(props) { function Chat(props) {
// let defaultname = sessionStorage.getItem('name');
const [sender, setSender] = useState([]) const [sender, setSender] = useState([])
const [roomName, setRoomName] = useState('') const [roomName, setRoomName] = useState('')
...@@ -20,7 +18,6 @@ function Chat(props) { ...@@ -20,7 +18,6 @@ function Chat(props) {
const [user, setUser] = useState('') const [user, setUser] = useState('')
const [error, setError] = useState(''); const [error, setError] = useState('');
const userId = isAuthenticated() const userId = isAuthenticated()
async function getProfile(userId) { async function getProfile(userId) {
try { try {
...@@ -40,6 +37,15 @@ function Chat(props) { ...@@ -40,6 +37,15 @@ function Chat(props) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
// async function sysMsg(roomCode) {
// try {
// let res = await axios.get('/room/sysMsg', { params: { 'roomCode': roomCode } })
// console.log('sysmsg', res.data)
// } catch (error) {
// catchErrors(error, setError)
// }
// }
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
...@@ -83,6 +89,7 @@ function Chat(props) { ...@@ -83,6 +89,7 @@ function Chat(props) {
useEffect(() => { useEffect(() => {
getRoomName(props.roomCode) getRoomName(props.roomCode)
sysMsg(props.roomCode)
}, [props.roomCode]) }, [props.roomCode])
const time = new Date().toLocaleTimeString() const time = new Date().toLocaleTimeString()
...@@ -98,7 +105,7 @@ function Chat(props) { ...@@ -98,7 +105,7 @@ function Chat(props) {
<Row > {props.roomCode} </Row> <Row > {props.roomCode} </Row>
</Col> </Col>
</Row> </Row>
<p>{props.newUser}님이 입장하셨습니다.</p>
{chat.map((value, index) => { {chat.map((value, index) => {
if (!(value == '')) { if (!(value == '')) {
if (!(sender[index] === user.nickname)) { if (!(sender[index] === user.nickname)) {
...@@ -135,7 +142,7 @@ function Chat(props) { ...@@ -135,7 +142,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%', position: 'fixed' }} />
<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 { Row, Col, Button } from 'react-bootstrap'; import { Row, Col, Button, Tabs, Tab } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs'; // import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab'; // 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';
...@@ -22,6 +22,7 @@ const INIT_ROOM = { ...@@ -22,6 +22,7 @@ const INIT_ROOM = {
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);
...@@ -34,7 +35,6 @@ function Home() { ...@@ -34,7 +35,6 @@ 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 [singleUser, setSingleUser] = useState('') const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('') const [recievedUser, setRecievedUser] = useState('')
...@@ -44,10 +44,18 @@ function Home() { ...@@ -44,10 +44,18 @@ function Home() {
//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} 입장`) // let res = await axios.get('/users/check', { params: { '_id': userId } })
// console.log('res형태 확인', res.data)
// if (res.data) {
// socket.emit('joinRoom', rCode)
// } else {
// socket.emit('joinRoom', rCode)
// socket.emit('access', { rmIf: rCode, userInfo: userId })
// }
// console.log(`joinRoom : ${rCode} 입장`)
} }
const [roomName, setRoomName] = useState('') const [roomName, setRoomName] = useState('')
...@@ -58,9 +66,10 @@ function Home() { ...@@ -58,9 +66,10 @@ function Home() {
const handleChato = () => setChat(true); const handleChato = () => setChat(true);
const handleChatc = () => setChat(false); const handleChatc = () => setChat(false);
socket.on("sendUser", (data) => { // socket.on("sendUser", (data) => {
setNewUser(data) // setNewUser(data)
}) // })
//오픈채팅방에서 참가하기 //오픈채팅방에서 참가하기
async function openListroom(roomId) { async function openListroom(roomId) {
......
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'
const nanoid = customAlphabet('1234567890abcdef', 10) const nanoid = customAlphabet('1234567890abcdef', 10)
...@@ -38,9 +39,8 @@ const makeRoom = async (req, res) => { ...@@ -38,9 +39,8 @@ 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) // 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('리스트 불러오기를 실패하였습니다!')
...@@ -50,7 +50,7 @@ const getClosedList = async (req, res) => { ...@@ -50,7 +50,7 @@ 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) // 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('리스트 불러오기를 실패하였습니다!')
...@@ -70,13 +70,32 @@ const getRoomName = async (req, res) => { ...@@ -70,13 +70,32 @@ 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)
let room = await Room.findOne({ roomId: roomId }).select('member') let room = await Room.findOne({ roomId: roomId }).select('member')
const isPresent = room.member.indexOf(userId) const isPresent = room.member.indexOf(userId)
try { try {
if (isPresent<0) { if (isPresent < 0) {
const memberId = room.member.push(userId) const memberId = room.member.push(userId)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member }) await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log('room.member 업데이트 완료') console.log('room.member 업데이트 완료')
...@@ -103,4 +122,4 @@ const roomInf = async (req, res) => { ...@@ -103,4 +122,4 @@ const roomInf = async (req, res) => {
} }
} }
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf } export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, /*{sysMsg}*/ }
...@@ -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,17 @@ const getProfile = (req, res) => { ...@@ -84,6 +84,17 @@ const getProfile = (req, res) => {
res.json(req.user) res.json(req.user)
} }
const checkUser = async (req, res) => {
try {
const info = await AccessInfo.findOne({ userInfo: 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 +105,5 @@ const loginNavbar = async (req, res) => { ...@@ -94,5 +105,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
...@@ -21,4 +21,7 @@ router.route('/room/member') ...@@ -21,4 +21,7 @@ router.route('/room/member')
router.route('/room/getRoomName') router.route('/room/getRoomName')
.get(roomCtrl.getRoomName) .get(roomCtrl.getRoomName)
export default router
\ No newline at end of file // router.route('/room/sysMsg')
// .get(roomCtrl.sysMsg)
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)
......
...@@ -10,6 +10,8 @@ import { Server } from 'socket.io'; ...@@ -10,6 +10,8 @@ import { Server } from 'socket.io';
import cors from "cors" import cors from "cors"
import Room from './models/Room.js' import Room from './models/Room.js'
import Chat from "./models/Chat.js" import Chat from "./models/Chat.js"
import User from "./models/User.js"
import AccessInfo from "./models/AccessInfo.js"
connectDb() connectDb()
...@@ -28,11 +30,20 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -28,11 +30,20 @@ io.on("connection", (socket) => { // 기본 연결
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴 socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
}); });
socket.on('newUser', (data) => { // socket.on('access', async (data) => {
console.log('newUser', data) // console.log('access', data)
let userInfo = data.userInfo; // const nick = await User.findOne({ _id: data.userInfo }).select('nickname').exec()
io.to(data.rmIf).emit('sendUser', userInfo) // const room = await Room.findOne({ roomId: data.rmIf })
}) // console.log('room확인2', room)
// //console.log('nick확인', nick) //{ _id: 5ffe897927a051f4bc17bbcc, nickname: 'rkyoung1' }
// const accessInfo = await new AccessInfo({
// room: room._id,
// userInfo: data.userInfo,
// nickname: nick.nickname,
// isEnt: true
// }).save()
// console.log('acc확인', accessInfo)
// })
socket.on('chat', async (data) => { socket.on('chat', async (data) => {
console.log('roomname확인', data) console.log('roomname확인', data)
......
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