Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3101 stevensc 1
import React from "react";
1 www 2
import { useState, useEffect } from "react";
976 stevensc 3
import { axios } from "../../utils";
1 www 4
import Contacts from "./contacts/Contacts";
1335 stevensc 5
import NotificationAlert from "../../shared/notification/NotificationAlert";
1 www 6
import Groups from "./groups/Groups";
7
import PersonalChat from "./personal-chat/PersonalChat";
2739 stevensc 8
import { FiMaximize2 } from 'react-icons/fi'
3101 stevensc 9
import { addNotification } from "../../redux/notification/notification.actions";
10
import { useDispatch } from "react-redux";
1 www 11
 
12
const notifyAudio = new Audio("/audio/chat.mp3");
13
 
14
const Chat = (props) => {
3101 stevensc 15
 
16
  const dispatch = useDispatch()
17
 
1 www 18
  // states
681 steven 19
  const [fullChats, setFullChats] = useState([]);
1 www 20
  const [contacts, setContacts] = useState([]);
21
  const [groups, setGroups] = useState([]);
22
  const [activeChats, setActiveChats] = useState([]);
23
  const [isChatOpen, setIsChatOpen] = useState(false);
24
  const [isMuted, setIsMuted] = useState(false);
25
  const [activeTab, setActiveTab] = useState("user");
976 stevensc 26
  const [search, setSearch] = useState('');
1775 stevensc 27
  const [loading, setLoading] = useState(false);
976 stevensc 28
 
994 stevensc 29
  const filtredContacts = contacts.filter(({ name }) => name.toLowerCase().includes(search.toLowerCase()))
30
  const filtredGroups = groups.filter(({ name }) => name.toLowerCase().includes(search.toLowerCase()))
976 stevensc 31
 
32
  const handleEntities = entities => {
2791 stevensc 33
    setFullChats([...entities]);
687 steven 34
    let newUserContacts = [];
35
    let newGroups = [];
36
    entities.map((entity) => {
37
      if (entity.not_received_messages) {
38
        handleNewMessage(entity);
39
      }
40
      switch (entity.type) {
41
        case "user":
42
          newUserContacts = [...newUserContacts, entity];
43
          handleUpdateOnline(entity);
44
          break;
45
        case "group":
46
          newGroups = [...newGroups, entity];
47
          break;
48
        default:
49
          break;
50
      }
51
    });
52
    setContacts(newUserContacts);
53
    setGroups(newGroups);
54
  }
2790 stevensc 55
 
56
  useEffect(() => {
57
    axios.get("/chat/heart-beat")
58
      .then(({ data }) => {
59
        if (data.success) {
60
          const entities = data.data
61
 
62
          entities.map(entity => {
2792 stevensc 63
            if (entity.is_open !== 0) {
64
              handleOpenConversation(entity, false);
2790 stevensc 65
            }
66
          })
67
        }
68
      })
69
  }, [])
70
 
687 steven 71
  const heartBeat = async () => {
689 steven 72
    try {
2973 stevensc 73
      const res = await axios.get("/chat/heart-beat")
74
      let entities = [];
75
      const resData = res.data;
76
      if (resData.success) {
77
        entities = resData.data;
2965 stevensc 78
        handleEntities(entities)
1 www 79
      }
689 steven 80
      return entities;
81
    } catch (error) {
976 stevensc 82
      console.log('>>: chat error > ', error)
689 steven 83
    }
687 steven 84
  };
1 www 85
 
976 stevensc 86
 
1 www 87
  const handleUpdateOnline = (entity) => {
88
    const existingChatId = activeChats.findIndex(
89
      (activeChat) => activeChat.id === entity.id
90
    );
91
    if (existingChatId >= 0) {
92
      if (activeChats[existingChatId].online !== entity.online) {
93
        const newActiveChats = [...activeChats];
94
        newActiveChats[existingChatId].online = entity.online;
95
        setActiveChats(newActiveChats);
96
      }
97
    }
98
  };
99
 
100
  const handleNewMessage = async (unseeEntity) => {
101
    await axios.post(unseeEntity.url_mark_received).then((response) => {
976 stevensc 102
      ('')
1 www 103
    });
104
    if (!activeChats.some((activeChat) => activeChat.id === unseeEntity.id)) {
105
      setActiveChats([...activeChats, { ...unseeEntity, minimized: false }]);
106
      playNotifyAudio();
107
    } else {
108
      const existingChatId = activeChats.findIndex(
109
        (activeChat) => activeChat.id === unseeEntity.id
110
      );
111
      if (!activeChats[existingChatId].unsee_messages) {
112
        const newActiveChats = [...activeChats];
113
        newActiveChats[existingChatId].unsee_messages = true;
114
        setActiveChats(newActiveChats);
115
        playNotifyAudio(newActiveChats[existingChatId].minimized);
116
      }
117
    }
118
  };
119
 
120
  const handleOpenConversation = (entity, minimized = false) => {
978 stevensc 121
    if (activeChats.length < 3 && !activeChats.some((el) => el.id === entity.id)) {
1 www 122
      setActiveChats([...activeChats, { ...entity, minimized: minimized }]);
123
    }
986 stevensc 124
    if (activeChats.length >= 3 && !activeChats.some((el) => el.id === entity.id)) {
125
      activeChats.map((el, index) => {
126
        if (index === 0) {
127
          axios.post(el.url_close)
128
        }
129
      })
130
      const newActiveChats = activeChats.filter((el, index) => index !== 0)
131
      setActiveChats([...newActiveChats, { ...entity, minimized: minimized }]);
132
    }
1 www 133
  };
134
 
3095 stevensc 135
  const handleReadChat = (index) => {
2169 steven 136
    const newActiveChats = [...activeChats];
3097 stevensc 137
 
3096 stevensc 138
    const markSeen = async () => {
3101 stevensc 139
      try {
140
        const { data } = await axios.post(activeChats[index].url_mark_seen)
141
        return data.success
142
      } catch (error) {
143
        dispatch(addNotification({
144
          style: 'danger',
145
          msg: `Error: ${error}`
146
        }))
147
      }
1 www 148
    }
3096 stevensc 149
    const markReceived = async () => {
3101 stevensc 150
      try {
151
        const { data } = await axios.post(activeChats[index].url_mark_received)
152
        return data.success
153
      } catch (error) {
154
        dispatch(addNotification({
155
          style: 'danger',
156
          msg: `Error: ${error}`
157
        }))
158
      }
2169 steven 159
    }
3095 stevensc 160
 
3097 stevensc 161
    Promise.all([markSeen(), markReceived()])
3096 stevensc 162
      .then(([seen, received]) => {
3102 stevensc 163
        if (seen && received) {
164
          newActiveChats[index].not_seen_messages = false;
165
          newActiveChats[index].not_received_messages = false;
166
          console.log(newActiveChats)
167
          setActiveChats(newActiveChats);
168
        }
3096 stevensc 169
      });
170
 
1 www 171
  };
172
 
173
  const handleMinimizeChat = (chatIndex, minimize) => {
174
    const newActiveChats = [...activeChats];
175
    switch (minimize) {
176
      case false:
177
        newActiveChats[chatIndex].minimized = false;
178
        break;
179
      default:
180
        newActiveChats[chatIndex].minimized =
181
          !newActiveChats[chatIndex].minimized;
182
        break;
183
    }
184
    setActiveChats(newActiveChats);
185
  };
186
 
187
  const handleCloseChat = (entityId, url_close) => {
188
    let newActiveChats = [];
1775 stevensc 189
    setLoading(true)
1 www 190
    axios.post(url_close).then((response) => {
191
      const resData = response.data;
192
    });
193
    newActiveChats = activeChats.filter(
194
      (activeChat) => activeChat.id !== entityId
2548 stevensc 195
    );
196
    setActiveChats(newActiveChats);
197
    setLoading(false)
1 www 198
  };
199
 
200
  const playNotifyAudio = (minimized = true) => {
201
    if (!isMuted && minimized) {
202
      notifyAudio.play();
203
    }
204
  };
205
 
206
  const handleMute = () => {
207
    setIsMuted(!isMuted);
208
    if (isMuted) {
209
      notifyAudio.play();
210
    }
211
  };
212
 
213
  const handleChangeTab = (tab) => {
214
    setActiveTab(tab);
215
  };
216
 
217
  useEffect(() => {
2548 stevensc 218
    if (!loading) {
2973 stevensc 219
      const fetchData = async () => {
2966 stevensc 220
        setLoading(true)
2973 stevensc 221
        const entities = await heartBeat() || [];
2966 stevensc 222
        setLoading(false)
2973 stevensc 223
 
224
        return entities
2966 stevensc 225
      }
226
 
2989 stevensc 227
      setTimeout(() => {
228
        fetchData()
229
      }, "2000")
691 steven 230
    }
2965 stevensc 231
  }, [loading]);
978 stevensc 232
 
1 www 233
  useEffect(() => {
234
    emojione.imageType = "png";
235
    emojione.sprites = false;
236
    emojione.ascii = true;
237
    emojione.imagePathPNG = props.emojiOnePath;
238
  }, []);
239
 
2069 steven 240
  return (window.innerWidth > 1000 && window.location.pathname !== '/chat') ? (
1 www 241
    <React.Fragment>
242
      <div id="drupalchat-wrapper">
243
        <div id="drupalchat">
244
          <div className="item-list" id="chatbox_chatlist">
245
            <ul id="mainpanel">
246
              <li id="chatpanel" className="first last">
2550 stevensc 247
                <div className="subpanel">
1 www 248
                  <div
249
                    className="subpanel_title"
2554 stevensc 250
                    onClick={(e) => (e.currentTarget === e.target) && setIsChatOpen(!isChatOpen)}
1 www 251
                  >
2554 stevensc 252
                    <a
253
                      href="/chat"
254
                      className="text-gray text-chat-title"
1 www 255
                    >
2554 stevensc 256
                      Chat
2739 stevensc 257
                      <FiMaximize2 className="ml-3" />
2554 stevensc 258
                    </a>
259
                    <div className="subpanel_title-icons">
2555 stevensc 260
                      <i
261
                        className={`icon ${isMuted ? "icon-volume-off" : "icon-volume-2"} text-20`}
262
                        onClick={handleMute}
263
                      />
264
                      <i
265
                        className={`fa ${isChatOpen ? "fa-angle-down" : "fa-angle-up"} text-20`}
266
                        onClick={() => setIsChatOpen(!isChatOpen)}
267
                      />
1 www 268
                    </div>
269
                  </div>
270
                  <div
271
                    id="showhidechatlist"
2551 stevensc 272
                    style={{ display: isChatOpen ? "grid" : "none" }}
1 www 273
                  >
274
                    <div
275
                      className="drupalchat_search_main chatboxinput"
276
                      style={{ background: "#f9f9f9" }}
277
                    >
2561 stevensc 278
                      <input
279
                        className="drupalchat_searchinput live-search-box"
280
                        id="live-search-box"
281
                        type="text"
282
                        name='search'
283
                        value={search}
284
                        onChange={e => setSearch(e.target.value || '')}
285
                      />
286
                      <i className="searchbutton fas fa-search" />
1 www 287
                    </div>
288
                    <div
289
                      className="drupalchat_search_main chatboxinput"
290
                      style={{ background: "#f9f9f9" }}
291
                    >
2548 stevensc 292
                      <button
2549 stevensc 293
                        className={`${activeTab === 'user' ? 'active' : ''}`}
2548 stevensc 294
                        onClick={() => handleChangeTab("user")}
1 www 295
                      >
2548 stevensc 296
                        Contactos
297
                      </button>
298
                      <button
2549 stevensc 299
                        className={`${activeTab === 'group' ? 'active' : ''}`}
2548 stevensc 300
                        onClick={() => handleChangeTab("group")}
1 www 301
                      >
2548 stevensc 302
                        Grupos
303
                      </button>
1 www 304
                    </div>
305
                    <div
306
                      className="contact-list chatboxcontent"
307
                      style={{
308
                        display: activeTab === "user" ? "block" : "none",
309
                      }}
310
                    >
311
                      <Contacts
976 stevensc 312
                        contacts={filtredContacts}
1 www 313
                        onOpenConversation={handleOpenConversation}
314
                      />
3058 stevensc 315
                    </div>
1 www 316
                    <div
317
                      className="group-list chatboxcontent"
318
                      style={{
319
                        display: activeTab === "group" ? "block" : "none",
320
                      }}
321
                    >
322
                      <ul id="group-list-ul" className="live-search-list-group">
323
                        <Groups
988 stevensc 324
                          groups={filtredGroups}
1 www 325
                          onOpenConversation={handleOpenConversation}
326
                        />
327
                      </ul>
328
                    </div>
329
                    <div
330
                      className="group-contacts-list chatboxcontent"
331
                      style={{ display: "none" }}
332
                    >
333
                      <div style={{ textAlign: "center", fontSize: "13px" }}>
334
                        Integrantes del grupo
335
                      </div>
336
                      <ul
337
                        id="contact-group-list-ul"
338
                        className="live-search-list"
339
                      ></ul>
340
                    </div>
341
                  </div>
342
                </div>
343
              </li>
344
            </ul>
345
          </div>
346
        </div>
347
      </div>
348
      <div style={{ display: "flex" }}>
349
        {activeChats.map((entity, index) => (
350
          <PersonalChat
351
            key={entity.id}
352
            entity={entity}
353
            index={index}
354
            onClose={handleCloseChat}
355
            onMinimize={handleMinimizeChat}
356
            onRead={handleReadChat}
357
          />
358
        ))}
359
      </div>
1335 stevensc 360
      <NotificationAlert />
1 www 361
    </React.Fragment>
362
  ) : (
363
    ""
364
  );
365
};
366
 
367
export default Chat;