Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15766 | Rev 16782 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
15761 stevensc 1
/* eslint-disable react/prop-types */
16780 stevensc 2
import React, { useEffect, useState } from 'react'
3
import { axios } from '../../utils'
4
import { FiMaximize2 } from 'react-icons/fi'
5
import AddIcon from '@mui/icons-material/Add'
15761 stevensc 6
 
7
// Components
16780 stevensc 8
import NotificationAlert from '../../shared/notification/NotificationAlert'
9
import PersonalChat from './personal-chat/PersonalChat'
10
import ContactsModal from './components/ContactsModal'
11
import ContactsFilters from './components/contactsFilters'
15761 stevensc 12
 
16780 stevensc 13
const notifyAudio = new Audio('/audio/chat.mp3')
15761 stevensc 14
 
15766 stevensc 15
const Chat = ({ emojiOnePath, timezones }) => {
16780 stevensc 16
  const [contacts, setContacts] = useState([])
17
  const [activeChats, setActiveChats] = useState([])
18
  const [isChatOpen, setIsChatOpen] = useState(false)
19
  const [isMuted, setIsMuted] = useState(false)
20
  const [showModal, setShowModal] = useState(false)
21
  const [loading, setLoading] = useState(false)
15761 stevensc 22
 
16780 stevensc 23
  const [pendingConversation, setPendingConversation] = useState('')
15761 stevensc 24
 
25
  const handleEntities = (entities) => {
26
    entities.map((entity) => {
16780 stevensc 27
      if (entity.not_received_messages) handleNewMessage(entity)
28
      if (entity.not_seen_messages) handleNotSeenMessage(entity)
29
      if (entity.is_open) handleOpenConversation(entity, false)
30
      if (entity.type === 'user') handleUpdateOnline(entity)
31
    })
32
    setContacts(entities)
33
  }
15761 stevensc 34
 
35
  const heartBeat = async () => {
36
    try {
16780 stevensc 37
      setLoading(true)
38
      const { data } = await axios.get('/chat/heart-beat')
39
      if (data.success) handleEntities(data.data)
40
      setLoading(false)
41
      return data.data
15761 stevensc 42
    } catch (error) {
16780 stevensc 43
      console.log('>>: chat error > ', error)
15761 stevensc 44
    }
16780 stevensc 45
  }
15761 stevensc 46
 
47
  const handleUpdateOnline = (entity) => {
48
    const existingChatId = activeChats.findIndex(
49
      (activeChat) => activeChat.id === entity.id
16780 stevensc 50
    )
15761 stevensc 51
    if (existingChatId >= 0) {
52
      if (activeChats[existingChatId].online !== entity.online) {
16780 stevensc 53
        const newActiveChats = [...activeChats]
54
        newActiveChats[existingChatId].online = entity.online
55
        setActiveChats(newActiveChats)
15761 stevensc 56
      }
57
    }
16780 stevensc 58
  }
15761 stevensc 59
 
60
  const handleNewMessage = async (unseeEntity) => {
16780 stevensc 61
    await axios.post(unseeEntity.url_mark_received)
15761 stevensc 62
    if (!activeChats.some((activeChat) => activeChat.id === unseeEntity.id)) {
16780 stevensc 63
      setActiveChats([...activeChats, { ...unseeEntity, minimized: false }])
64
      playNotifyAudio()
15761 stevensc 65
    } else {
66
      const existingChatId = activeChats.findIndex(
67
        (activeChat) => activeChat.id === unseeEntity.id
16780 stevensc 68
      )
15761 stevensc 69
      if (!activeChats[existingChatId].unsee_messages) {
16780 stevensc 70
        const newActiveChats = [...activeChats]
71
        newActiveChats[existingChatId].unsee_messages = true
72
        setActiveChats(newActiveChats)
73
        playNotifyAudio(newActiveChats[existingChatId].minimized)
15761 stevensc 74
      }
75
    }
16780 stevensc 76
  }
15761 stevensc 77
 
16780 stevensc 78
  const handleCloseConversation = async (url) => {
79
    const { data } = await axios.post(url)
80
    console.log(data)
81
    if (!data.success) console.log('Error in entity close')
15761 stevensc 82
    setActiveChats(
83
      activeChats.filter((prevActiveChats) => prevActiveChats.id !== entity.id)
16780 stevensc 84
    )
85
  }
15761 stevensc 86
 
87
  const handleOpenConversation = async (entity, minimized = false) => {
88
    if (activeChats.some((el) => el.id === entity.id)) {
16780 stevensc 89
      return null
15761 stevensc 90
    }
91
 
92
    if (activeChats.length >= 3) {
16780 stevensc 93
      await handleCloseConversation(activeChats[0])
15761 stevensc 94
      setActiveChats((prevActiveChats) => [
95
        ...prevActiveChats,
16780 stevensc 96
        { ...entity, minimized }
97
      ])
98
      return
15761 stevensc 99
    }
100
 
101
    setActiveChats((prevActiveChats) => [
102
      ...prevActiveChats,
16780 stevensc 103
      { ...entity, minimized }
104
    ])
105
  }
15761 stevensc 106
 
107
  const handleReadConversation = async (entity) => {
108
    try {
16780 stevensc 109
      const { data } = await axios.post(entity.url_mark_seen)
110
      if (!data.success) console.log('Ha ocurrido un error')
15761 stevensc 111
      setActiveChats((prevActiveChats) =>
112
        [...prevActiveChats].map((chat) => {
113
          if (entity.id === chat.id)
16780 stevensc 114
            return { ...chat, not_seen_messages: false }
115
          return chat
15761 stevensc 116
        })
16780 stevensc 117
      )
15761 stevensc 118
    } catch (error) {
16780 stevensc 119
      console.log(`Error: ${error}`)
15761 stevensc 120
    }
16780 stevensc 121
  }
15761 stevensc 122
 
123
  const handleMinimizeConversation = (entity, minimized = null) => {
124
    return setActiveChats((prevActiveChats) =>
125
      [...prevActiveChats].map((chat) => {
126
        if (entity.id === chat.id)
16780 stevensc 127
          return { ...chat, minimized: minimized ?? !chat.minimized }
128
        return chat
15761 stevensc 129
      })
16780 stevensc 130
    )
131
  }
15761 stevensc 132
 
133
  const handleNotSeenMessage = (entity) => {
16780 stevensc 134
    const index = activeChats.findIndex((chat) => chat.id === entity.id)
15761 stevensc 135
 
136
    if (index !== -1) {
137
      setActiveChats((prev) =>
138
        [...prev].map((chat) => {
139
          if (chat.id === entity.id) {
140
            return {
141
              ...chat,
16780 stevensc 142
              not_seen_messages: entity.not_seen_messages
143
            }
15761 stevensc 144
          }
16780 stevensc 145
          return chat
15761 stevensc 146
        })
16780 stevensc 147
      )
15761 stevensc 148
    }
16780 stevensc 149
  }
15761 stevensc 150
 
151
  const playNotifyAudio = (minimized = true) => {
152
    if (!isMuted && minimized) {
16780 stevensc 153
      notifyAudio.play()
15761 stevensc 154
    }
16780 stevensc 155
  }
15761 stevensc 156
 
157
  const handleMute = () => {
16780 stevensc 158
    setIsMuted(!isMuted)
15761 stevensc 159
    if (isMuted) {
16780 stevensc 160
      notifyAudio.play()
15761 stevensc 161
    }
16780 stevensc 162
  }
15761 stevensc 163
 
164
  useEffect(() => {
16780 stevensc 165
    if (!loading) setTimeout(() => heartBeat(), 2000)
166
  }, [loading])
15761 stevensc 167
 
168
  useEffect(() => {
169
    if (pendingConversation) {
170
      const pendingChat = contacts.find(
171
        (contact) => contact.url_send === pendingConversation
16780 stevensc 172
      )
15761 stevensc 173
 
174
      if (pendingChat) {
16780 stevensc 175
        handleOpenConversation(pendingChat)
176
        setPendingConversation('')
15761 stevensc 177
      }
178
    }
16780 stevensc 179
  }, [pendingConversation, contacts])
15761 stevensc 180
 
181
  useEffect(() => {
16780 stevensc 182
    emojione.imageType = 'png'
183
    emojione.sprites = false
184
    emojione.ascii = true
185
    emojione.imagePathPNG = emojiOnePath
186
  }, [])
15761 stevensc 187
 
16780 stevensc 188
  if (window.innerWidth < 1000 || window.location.pathname === '/chat')
189
    return null
15761 stevensc 190
 
191
  return (
192
    <>
193
      <div className="chat-helper">
194
        <div
195
          className="subpanel_title"
196
          onClick={(e) =>
197
            e.currentTarget === e.target && setIsChatOpen(!isChatOpen)
198
          }
199
        >
200
          <a href="/chat" className="text-chat-title">
201
            {CHAT_LABELS.CHAT}
202
            <FiMaximize2 className="ml-3" />
203
          </a>
204
 
205
          <div className="subpanel_title-icons">
206
            <i
207
              className={`icon ${
16780 stevensc 208
                isMuted ? 'icon-volume-off' : 'icon-volume-2'
15761 stevensc 209
              } text-20`}
210
              onClick={handleMute}
211
            />
212
            <i
213
              className={`fa ${
16780 stevensc 214
                isChatOpen ? 'fa-angle-down' : 'fa-angle-up'
15761 stevensc 215
              } text-20`}
216
              onClick={() => setIsChatOpen(!isChatOpen)}
217
            />
218
          </div>
219
        </div>
220
        {isChatOpen && (
221
          <>
222
            <button className="action-btn" onClick={() => setShowModal(true)}>
223
              <AddIcon />
224
              {CHAT_LABELS.START_CONVERSATION}
225
            </button>
226
            <ContactsFilters
227
              dataset={contacts}
228
              selectConversation={(entity) => handleOpenConversation(entity)}
229
            />
230
          </>
231
        )}
232
      </div>
233
 
234
      <div className="active_chats-list">
235
        {activeChats.map((entity, index) => (
236
          <PersonalChat
237
            index={index}
238
            key={entity.id}
239
            entity={entity}
240
            not_seen_messages={entity.not_seen_messages}
241
            minimized={entity.minimized}
242
            onClose={handleCloseConversation}
243
            onMinimize={handleMinimizeConversation}
244
            onRead={handleReadConversation}
245
            timezones={timezones}
246
          />
247
        ))}
248
      </div>
249
      <ContactsModal show={showModal} onClose={() => setShowModal(false)} />
250
      <NotificationAlert />
251
    </>
16780 stevensc 252
  )
253
}
15761 stevensc 254
 
16780 stevensc 255
export default Chat