Commit 79e0fc87 authored by 우지원's avatar 우지원
Browse files

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

parents 17577aa9 d36c5c41
...@@ -12,6 +12,7 @@ const INIT_CHAT = { ...@@ -12,6 +12,7 @@ const INIT_CHAT = {
img: '', img: '',
time: '' time: ''
} }
function Chat(props) { function Chat(props) {
//const [sender, setSender] = useState([]) //const [sender, setSender] = useState([])
...@@ -44,7 +45,8 @@ function Chat(props) { ...@@ -44,7 +45,8 @@ function Chat(props) {
e.preventDefault() e.preventDefault()
setInner(e.target.value) setInner(e.target.value)
setDisabled(false) setDisabled(false)
//console.log(chat)
console.log(props.leftInfo)
} }
function sendMsgCH(e) { function sendMsgCH(e) {
...@@ -57,18 +59,34 @@ function Chat(props) { ...@@ -57,18 +59,34 @@ function Chat(props) {
props.sendMsg(e) props.sendMsg(e)
setInner('') setInner('')
setDisabled(true) setDisabled(true)
recordEntryLog() //그냥 새로고침해도 최신화
} }
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([''])
recordEntryLog()
props.handleChatc() props.setRoomCode('')
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
} }
function settingtime(hour) { function settingtime(hour) {
...@@ -89,7 +107,6 @@ function Chat(props) { ...@@ -89,7 +107,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 +138,6 @@ function Chat(props) { ...@@ -121,7 +138,6 @@ function Chat(props) {
useEffect(() => { useEffect(() => {
getPreviousChat() getPreviousChat()
// console.log('겟 룸네임', chat)
}, [props.roomCode]) }, [props.roomCode])
...@@ -142,7 +158,7 @@ function Chat(props) { ...@@ -142,7 +158,7 @@ function Chat(props) {
<a href="#;" onClick={() => setExit(!exit)}><BsX size="1em" color="#F2D788" /></a> <a href="#;" onClick={() => setExit(!exit)}><BsX size="1em" color="#F2D788" /></a>
</div> </div>
: null} : null}
<div id="chat-body" style={{ overflow: 'auto', paddingRight: '15px', width: "100%", height: "400px", margin: "1%", background: '' }}> <div id="chat-body" style={{ overflow: 'auto', padding: '15px', width: "100%", height: "75%", margin: "1%", background: '' }}>
{chat.map((value, index) => { {chat.map((value, index) => {
if (!(value.msg === '')) { if (!(value.msg === '')) {
if (value.sender === "system") { if (value.sender === "system") {
...@@ -160,7 +176,7 @@ function Chat(props) { ...@@ -160,7 +176,7 @@ function Chat(props) {
<Col className="ml-2"> <Col className="ml-2">
<Row><strong>{value.sender}</strong></Row> <Row><strong>{value.sender}</strong></Row>
<Row xs="auto" className='d-flex flex-wrap-nowrap'> <Row xs="auto" className='d-flex flex-wrap-nowrap'>
<Row style={{ width: 'max-content', maxWidth: '80%', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: '#f1ebf7', borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Row> <Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: '#f1ebf7', borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Row>
<Col className="ml-1">{value.time}</Col> <Col className="ml-1">{value.time}</Col>
</Row> </Row>
</Col> </Col>
......
import React from 'react' import React, { useState, useEffect } from 'react'
import { Badge, ListGroup } from 'react-bootstrap'; import { Badge, ListGroup } from 'react-bootstrap';
import "../Pages/Home.css";
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)
} }
...@@ -13,16 +33,43 @@ function ClosedList(props) { ...@@ -13,16 +33,43 @@ function ClosedList(props) {
props.setRoomCode(roomCode) props.setRoomCode(roomCode)
props.setRoomName(roomName) props.setRoomName(roomName)
await recordEntryLog(e) //방 입장시 시간 업데이트 (그래야 안 읽은 메세지가 0개로 되니까)
props.unreadMessage() //방 입장시 메세지 개수 다시셈 (그래야 입장시 0으로 초기화 되니까)
}
//안읽은 메세지 count하는 부분
useEffect(() => { // 누군가 보내면 다시 개수 셈
console.log('chat 클라이언트 변경!')
props.unreadMessage()
console.log('새 메세지가 도착했습니다.', props.leftInfo)
}, [props.checknew])
useEffect(() => { //일단 들오면 실행해야지
props.unreadMessage()
}, [props.closedlist])
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 style={{height: "80vh"}}> <div style={{height: "80vh"}}>
<div style={{overflow: 'auto', height:"100%"}}> <div style={{overflow: 'auto', height:"100%"}}>
{props.closedlist.map((item, index) => {props.closedlist.map((item, index) =>
<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}
className='rounded-0'>
{item.roomName} {item.roomName}
{/* {[index] ? <Badge className='ml-2' pill variant='danger'>{unreadnumber[index]}</Badge> : ''} */} {unread[index] ? <Badge className='ml-2' pill variant='danger'>{unread[index]}</Badge> : ''}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
) )
......
...@@ -52,7 +52,7 @@ function EnterRoom(props) { ...@@ -52,7 +52,7 @@ function EnterRoom(props) {
</Form.Group> </Form.Group>
<Form.Group as={Row}> <Form.Group as={Row}>
<Col sm={{ span: 5, offset: 4 }}> <Col sm={{ span: 5, offset: 4 }}>
<Button type="submit">참가</Button> <Button type="submit" style={{backgroundColor:"#9174ad", borderColor:"#9174ad"}} >참가</Button>
</Col> </Col>
</Form.Group> </Form.Group>
</Form> </Form>
......
...@@ -11,26 +11,28 @@ function Menu(props) { ...@@ -11,26 +11,28 @@ function Menu(props) {
return ( return (
<div className="container-fluid" style={{ display: "flex", flexDirection: "row", backgroundColor: "#61477a", heigth: "100%", position: "relative" }}> <div className="container-fluid" style={{ display: "flex", flexDirection: "row", backgroundColor: "#61477a", heigth: "100%", position: "relative" }}>
<p className="navbar-brand" href="/home" style={{color: 'white', alignItems: "center"}}>YDK Messenger</p> <a href="/" className="navbar-brand" href="/home" style={{ color: 'white', alignItems: "center" }}>{'YDK Messenger'}</a>
{name ? {name ?
<> <>
<div className="nav navbar-nav mr-auto" style={{ color: 'white', display: "flex", flexDirection: "row", alignItems: "center"}}> <div className="nav navbar-nav mr-auto" style={{ color: 'white', display: "flex", flexDirection: "row", alignItems: "center" }}>
<p className="mt-2 mr-4">{name} 환영합니다</p> <p className="mt-2 mr-4">{`${name}님 환영합니다`}</p>
<div className="showText"> <div className="showText">
<a href="/profile" style={{color:"#FFFFFF", marginRight: "15px"}}>{'Profile'}</a> <a href="/profile" style={{ color: "#FFFFFF", marginRight: "15px" }}>{'Profile'}</a>
<a onClick={() => handleLogout()} href="/login" style={{color:"#FFFFFF"}}>{'logout'}</a> <a onClick={() => handleLogout()} href="/login" style={{ color: "#FFFFFF" }}>{'logout'}</a>
</div> </div>
<div className="showIcon"> <div className="showIcon">
<a href="/profile" style={{marginRight: "15px"}}><BsPeopleCircle size="25" color="#FFFFFF" /></a> <a href="/profile" style={{ marginRight: "15px" }}><BsPeopleCircle size="25" color="#FFFFFF" /></a>
<a href="/login" onClick={() => handleLogout()}><AiOutlineLogout size="25" color="#FFFFFF" /></a> <a href="/login" onClick={() => handleLogout()}><AiOutlineLogout size="25" color="#FFFFFF" /></a>
</div> </div>
</div> </div>
</> </>
: <> : <>
<Nav className="nav navbar-nav"> <div className="nav navbar-nav" style={{ display: "flex", flexDirection: "row", alignItems: "center" }}>
<Nav.Link href="/login">Login</Nav.Link> <div className="showTextBFLogin">
<Nav.Link href="/signup">Signup</Nav.Link> <a href="/login" style={{ color:"#FFFFFF", marginRight: "15px" }}>{'Login'}</a>
</Nav> <a href="/signup" style={{ color:"#FFFFFF" }}>{'Signup'}</a>
</div>
</div>
</>} </>}
</div> </div>
) )
......
import React from 'react' import React from 'react'
import { ListGroup } from 'react-bootstrap'; import { ListGroup } from 'react-bootstrap';
import "../Pages/Home.css";
function OpenList(props) { function OpenList(props) {
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
if (props.roomCode){ if (props.roomCode) {
props.closeChatRoom(props.roomCode) props.closeChatRoom(props.roomCode)
} }
const roomCode = e.target.name const roomCode = e.target.name
...@@ -16,7 +17,7 @@ function OpenList(props) { ...@@ -16,7 +17,7 @@ function OpenList(props) {
<div style={{overflow: 'auto', height: "80vh"}}> <div style={{overflow: 'auto', height: "80vh"}}>
{props.openlist.map((item, index) => {props.openlist.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} className='rounded-0'>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
...@@ -80,7 +80,7 @@ function RoomMake(props) { ...@@ -80,7 +80,7 @@ function RoomMake(props) {
} }
<Form.Group as={Row}> <Form.Group as={Row}>
<Col sm={{ span: 5, offset: 4 }}> <Col sm={{ span: 5, offset: 4 }}>
<Button type="submit" > 생성</Button> <Button type="submit" style={{backgroundColor:"#9174ad", borderColor:"#9174ad"}} > 생성</Button>
</Col> </Col>
</Form.Group> </Form.Group>
</Form> </Form>
......
.nav-tabs .nav-item.nav-link {
color: silver !important;
}
.nav-tabs .nav-item.nav-link.active {
color:slateblue !important;
}
.list-group-item-action{
border-top: none;
}
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Tabs, Tab } from 'react-bootstrap'; import { Row, Col, Button, Tabs, Tab, Form } from 'react-bootstrap';
import styled from 'styled-components'; import styled from 'styled-components';
import ClosedList from '../Components/ClosedList'; import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList'; import OpenList from '../Components/OpenList';
...@@ -9,6 +9,7 @@ import Chat from "../Components/Chat"; ...@@ -9,6 +9,7 @@ import Chat from "../Components/Chat";
import RoomMake from "../Components/RoomMake" import RoomMake from "../Components/RoomMake"
import EnterRoom from "../Components/EnterRoom" import EnterRoom from "../Components/EnterRoom"
import axios from 'axios'; import axios from 'axios';
import "./Home.css"
const socket = io(); const socket = io();
...@@ -25,11 +26,18 @@ const INIT_LIST = [{ ...@@ -25,11 +26,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);
...@@ -52,7 +60,6 @@ function Home() { ...@@ -52,7 +60,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 = () => { const handleCloseModal = () => {
setShowModal(false); setShowModal(false);
...@@ -76,6 +83,7 @@ function Home() { ...@@ -76,6 +83,7 @@ function Home() {
console.log(`joinRoom : ${rCode} 입장`) console.log(`joinRoom : ${rCode} 입장`)
console.log('show:', show) console.log('show:', show)
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데 //여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
console.log('HomePage/enterChatRoom 끝났습니다')
} }
function closeChatRoom(rCode) { function closeChatRoom(rCode) {
...@@ -83,6 +91,7 @@ function Home() { ...@@ -83,6 +91,7 @@ function Home() {
console.log(`${rCode}방 보기 중단`) console.log(`${rCode}방 보기 중단`)
} }
async function exitRoom(roomId) { async function exitRoom(roomId) {
const response = await axios.get('/users/check', { params: { '_id': userId } }) const response = await axios.get('/users/check', { params: { '_id': userId } })
const userNick = response.data.nickname; const userNick = response.data.nickname;
...@@ -94,6 +103,7 @@ function Home() { ...@@ -94,6 +103,7 @@ 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)
} }
...@@ -163,13 +173,48 @@ function Home() { ...@@ -163,13 +173,48 @@ function Home() {
} }
}, [sysmsg]) }, [sysmsg])
const INIT_LEFT = {
userId: '',
roomCode: '',
now: '',
}
const [leftInfo, setLeftInfo] = useState(INIT_LEFT)
async function unreadMessage() {
const userId = sessionStorage.getItem('userId')
let leaveInfo = []
try {
for (let i = 0; i < closedlist.length; i++) {
leaveInfo.push({ userId: userId, roomCode: closedlist[i].roomId, now: 0 })
}
for (let i = 0; i < closedlist.length; i++) {
if (leaveInfo[i].roomCode === roomCode) {
leaveInfo[i].now = '보는중'
} else {
leaveInfo[i].now = 0
}
}
setUnreadnumber([''])
const respond = await axios.get('/room/unreadMessage', { params: leaveInfo })
setUnreadnumber(respond.data)
setLeftInfo(leaveInfo)
} 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)
}) })
}, []) }, [])
...@@ -178,10 +223,10 @@ function Home() { ...@@ -178,10 +223,10 @@ function Home() {
<Menu style={{ weight: "100%", height: "10%" }} /> <Menu style={{ weight: "100%", height: "10%" }} />
<Row className="mr-0" style={{ weight: "100%", height: "80%" }}> <Row className="mr-0" style={{ weight: "100%", height: "80%" }}>
<Col className="list" md={5}> <Col className="list" md={5}>
<Sdiv chat={chat}> <Sdiv chat={chat} open={open}>
<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 closedlist={closedlist} leftInfo={leftInfo} checknew={checknew} unreadMessage={unreadMessage} unreadnumber={unreadnumber} setUnreadnumber={setUnreadnumber} 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} />
...@@ -191,7 +236,7 @@ function Home() { ...@@ -191,7 +236,7 @@ function Home() {
</Col> </Col>
<Col style={{ padding: "5px", marginLeft: "15px" }}> <Col style={{ padding: "5px", marginLeft: "15px" }}>
{show ? <> {show ? <>
{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 ? <Chat leftInfo={leftInfo} setLeftInfo={setLeftInfo} 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} setRoomCode={setRoomCode} />
: <div style={{ position: "fixed", bottom: "20px", right: "30px" }}> : <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowModal} size="lg" block>생성</Button> <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowModal} size="lg" block>생성</Button>
<Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowEnter} size="lg" block>참가</Button> <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowEnter} size="lg" block>참가</Button>
...@@ -224,8 +269,8 @@ function Home() { ...@@ -224,8 +269,8 @@ function Home() {
const Sdiv = styled.div` const Sdiv = styled.div`
@media screen and (max-width: 768px) { @media screen and (max-width: 768px) {
display: ${({ chat }) => { display: ${({ chat, open }) => {
return chat === false ? 'block' : 'none' return (chat || open) ? 'none' : 'block'
}} }}
} }
` `
......
...@@ -54,7 +54,7 @@ function LogIn() { ...@@ -54,7 +54,7 @@ function LogIn() {
return ( return (
<> <>
<Menu /> <Menu />
<Form onSubmit={handleSubmit} className='vh-100 flex-column align-items-center justify-content-center mt-2'> <Form onSubmit={handleSubmit} className='vh-85 flex-column align-items-center justify-content-center mt-2'>
<Container className="d-flex justify-content-center"> <Container className="d-flex justify-content-center">
<div className="mt-5 p-5 shadow w-75"> <div className="mt-5 p-5 shadow w-75">
<h2 className="text-center">로그인</h2> <h2 className="text-center">로그인</h2>
......
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import styled from 'styled-components';
import { Image, Button, Container, Form, Row, Col } from 'react-bootstrap'; import { Image, Button, Container, Form, Row, Col } from 'react-bootstrap';
import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
...@@ -20,6 +18,7 @@ function ProfilePage() { ...@@ -20,6 +18,7 @@ function ProfilePage() {
const [hidden, setHidden] = useState(true) const [hidden, setHidden] = useState(true)
const [changed, setChanged] = useState(false) const [changed, setChanged] = useState(false)
const [selectedImg, setSelectedImg] = useState('')
const userId = isAuthenticated() const userId = isAuthenticated()
...@@ -40,6 +39,7 @@ function ProfilePage() { ...@@ -40,6 +39,7 @@ function ProfilePage() {
setHidden(true) setHidden(true)
} }
} }
function handleChange(e) { function handleChange(e) {
const { name, value, files } = e.target const { name, value, files } = e.target
if (files) { if (files) {
...@@ -48,6 +48,14 @@ function ProfilePage() { ...@@ -48,6 +48,14 @@ function ProfilePage() {
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
setChanged(true) setChanged(true)
if (files) {
let reader = new FileReader()
reader.onload = function (e) {
setSelectedImg(e.target.result)
}
reader.readAsDataURL(e.target.files[0])
}
} }
async function handleSubmit(e) { async function handleSubmit(e) {
e.preventDefault() e.preventDefault()
...@@ -76,6 +84,8 @@ function ProfilePage() { ...@@ -76,6 +84,8 @@ function ProfilePage() {
getProfile(userId) getProfile(userId)
}, [userId]) }, [userId])
return ( return (
<> <>
<Menu /> <Menu />
...@@ -83,7 +93,8 @@ function ProfilePage() { ...@@ -83,7 +93,8 @@ function ProfilePage() {
<Row > <Row >
<Col sm={4}> <Col sm={4}>
<Row className='justify-content-center'> <Row className='justify-content-center'>
<Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> {!selectedImg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> :
<Image src={selectedImg} style={{ width: "300px", height: "300px" }} roundedCircle />}
</Row> </Row>
<Row className='ml-3 mt-3 justify-content-center'> <Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex"> <Form className="d-flex">
...@@ -125,9 +136,7 @@ function ProfilePage() { ...@@ -125,9 +136,7 @@ function ProfilePage() {
<Row className='m-3 justify-content-center'> <Row className='m-3 justify-content-center'>
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Button size="sm" className="mr-4" type='submit' variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}>저장</Button> <Button size="sm" className="mr-4" type='submit' variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}>저장</Button>
<Link to='/'> <Button href="/" size="sm" className="ml-4" variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}> 화면으로</Button>
<Button size="sm" className="ml-4" variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}> 화면으로</Button>
</Link>
</Form> </Form>
</Row> </Row>
</Col> </Col>
......
...@@ -7,6 +7,15 @@ ...@@ -7,6 +7,15 @@
right: 0; right: 0;
} }
.showTextBFLogin {
display: flex;
flex-direction: row;
margin-right: 5px;
margin-left: 5px;
position: absolute;
right: 0;
}
.showIcon { .showIcon {
display: none; display: none;
} }
......
...@@ -2,13 +2,14 @@ import Room from "../models/Room.js" ...@@ -2,13 +2,14 @@ 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 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) {
...@@ -29,7 +30,7 @@ const makeRoom = async (req, res) => { ...@@ -29,7 +30,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)
...@@ -57,11 +58,11 @@ const getOpenList = async (req, res) => { ...@@ -57,11 +58,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('리스트 불러오기를 실패하였습니다!')
...@@ -70,14 +71,14 @@ const getRoomName = async (req, res) => { ...@@ -70,14 +71,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 {
...@@ -89,15 +90,15 @@ const changemember = async (req, res) => { ...@@ -89,15 +90,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('멤버 업데이트 실패')
...@@ -106,52 +107,43 @@ const deleteUserId = async (req, res) => { ...@@ -106,52 +107,43 @@ const deleteUserId = async (req, res) => {
const roomInf = async (req, res) => { const roomInf = async (req, res) => {
try { try {
console.log(req.query.roomId)
let roomInf = await Room.find({ roomId: req.query.roomId }) let roomInf = await Room.find({ roomId: req.query.roomId })
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 = '' try {
console.log('서버에서 초기 leaveInfo',leaveInfo) for (const key in Object.keys(leaveInfo)) {
for (let i = 1; i < leaveInfo.length; i++) { //일단 형식좀 맞추고 leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
leaveInfo[i] = JSON.parse(leaveInfo[i])
} }
//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) {
} if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
} else {
const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
}
} 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') //그 방의 메세지와 전송시간을 가져옴
let count = 0
//mongoose 시간비교 방법이 있음 (gte...)
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)
} }
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
...@@ -33,5 +34,53 @@ const getChatInfo = async (req, res) => { ...@@ -33,5 +34,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
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)
...@@ -34,9 +34,6 @@ const UserSchema = new mongoose.Schema({ ...@@ -34,9 +34,6 @@ const UserSchema = new mongoose.Schema({
type: String, type: String,
default: '3cd14b9bcb2007f324fcb82e0b566cce', default: '3cd14b9bcb2007f324fcb82e0b566cce',
}, },
entrylog: {
type: Array,
}
}, { }, {
timestamps: true timestamps: true
......
...@@ -22,14 +22,9 @@ router.route('/room/member') ...@@ -22,14 +22,9 @@ router.route('/room/member')
router.route('/room/getRoomName') router.route('/room/getRoomName')
.get(roomCtrl.getRoomName) .get(roomCtrl.getRoomName)
// 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,21 +23,21 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -23,21 +23,21 @@ 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('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,
...@@ -45,10 +45,10 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -45,10 +45,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