Commit 78b14ec0 authored by Choi Ga Young's avatar Choi Ga Young
Browse files

xxxxx

parent 6a3b89dc
......@@ -17,9 +17,6 @@ function Chat(props) {
const usualTime = simpleTime.substring(0, simpleTime.length - 3)
const realTime = new Date().toISOString()
const r = Date.parse(realTime)
const [disabled, setDisabled] = useState(true)
const [user, setUser] = useState('')
const [error, setError] = useState('');
......@@ -43,15 +40,6 @@ const r = Date.parse(realTime)
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) {
e.preventDefault()
......@@ -66,7 +54,6 @@ const r = Date.parse(realTime)
props.setSingleImg(user.profileimg)
props.setSingleUser(user.nickname)
props.setSingleChat(inner)
props.sendMsg(e)
setInner('')
setDisabled(true)
......@@ -81,7 +68,7 @@ const r = Date.parse(realTime)
console.log('chat2', chat)
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
console.log('나간시간',realTime, usualTime)
console.log('나간시간', realTime, usualTime)
}
function settingtime(hour) {
......@@ -98,30 +85,46 @@ const r = Date.parse(realTime)
return newhour
}
//이전 채팅 내용에 대한 것 불러오기
//프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
async function getPreviousChat() {
//메세지, 닉네임, 시간 불러오기
const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
console.log(respond)
const info = respond.data
let chatlist = []
let userlist = []
let timelist = []
let imglist = []
let intlist = []
for (let i = 0; i <= info.length - 1; i++) { //사용하려는 형식에 맞게 수정
chatlist = [...chatlist, info[i].message]
userlist = [...userlist, info[i].username]
//userlist = [...userlist, info[i].username]
if (info[i].username === "system") {
userlist = [...userlist, ""]
intlist.push(i)
// continue;
} else {
userlist = [...userlist, info[i].username]
}
timelist = [...timelist, info[i].createdAt]
// console.log('int', intlist)
// console.log('timelist', timelist)
let hour = timelist[i].split('T')[1].split(':')
timelist[i] = settingtime(hour[0]) + ':' + hour[1]
}
console.log('userlist확인', userlist)
//그 nick에 맞는 프사 불러오기
const respond2 = await axios.get('/room/getProfileImage', { params: { 'userlist': userlist } })
const imginfo = respond2.data
for (let j = 0; j <= imginfo.length - 1; j++) {
imglist = [...imglist, imginfo[j][0].profileimg]
if (intlist.indexOf(j) < 0) {
imglist = [...imglist, imginfo[j][0].profileimg]
} else {
imglist = [...imglist, ""]
}
}
setChat(chatlist)
setSender(userlist)
......@@ -153,7 +156,6 @@ const r = Date.parse(realTime)
useEffect(() => {
getRoomName(props.roomCode)
//sysMsg(props.roomCode)
console.log('겟 룸네임', chat)
}, [props.roomCode])
......@@ -174,7 +176,7 @@ const r = Date.parse(realTime)
{chat.map((value, index) => {
if (!(value == '')) {
if (!(sender[index] === user.nickname)) {
return (
return ( //상대편 메시지
<Row key={index} className='m-1' >
<Col xs={2}>
<Image src={img && `/images/${img[index]}`} style={{ width: "50px", height: "50px" }} roundedCircle />
......@@ -188,8 +190,12 @@ const r = Date.parse(realTime)
</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'>{time[index]}</Col>
......
......@@ -51,7 +51,7 @@ function ClosedList(props) {
<ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}>
{item.roomName}
<Badge className='ml-2' pill variant='danger'>8</Badge>
{/* <Badge className='ml-2' pill variant='danger'>8</Badge> */}
</ListGroup.Item>
</ListGroup>
)}
......
......@@ -8,28 +8,31 @@ 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
setEnterCode(value)
console.log(enterCode)
}
async function handleSubmit(event) {
event.preventDefault()
try {
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)
}
}
......
......@@ -23,7 +23,7 @@ function RoomMake(props) {
function handleChange(event) {
const { name, value } = event.target
setRoom({ ...room, [name]: value , member})
console.log(room)
// console.log(room)
}
async function handleSubmit(event) {
......
......@@ -33,6 +33,7 @@ function Home() {
const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('')
const [roomCode, setRoomCode] = useState('')
const [sysmsg, setSysmsg] = useState('')
const [singleUser, setSingleUser] = useState('')
const [recievedUser, setRecievedUser] = useState('')
......@@ -49,17 +50,7 @@ function Home() {
async function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rCode)
socket.emit('newUser', { rmIf: rCode, userInfo: userName })
// 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} 입장`)
console.log(`joinRoom : ${rCode} 입장`)
console.log('123123방입ㄴ장')
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
}
const [roomName, setRoomName] = useState('')
......@@ -71,29 +62,27 @@ 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])
// 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('이미 참가된 방입니다.')
}
......@@ -122,6 +111,20 @@ function Home() {
}
}, [singleChat])
useEffect(() => {
if (!(sysmsg == '')) {
socket.emit("chat", {
roomInfo: roomCode,
sendInfo: {
msg: sysmsg,
sender: "system",
// time: singleTime
}
})
setSysmsg('')
}
}, [sysmsg])
useEffect(() => {
socket.on("sendedMSG", (sendInfo) => {
......@@ -178,7 +181,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} />
</>
);
}
......
......@@ -105,7 +105,6 @@ const changemember = async (req, res) => {
else {
return res.json(false)
}
res.end()
} catch (error) {
res.status(500).send('멤버 업데이트 실패')
}
......
......@@ -86,8 +86,7 @@ const getProfile = (req, res) => {
const checkUser = async (req, res) => {
try {
const info = await AccessInfo.findOne({ userInfo: req.query._id })
const info = await User.findOne({ _id: req.query._id })
console.log('info 확인', info)
return res.json(info)
} catch (error) {
......
......@@ -11,7 +11,6 @@ import cors from "cors"
import Room from './models/Room.js'
import Chat from "./models/Chat.js"
import User from "./models/User.js"
import AccessInfo from "./models/AccessInfo.js"
connectDb()
......@@ -30,21 +29,6 @@ io.on("connection", (socket) => { // 기본 연결
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
});
// socket.on('access', async (data) => {
// console.log('access', data)
// const nick = await User.findOne({ _id: data.userInfo }).select('nickname').exec()
// 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) => {
console.log('roomname확인', data)
const room = await Room.findOne({ roomId: data.roomInfo })
......@@ -53,13 +37,13 @@ io.on("connection", (socket) => { // 기본 연결
const chat = await new Chat({
room: room._id,
username: data.sendInfo.sender,
message: data.sendInfo.msg
message: data.sendInfo.msg
}).save()
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)
......
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