HomePage.js 11.1 KB
Newer Older
Soo Hyun Kim's avatar
Soo Hyun Kim committed
1
import React, { useState, useEffect } from 'react';
2
import { Row, Col, Button, Tabs, Tab, Form } from 'react-bootstrap';
Soo Hyun Kim's avatar
Soo Hyun Kim committed
3
import styled from 'styled-components';
우지원's avatar
ul    
우지원 committed
4
5
import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList';
Choi Ga Young's avatar
Choi Ga Young committed
6
import Menu from '../Components/Menu';
7
import { io } from "socket.io-client";   //모듈 가져오기
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
8
import Chat from "../Components/Chat";
Soo Hyun Kim's avatar
Soo Hyun Kim committed
9
10
import RoomMake from "../Components/RoomMake"
import EnterRoom from "../Components/EnterRoom"
우지원's avatar
우지원 committed
11
import axios from 'axios';
Choi Ga Young's avatar
탭 색    
Choi Ga Young committed
12
import "./Home.css"
13
import catchErrors from '../utils/catchErrors';
우지원's avatar
ul    
우지원 committed
14

15
const socket = io();
우지원's avatar
ul    
우지원 committed
16

우지원's avatar
우지원 committed
17
const INIT_ROOM = {
18
19
20
21
  roomName: '',
  interest: '',
  roomId: '',
  member: '',
우지원's avatar
우지원 committed
22
}
23
24
25
26
27
28
29
const INIT_LIST = [{
  interest: '',
  isOpen: '',
  memeber: [],
  roomId: '',
  roomName: '',
}]
30
31
32
33
const INIT_UNREAD = {
  roomCode: '',
  unreadcount: '',
}
우지원's avatar
우지원 committed
34

우지원's avatar
ul    
우지원 committed
35
function Home() {
36
  const userName = sessionStorage.getItem('name')
Choi Ga Young's avatar
x    
Choi Ga Young committed
37
  const userId = sessionStorage.getItem('userId')
38
39
40
  const realTime = new Date().toISOString()

  const [error, setError] = useState('')
41

42
43
44
  const [checknew, setChecknew] = useState('')
  const [unreadnumber, setUnreadnumber] = useState(INIT_UNREAD)

JeongYeonwoo's avatar
JeongYeonwoo committed
45
  const [showModal, setShowModal] = useState(false);
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
46
  const [showEnter, setShowEnter] = useState(false);
JeongYeonwoo's avatar
JeongYeonwoo committed
47
  const [chat, setChat] = useState(false);
48
49
  const [open, setOpen] = useState(false);
  const [room, setRoom] = useState(INIT_ROOM)
50
  const [show, setShow] = useState(false)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
51

JeongYeonwoo's avatar
JeongYeonwoo committed
52
53
54
55
  //소켓
  const [singleChat, setSingleChat] = useState('')
  const [recievedMsg, setRecievedMsg] = useState('')
  const [roomCode, setRoomCode] = useState('')
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
56
  const [sysmsg, setSysmsg] = useState('')
Soo Hyun Kim's avatar
Soo Hyun Kim committed
57
  const [roomName, setRoomName] = useState('')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
58

JeongYeonwoo's avatar
JeongYeonwoo committed
59
60
  const [singleUser, setSingleUser] = useState('')
  const [recievedUser, setRecievedUser] = useState('')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
61

JeongYeonwoo's avatar
JeongYeonwoo committed
62
63
64
  const [singleImg, setSingleImg] = useState('')
  const [recievedImg, setRecievedImg] = useState('')

65
66
67
  const [singleTime, setSingleTime] = useState('')
  const [recievedTime, setRecievedTime] = useState('')

Choi Ga Young's avatar
Choi Ga Young committed
68
69
70
71
72
73
  const handleCloseModal = () => {
    setShowModal(false);
    getClosedList()
    getOpenList()

  }
JeongYeonwoo's avatar
JeongYeonwoo committed
74
  const handleShowModal = () => setShowModal(true);
75
76
  const handleCloseEnter = () => setShowEnter(false);
  const handleShowEnter = () => setShowEnter(true);
JeongYeonwoo's avatar
JeongYeonwoo committed
77
78
  const handleChato = () => setChat(true);
  const handleChatc = () => setChat(false);
79
80
  const [closedlist, setClosedList] = useState(INIT_LIST);
  const [openlist, setOpenlist] = useState([])
81

82
  //SOCKET 관련 시작
Choi Ga Young's avatar
x    
Choi Ga Young committed
83
  async function enterChatRoom(rCode) {    //방 입장하기
84
85
    socket.emit('joinRoom', rCode)
    socket.emit('newUser', { rmIf: rCode, userInfo: userName })
우지원's avatar
오픈    
우지원 committed
86
    setShow(true)
87
    console.log(`joinRoom : ${rCode} 입장`)
우지원's avatar
오픈    
우지원 committed
88
    console.log('show:', show)
89
    //여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
90
    console.log('HomePage/enterChatRoom 끝났습니다')
91
  }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
92

Soo Hyun Kim's avatar
Soo Hyun Kim committed
93
94
95
96
  function closeChatRoom(rCode) {
    socket.emit('closeRoom', rCode)
    console.log(`${rCode}방 보기 중단`)
  }
Choi Ga Young's avatar
Choi Ga Young committed
97

98

Soo Hyun Kim's avatar
Soo Hyun Kim committed
99
  async function exitRoom(roomId) {
Choi Ga Young's avatar
퇴장    
Choi Ga Young committed
100
101
    const response = await axios.get('/users/check', { params: { '_id': userId } })
    const userNick = response.data.nickname;
Soo Hyun Kim's avatar
Soo Hyun Kim committed
102
    await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
Choi Ga Young's avatar
퇴장    
Choi Ga Young committed
103
    setSysmsg(`${userNick}님이 나갔습니다.`)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
104
105
    setRoomCode("")
  }
JeongYeonwoo's avatar
JeongYeonwoo committed
106

107
108
109
  async function getClosedList() {
    const userid = sessionStorage.getItem('userId')
    let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
110
    // console.log('getClosedList',res.data)
111
112
113
114
115
116
117
118
    setClosedList(res.data)
  }

  async function getOpenList() {
    let res = await axios.get('/room/openlist')
    setOpenlist(res.data)
  }

119
120
121
122
  async function openListroom(roomId) {
    const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } })
    setRoom(roomInf.data[0])
    setShow(false)
우지원's avatar
오픈    
우지원 committed
123
    setOpen(true)
124
  }
Choi Ga Young's avatar
Choi Ga Young committed
125
  //오픈채팅방에서 참가하기
126
127
128
  async function attendListRoom() {
    const roomId = room.roomId
    const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
129
130
    const response = await axios.get('/users/check', { params: { '_id': userId } })
    const userNick = response.data.nickname;
131
132
    if (tf.data) {
      alert('참가되었습니다.')
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
133
      setSysmsg(`${userNick}님이 들어왔습니다.`)
Choi Ga Young's avatar
Choi Ga Young committed
134
      getClosedList()
135
136
      recordEntryLog()

137
138
    } else {
      alert('이미 참가된 방입니다.')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
139
    }
140
141
  }

142
143
144
145
146
147
148
149
150
151
152
153
154
155
  async function recordEntryLog() {
    const leaveInfo = { userId: userId, roomCode: 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)
    }
  }

156
157
158
  function enterButton() {
    setOpen(false)
  }
Choi Ga Young's avatar
Choi Ga Young committed
159
160
161
162
  const sendMsg = (e) => {
    e.preventDefault()
  }

163
164
165
166
  useEffect(() => {
    getClosedList();
    getOpenList();
  }, [roomCode]);
Choi Ga Young's avatar
Choi Ga Young committed
167

JeongYeonwoo's avatar
JeongYeonwoo committed
168
  useEffect(() => {
Choi Ga Young's avatar
Choi Ga Young committed
169
    if (!(singleChat === "")) {
JeongYeonwoo's avatar
JeongYeonwoo committed
170
171
      socket.emit("chat", {
        roomInfo: roomCode,
172
173
174
        sendInfo: {
          msg: singleChat,
          sender: singleUser,
175
176
          img: singleImg,
          time: singleTime
177
        }
JeongYeonwoo's avatar
JeongYeonwoo committed
178
      })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
179
      setSingleChat("")
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
180
    }
JeongYeonwoo's avatar
JeongYeonwoo committed
181
  }, [singleChat])
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
182

Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
183
  useEffect(() => {
Choi Ga Young's avatar
Choi Ga Young committed
184
    if (!(sysmsg === '')) {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
185
186
187
188
189
190
191
192
193
194
195
      socket.emit("chat", {
        roomInfo: roomCode,
        sendInfo: {
          msg: sysmsg,
          sender: "system",
        }
      })
      setSysmsg('')
    }
  }, [sysmsg])

196
197


198
199
200
201
202
203
204
  const INIT_LEFT = {
    userId: '',
    roomCode: '',
    now: '',
  }
  const [leftInfo, setLeftInfo] = useState(INIT_LEFT)

205
206
  async function unreadMessage() {
    const userId = sessionStorage.getItem('userId')
207
    let leaveInfo = []
208
209
210
211
212
213
    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) {
214
          leaveInfo[i].now = '보는중'
215
216
217
218
219
220
221
        } else {
          leaveInfo[i].now = 0
        }
      }
      setUnreadnumber([''])
      const respond = await axios.get('/room/unreadMessage', { params: leaveInfo })
      setUnreadnumber(respond.data)
222
      setLeftInfo(leaveInfo)
223
224
225
226
227
    } catch (error) {
      console.log(error)
    }
  }

JeongYeonwoo's avatar
JeongYeonwoo committed
228
  useEffect(() => {
Choi Ga Young's avatar
Choi Ga Young committed
229
    socket.on("sendedMSG", (sendInfo) => {
230
      setRecievedTime(sendInfo.time)
JeongYeonwoo's avatar
JeongYeonwoo committed
231
232
233
      setRecievedImg(sendInfo.img)
      setRecievedUser(sendInfo.sender)
      setRecievedMsg(sendInfo.msg)
234
235
236
237
    })
    socket.on('checking', (check) => {
      console.log('클라이언트', check)
      setChecknew(check)
Choi Ga Young's avatar
Choi Ga Young committed
238
    })
JeongYeonwoo's avatar
JeongYeonwoo committed
239
240
241
  }, [])

  return (
우지원's avatar
a    
우지원 committed
242
    
Soo Hyun Kim's avatar
Soo Hyun Kim committed
243
244
245
    <div style={{ weight: "100vw", height: "100vh", backgroundColor: "" }}>
      <Menu style={{ weight: "100%", height: "10%" }} />
      <Row className="mr-0" style={{ weight: "100%", height: "80%" }}>
JeongYeonwoo's avatar
JeongYeonwoo committed
246
        <Col className="list" md={5}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
247
          <Sdiv chat={chat} open={open}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
248
249
            <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example" >
              <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
250
                <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} />
Soo Hyun Kim's avatar
Soo Hyun Kim committed
251
252
253
254
255
256
              </Tab>
              <Tab eventKey="open" title="공개방" onClick={handleChatc}>
                <OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
              </Tab>
            </Tabs>
          </Sdiv>
JeongYeonwoo's avatar
JeongYeonwoo committed
257
        </Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
258
        <Col style={{ padding: "5px", marginLeft: "15px" }}>
우지원's avatar
오픈    
우지원 committed
259
          {show ? <>
Choi Ga Young's avatar
Choi Ga Young committed
260
            {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} />
261
              : <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
262
263
                <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>
우지원's avatar
오픈    
우지원 committed
264
              </div>} </>
우지원's avatar
우지원 committed
265
266
            : <> {open ? 
            <div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
우지원's avatar
오픈    
우지원 committed
267
              <div className="d-flex justify-content-center">
우지원's avatar
우지원 committed
268
                <div className="mt-5 p-5 mr-2" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', position: "relative" }}>
우지원's avatar
오픈    
우지원 committed
269
270
271
272
273
274
275
276
                  <h2 className="d-flex justify-content-center mb-3">현재 {room.roomName} 입니다.</h2>
                  <h5> 관심분야 : {room.interest}</h5>
                  <h5> 참여인원 : {room.member.length}</h5>
                  <h5 className="mb-3"> 방코드(방코드를 통해서도 참여할  있습니다.) : {room.roomId}</h5>
                  <Row className='justify-content-center'>
                    <Button variant="outline" style={{ border: "3px solid", borderColor: "#b49dc9" }} size="sm" className="mr-4" onClick={enterButton}>뒤로가기</Button>
                    <Button variant="outline" style={{ border: "3px solid", borderColor: "#b49dc9" }} size="sm" className="ml-4" type='submit' onClick={attendListRoom}>참가</Button>
                  </Row>
277
278
                </div>
              </div>
우지원's avatar
오픈    
우지원 committed
279
280
281
282
            </div> : <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={handleShowEnter} size="lg" block>참가</Button>
              </div>} </>}
JeongYeonwoo's avatar
JeongYeonwoo committed
283
284
285
        </Col>
      </Row>
      <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
286
      <EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName} sysmsg={sysmsg} setSysmsg={setSysmsg} />
Soo Hyun Kim's avatar
Soo Hyun Kim committed
287
    </div>
JeongYeonwoo's avatar
JeongYeonwoo committed
288
  );
우지원's avatar
ul    
우지원 committed
289
290
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
291
292
const Sdiv = styled.div`
    @media screen and (max-width: 768px) {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
293
294
     display: ${({ chat, open }) => {
    return (chat || open) ? 'none' : 'block'
Choi Ga Young's avatar
Choi Ga Young committed
295
  }}
Soo Hyun Kim's avatar
Soo Hyun Kim committed
296
297
298
   }
`

우지원's avatar
e    
우지원 committed
299
export default Home;