Commit c7aa37bd authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

안읽은 메세지 - 2%부족(현재 보고있는 방 상태를 없애는 것 불가능)

parent 4c23bf1f
...@@ -11,6 +11,7 @@ const INIT_CHAT = { ...@@ -11,6 +11,7 @@ const INIT_CHAT = {
img: '', img: '',
time: '' time: ''
} }
function Chat(props) { function Chat(props) {
const [sender, setSender] = useState([]) const [sender, setSender] = useState([])
...@@ -43,7 +44,6 @@ function Chat(props) { ...@@ -43,7 +44,6 @@ function Chat(props) {
e.preventDefault() e.preventDefault()
setInner(e.target.value) setInner(e.target.value)
setDisabled(false) setDisabled(false)
//console.log(chat)
} }
function sendMsgCH(e) { function sendMsgCH(e) {
...@@ -58,16 +58,47 @@ function Chat(props) { ...@@ -58,16 +58,47 @@ function Chat(props) {
setDisabled(true) setDisabled(true)
} }
async function recordEntryLog() {
const leaveInfo = { userId: userId, roomCode: props.roomCode, leaveTime: realTime }
try {
const check = await axios.get('/room/entrylog', { params: leaveInfo })
if (check.data) { //있으면 put으로
await axios.put('/room/entrylog', leaveInfo)
} else { //없으면 post
await axios.post('/room/entrylog', leaveInfo)
}
} catch (error) {
catchErrors(error, setError)
}
}
function handleClick() { function handleClick() {
props.closeChatRoom(props.roomCode) props.closeChatRoom(props.roomCode)
props.setRecievedMsg('') props.setRecievedMsg('')
props.handleChatc() props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
console.log('나간시간', realTime, usualTime)
setChat(['']) setChat([''])
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }]) recordEntryLog()
//아니 0으로 바꿔도 개수 세는걸 업데이트안하니까 소용없음 usestate해서 useEffect에 leaveInfo를 달아줘야할듯@@@@
//누르면 now를 0으로
// for (let i = 0; i < props.closedlist.length; i++) {
// props.leaveInfo[i].now = 0 //그냥 싹다 0으로 해도되잖아?
// if (props.leaveInfo[i].roomCode === props.roomCode) {
// // setLeftInfo(leftInfo[i].now='보는중')
// props.leaveInfo[i].now = 0 // 방 나가면 안 보는중으로 하기 위해 0으로 바꾸기!!!!!@@@@@@@@@@
// //usestate로 해보기@@@@@@
// console.log(i, '아아아아아아아아')
// } else {
// props.leaveInfo[i].now = 0
// }
// }
} }
function settingtime(hour) { function settingtime(hour) {
...@@ -88,7 +119,6 @@ function Chat(props) { ...@@ -88,7 +119,6 @@ function Chat(props) {
//프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식 //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
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 = []
...@@ -121,7 +151,6 @@ function Chat(props) { ...@@ -121,7 +151,6 @@ function Chat(props) {
useEffect(() => { useEffect(() => {
getPreviousChat() getPreviousChat()
// console.log('겟 룸네임', chat)
}, [props.roomCode]) }, [props.roomCode])
...@@ -186,7 +215,7 @@ function Chat(props) { ...@@ -186,7 +215,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, ListGroup } from 'react-bootstrap'; import { Badge, ListGroup } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors';
function ClosedList(props) { function ClosedList(props) {
const [error, setError] = useState('')
const realTime = new Date().toISOString()
function enterChatRoomCH(e) { async function recordEntryLog(e) {
const leaveInfo = { userId: props.userId, roomCode: e.target.name, leaveTime: realTime }
try {
const check = await axios.get('/room/entrylog', { params: leaveInfo })
if (check.data) { //있으면 put으로
await axios.put('/room/entrylog', leaveInfo)
} else { //없으면 post
await axios.post('/room/entrylog', leaveInfo)
}
} catch (error) {
catchErrors(error, setError)
}
}
async function enterChatRoomCH(e) {
if (props.roomCode) { if (props.roomCode) {
props.closeChatRoom(props.roomCode) props.closeChatRoom(props.roomCode)
} }
...@@ -15,48 +32,34 @@ function ClosedList(props) { ...@@ -15,48 +32,34 @@ function ClosedList(props) {
props.setRoomCode(roomCode) props.setRoomCode(roomCode)
props.setRoomName(roomName) props.setRoomName(roomName)
// console.log('rrrrrrrrrrrrrrr',props.closedlist) await recordEntryLog(e) //방 입장시 시간 업데이트 (그래야 안 읽은 메세지가 0개로 되니까)
// console.log('1111111111111111111',props.leaveInfo, typeof(props.leaveInfo)) props.unreadMessage() //방 입장시 메세지 개수 다시셈 (그래야 입장시 0으로 초기화 되니까)
// unreadMessage()
} }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//안읽은 메세지 count하는 부분
// const [checknew, setChecknew] = useState([]) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// const [unreadnumber, setUnreadnumber] = useState(['']) //안읽은 메세지 count하는 부분
// async function dbChat() {
// for (let i = 0; i <= props.closedlist.length - 1; i++) {
// const respond = await axios.get('/room/dbChat', { params: { 'roomId': props.closedlist[i].roomId } })
// setChecknew(respond.data)
// }
// }
// useEffect(() => {
// dbChat()
// }, [props.singleChat, props.recievedMsg])
// useEffect(() => { useEffect(() => { // 누군가 보내면 다시 개수 셈
// // console.log('chat 클라이언트 변경!') console.log('chat 클라이언트 변경!')
// unreadMessage() props.unreadMessage()
// }, [checknew]) }, [props.checknew])
// async function unreadMessage() { useEffect(() => { //일단 들오면 실행해야지
// //여기서 나간시간과 db의 메세지와 시간비교해서 개수를 count해주면 됨 props.unreadMessage()
// //물론 그 방 별로 찾아서 list를 맵써서 하던? }, [props.closedlist])
// // console.log('ddddddddd', list[0].roomId)
// setUnreadnumber([''])
// let arr = []
// for (let i = 0; i <= props.closedlist.length - 1; i++) {
// const respond = await axios.get('/room/unreadMessage', { params: { 'leaveInfo': props.leaveInfo, 'roomId': props.closedlist[i].roomId } })
// // setUnreadnumber([...unreadnumber, respond.data])
// arr = [...arr, respond.data]
// }
// setUnreadnumber(arr)
// // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length)
// } let count=[]
const [unread, setUnread] = useState([])
useEffect(() => { //unread정보가 들어오면 재정비해서 뿌려주기 위한 작업!
for (let i = 0; i < props.unreadnumber.length; i++) {
count.push(props.unreadnumber[i].unreadcount)
}
setUnread(count)
}, [props.unreadnumber])
return ( return (
<div> <div>
...@@ -64,7 +67,7 @@ function ClosedList(props) { ...@@ -64,7 +67,7 @@ function ClosedList(props) {
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}>
{item.roomName} {item.roomName}
{<Badge className='ml-2' pill variant='danger'>7</Badge>} {unread[index] ? <Badge className='ml-2' pill variant='danger'>{unread[index]}</Badge> : ''}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
) )
......
...@@ -24,11 +24,18 @@ const INIT_LIST = [{ ...@@ -24,11 +24,18 @@ const INIT_LIST = [{
roomId: '', roomId: '',
roomName: '', roomName: '',
}] }]
const INIT_UNREAD = {
roomCode: '',
unreadcount: '',
}
function Home() { function Home() {
const userName = sessionStorage.getItem('name') const userName = sessionStorage.getItem('name')
const userId = sessionStorage.getItem('userId') const userId = sessionStorage.getItem('userId')
const [checknew, setChecknew] = useState('')
const [unreadnumber, setUnreadnumber] = useState(INIT_UNREAD)
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [showEnter, setShowEnter] = useState(false); const [showEnter, setShowEnter] = useState(false);
const [chat, setChat] = useState(false); const [chat, setChat] = useState(false);
...@@ -51,7 +58,6 @@ function Home() { ...@@ -51,7 +58,6 @@ function Home() {
const [singleTime, setSingleTime] = useState('') const [singleTime, setSingleTime] = useState('')
const [recievedTime, setRecievedTime] = useState('') const [recievedTime, setRecievedTime] = useState('')
const [leaveInfo, setLeaveInfo] = useState([{ roomName: "", leaveTime: "" }])
const handleCloseModal = () => setShowModal(false); const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true); const handleShowModal = () => setShowModal(true);
...@@ -68,6 +74,7 @@ function Home() { ...@@ -68,6 +74,7 @@ function Home() {
socket.emit('newUser', { rmIf: rCode, userInfo: userName }) socket.emit('newUser', { rmIf: rCode, userInfo: userName })
console.log(`joinRoom : ${rCode} 입장`) console.log(`joinRoom : ${rCode} 입장`)
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데 //여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
console.log('HomePage/enterChatRoom 끝났습니다')
} }
function closeChatRoom(rCode) { function closeChatRoom(rCode) {
...@@ -75,6 +82,7 @@ function Home() { ...@@ -75,6 +82,7 @@ function Home() {
console.log(`${rCode}방 보기 중단`) console.log(`${rCode}방 보기 중단`)
} }
async function exitRoom(roomId) { async function exitRoom(roomId) {
await axios.put('/room/deleteMem', { userId: userId, roomId: roomId }) await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
console.log(`${roomId}${userId} 탈퇴`) console.log(`${roomId}${userId} 탈퇴`)
...@@ -84,12 +92,13 @@ function Home() { ...@@ -84,12 +92,13 @@ function Home() {
async function getClosedList() { async function getClosedList() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
let res = await axios.get('/room/closedlist', { params: { '_id': userid } }) let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
// console.log('getClosedList',res.data)
setClosedList(res.data) setClosedList(res.data)
} }
async function getOpenList() { async function getOpenList() {
let res = await axios.get('/room/openlist') let res = await axios.get('/room/openlist')
console.log('getOpenlist', res.data) // console.log('getOpenlist', res.data)
setOpenlist(res.data) setOpenlist(res.data)
} }
...@@ -156,13 +165,56 @@ function Home() { ...@@ -156,13 +165,56 @@ function Home() {
} }
}, [sysmsg]) }, [sysmsg])
// const INIT_LEFT = {
// userId: '',
// roomCode: '',
// now: '',
// }
// const [leftInfo, setLeftInfo] = useState(INIT_LEFT)
let leaveInfo = []
async function unreadMessage() {
const userId = sessionStorage.getItem('userId')
try {
for (let i = 0; i < closedlist.length; i++) {
leaveInfo.push({ userId: userId, roomCode: closedlist[i].roomId, now: 0 })
}
// setLeftInfo(leaveInfo)
for (let i = 0; i < closedlist.length; i++) {
if (leaveInfo[i].roomCode === roomCode) {
// setLeftInfo(leftInfo[i].now='보는중')
leaveInfo[i].now = '보는중' // 방 나가면 안 보는중으로 하기 위해 0으로 바꾸기!!!!!@@@@@@@@@@
//usestate로 해보기@@@@@@
console.log(i, '아아아아아아아아')
} else {
leaveInfo[i].now = 0
}
}
// leaveInfo[0].now='시발'
console.log('클ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ', leaveInfo)
setUnreadnumber([''])
const respond = await axios.get('/room/unreadMessage', { params: leaveInfo })
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~', respond.data)
setUnreadnumber(respond.data)
} catch (error) {
console.log(error)
}
}
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) })
socket.on('checking', (check) => {
console.log('클라이언트', check)
setChecknew(check)
}) })
}, []) }, [])
...@@ -173,7 +225,7 @@ function Home() { ...@@ -173,7 +225,7 @@ function Home() {
<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} closeChatRoom={closeChatRoom} /> <ClosedList checknew={checknew} unreadMessage={unreadMessage} unreadnumber={unreadnumber} setUnreadnumber={setUnreadnumber} setChecknew={setChecknew} closedlist={closedlist} userId={userId} singleChat={singleChat} recievedMsg={recievedMsg} 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} closeChatRoom={closeChatRoom} /> <OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
...@@ -190,9 +242,9 @@ function Home() { ...@@ -190,9 +242,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} closeChatRoom={closeChatRoom} exitRoom={exitRoom} /> <Chat leaveInfo={leaveInfo} handleChatc={handleChatc} 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} closedlist={closedlist}/>
: 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">
......
...@@ -3,13 +3,14 @@ import { customAlphabet } from 'nanoid' ...@@ -3,13 +3,14 @@ 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 AccessInfo from '../models/AccessInfo.js'
import Chat from "../models/Chat.js" import Chat from "../models/Chat.js"
import EntryLog from "../models/EntryLog.js"
const nanoid = customAlphabet('1234567890abcdef', 10) const nanoid = customAlphabet('1234567890abcdef', 10)
const makeRoom = async (req, res) => { const makeRoom = async (req, res) => {
console.log(req.body) // console.log(req.body)
const { roomName, interest, isOpen, member } = 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 roomId = nanoid()
const room = await Room.findOne({ roomId }) const room = await Room.findOne({ roomId })
while (room) { while (room) {
...@@ -30,7 +31,7 @@ const makeRoom = async (req, res) => { ...@@ -30,7 +31,7 @@ const makeRoom = async (req, res) => {
isOpen, isOpen,
member, member,
}).save() }).save()
console.log(newRoom) // console.log(newRoom)
res.json(newRoom) res.json(newRoom)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -58,11 +59,11 @@ const getOpenList = async (req, res) => { ...@@ -58,11 +59,11 @@ const getOpenList = async (req, res) => {
const getRoomName = async (req, res) => { const getRoomName = async (req, res) => {
const roomId = req.query.roomCode const roomId = req.query.roomCode
console.log('getRoomName', req.query.roomCode) // console.log('getRoomName', req.query.roomCode)
try { try {
let roominfo = await Room.findOne({ roomId: roomId }).select('roomName') let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
console.log(roominfo.roomName) // console.log(roominfo.roomName)
return res.json(roominfo.roomName) return res.json(roominfo.roomName)
} catch (error) { } catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!') res.status(500).send('리스트 불러오기를 실패하였습니다!')
...@@ -90,14 +91,14 @@ const getRoomName = async (req, res) => { ...@@ -90,14 +91,14 @@ const getRoomName = async (req, res) => {
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 업데이트 완료')
return res.json(true) return res.json(true)
} }
else { else {
...@@ -109,15 +110,15 @@ const changemember = async (req, res) => { ...@@ -109,15 +110,15 @@ const changemember = async (req, res) => {
} }
const deleteUserId = async (req, res) => { const deleteUserId = async (req, res) => {
console.log(req.body) // console.log(req.body)
const { userId, roomId } = req.body const { userId, roomId } = req.body
let room = await Room.findOne({ roomId: roomId }).select('member') let room = await Room.findOne({ roomId: roomId }).select('member')
console.log('deletetest', room) // console.log('deletetest', room)
const memIndex = room.member.indexOf(userId) const memIndex = room.member.indexOf(userId)
try { try {
room.member.splice(memIndex, 1) room.member.splice(memIndex, 1)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member }) await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log(`${roomId}${userId}삭제완료`) // console.log(`${roomId}방 ${userId}삭제완료`)
return res.json(true) return res.json(true)
} catch (error) { } catch (error) {
res.status(500).send('멤버 업데이트 실패') res.status(500).send('멤버 업데이트 실패')
...@@ -126,56 +127,51 @@ const deleteUserId = async (req, res) => { ...@@ -126,56 +127,51 @@ const deleteUserId = async (req, res) => {
const roomInf = async (req, res) => { const roomInf = async (req, res) => {
try { try {
console.log(req.query.roomId) // console.log(req.query.roomId)
// let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec() // let roomInf = await Room.findOne({ member: req.query.roomId }).select('interest roomId member').exec()
let roomInf = await Room.find({ roomId: req.query.roomId }) let roomInf = await Room.find({ roomId: req.query.roomId })
console.log('room_member로 정보 가져오기:', roomInf) // console.log('room_member로 정보 가져오기:', roomInf)
return res.json(roomInf) return res.json(roomInf)
} catch (error) { } catch (error) {
alert('올바르지 못한 접근입니다.') alert('올바르지 못한 접근입니다.')
} }
} }
////////////////////////////////////////////////////////////////////////////////////////////
const unreadMessage = async (req, res) => { const unreadMessage = async (req, res) => {
let leaveInfo = req.query.leaveInfo const nowTime = new Date().toISOString()
const roomId = req.query.roomId let leaveInfo = req.query
let leaveTime = '' console.log('서버의 언리드 리브인포', leaveInfo)
console.log('서버에서 초기 leaveInfo', leaveInfo) try {
for (let i = 1; i < leaveInfo.length; i++) { //일단 형식좀 맞추고 for (const key in Object.keys(leaveInfo)) {
leaveInfo[i] = JSON.parse(leaveInfo[i]) leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
} }
//findOne으로 해보자 let countArr = []
for (let i = 1; i <= leaveInfo.length - 1; i++) { //그 방의 id와 나간기록의 방과 일치하는지 확인하고 for (const key in Object.keys(leaveInfo)) {
if (leaveInfo[i].roomName === roomId) { const room = await Room.findOne({ roomId: leaveInfo[key].roomCode }) //들어온 방 코드로 그 방의 정보 찾아옴
leaveTime = leaveInfo[i].leaveTime //그 방에서 나간 시간을 찾아옴 const entrylog = await EntryLog.findOne({ userId: leaveInfo[key].userId, room: room._id }) //그 방에서 나간시간 가져옴
break; if (entrylog) {
console.log('자이거는 서버다!', leaveInfo[key].now)
if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
// countArr.push({ roomCode: room.roomId, unreadcount: count })
} else {
const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
// countArr.push({ roomCode: room.roomId, unreadcount: count })
}
} else {
countArr.push(0)
}
} }
res.json(countArr)
} catch (error) {
res.send(error)
} }
const room_id = await Room.find({ roomId: roomId }).select('_id') //id로 _id를 찾아와서
let unreadMsg = await Chat.find({ room: room_id }).select('createdAt') //그 방의 메세지와 전송시간을 가져옴
//Chat 전체가 아니라 그 방의 메세지에서 확인해야함!!
const count = unreadMsg.find({ createdAt: { $gte: leaveTime } })
console.log('서버에서 가자', count.length)
//mongoose 시간비교 방법이 있음 (gte.,lte..)
// for (let i = 0; i <= unreadMsg.length - 1; i++) {
// const dbtime = Date.parse(unreadMsg[i].createdAt)
// const parsedleaveTime = Date.parse(leaveTime)
// if (parsedleaveTime < dbtime) { //시간 비교를하고 이후에 온 메세지의 개수를 count함
// console.log('이번째부터 나중에온 메세지', i)
// count += 1
// }
// }
res.json(count.length)
} }
const dbChat = async (req, res) => {
const roomId = req.query.roomId
const room_id = await Room.find({ roomId: roomId }).select('_id')
let chatlist = await Chat.find({ room: room_id }).select('message')
res.json(chatlist)
}
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, dbChat, deleteUserId } export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, deleteUserId }
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 User from "../models/User.js";
import EntryLog from "../models/EntryLog.js";
const roomEnter = async (req, res) => { const roomEnter = async (req, res) => {
const roomId = req.body.enterCode const roomId = req.body.enterCode
...@@ -36,5 +37,53 @@ const getChatInfo = async (req, res) => { ...@@ -36,5 +37,53 @@ const getChatInfo = async (req, res) => {
} }
//그사람의 그방에서의 기록이 있는지 확인
const checklog = async (req, res) => {
console.log('@@@@@서버에서 체크 로그')
const { userId, roomCode } = req.query
const roomId = await Room.findOne({ roomId: roomCode })
try {
const entrylog = await EntryLog.findOne({ userId: userId, room: roomId })
res.json(Boolean(entrylog))
} catch (error) {
res.json(false)
}
}
//출입기록 업로드
const uploadlog = async (req, res) => {
console.log('@@@@@서버에서 업로드 로그')
const { userId, leaveTime, roomCode } = req.body
const user = await User.findOne({ _id: userId }) // 받아온 _id로 그 유저의 정보 가져옴
const room = await Room.findOne({ roomId: roomCode }) // 받아온 roomCode로 그 방의 정보 가져옴
try {
const entrylog = await new EntryLog({
userId: user._id,
room: room._id,
leaveTime: leaveTime,
}).save()
res.json(entrylog)
} catch (error) {
console.log(error)
res.send(500).send('출입시간이 기록되지 않았습니다.')
}
}
//출입기록 수정
const updatelog = async (req, res) => {
console.log('@@@@@서버에서 업데이트 로그')
const { userId, leaveTime, roomCode } = req.body
console.log('@@@@@', leaveTime, userId, roomCode)
const room = await Room.findOne({ roomId: roomCode })
try {
await EntryLog.updateOne({ userId: userId, room: room._id }, { leaveTime: leaveTime }) //항상 id와 room이 둘다 맞는걸 수정해야함 !
res.send('finished')
} catch (error) {
console.log(error)
res.send(500).send('출입시간 업데이트 실패')
}
}
export default { roomEnter, getChatInfo } export default { roomEnter, getChatInfo, checklog, uploadlog, updatelog }
\ No newline at end of file \ No newline at end of file
...@@ -3,7 +3,6 @@ import isLength from 'validator/lib/isLength.js' ...@@ -3,7 +3,6 @@ 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([
......
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
import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types
const EntryLogSchema = new mongoose.Schema({
userId: {
type: mongoose.ObjectId,
required: true,
ref: 'User',
},
room: {
type: mongoose.ObjectId,
required: true,
ref: 'Room',
},
leaveTime: {
type: String,
required: true,
}
}, {
timestamps: true
})
export default mongoose.models.EntryLog || mongoose.model('EntryLog', EntryLogSchema)
...@@ -22,17 +22,9 @@ router.route('/room/member') ...@@ -22,17 +22,9 @@ 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')
.get(roomCtrl.dbChat)
router.route('/room/deleteMem') router.route('/room/deleteMem')
.put(roomCtrl.deleteUserId) .put(roomCtrl.deleteUserId)
......
...@@ -9,5 +9,10 @@ router.route('/room/enterRoom') ...@@ -9,5 +9,10 @@ router.route('/room/enterRoom')
router.route('/room/getChatInfo') router.route('/room/getChatInfo')
.get(roomEnterCtrl.getChatInfo) .get(roomEnterCtrl.getChatInfo)
router.route('/room/entrylog')
.get(roomEnterCtrl.checklog)
.post(roomEnterCtrl.uploadlog)
.put(roomEnterCtrl.updatelog)
export default router export default router
\ No newline at end of file
...@@ -23,27 +23,27 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -23,27 +23,27 @@ io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id) console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때 socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
console.log('join_data확인', data) // console.log('join_data확인', data)
let roomInfo = data; let roomInfo = data;
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴 socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
}); });
socket.on('closeRoom', (data) => { socket.on('closeRoom', (data) => {
console.log('close_data확인', data) // console.log('close_data확인', data)
let roomInfo = data; let roomInfo = data;
socket.leave(roomInfo); //클라이언트에서 data에 적힌 room정보를 브로드캐스팅 받지 않는다. 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;
io.to(data.rmIf).emit('sendUser', userInfo) io.to(data.rmIf).emit('sendUser', userInfo)
}) })
socket.on('chat', async (data) => { socket.on('chat', async (data) => {
console.log('roomname확인', data) // console.log('roomname확인', data)
const room = await Room.findOne({ roomId: data.roomInfo }) const room = await Room.findOne({ roomId: data.roomInfo })
console.log('room이 떴나', room) // console.log('room이 떴나', room)
const chat = await new Chat({ const chat = await new Chat({
room: room._id, room: room._id,
...@@ -51,10 +51,10 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -51,10 +51,10 @@ io.on("connection", (socket) => { // 기본 연결
message: data.sendInfo.msg, message: data.sendInfo.msg,
profileimg: data.sendInfo.img profileimg: data.sendInfo.img
}).save() }).save()
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 제외 특정 방으로
socket.broadcast.emit('checking', data.sendInfo) // 메세지를 어딘가에서 보냈다는 신호
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
......
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