11350 |
nelberth |
1 |
import {axios} from "../../utils";
|
|
|
2 |
import React, { useEffect, useRef } from "react";
|
|
|
3 |
import { connect } from "react-redux";
|
|
|
4 |
import {
|
|
|
5 |
setHaveNewMessage,
|
|
|
6 |
setUnreadMessages,
|
|
|
7 |
setShouldAlertNewMessage,
|
|
|
8 |
} from "../../redux/chat/chat.actions";
|
|
|
9 |
|
|
|
10 |
const notifyAudio = new Audio("/audio/chat.mp3");
|
|
|
11 |
|
|
|
12 |
const ChatHelper = (props) => {
|
|
|
13 |
// redux destructuring
|
|
|
14 |
// redux states
|
|
|
15 |
const { unreadMessages, shouldAlertNewMessage } = props;
|
|
|
16 |
// redux actions
|
|
|
17 |
const { setUnreadMessages, setShouldAlertNewMessage } = props;
|
|
|
18 |
// refs
|
|
|
19 |
const unreads = useRef([]);
|
|
|
20 |
const shouldNotify = useRef(false);
|
|
|
21 |
|
|
|
22 |
useEffect(() => {
|
|
|
23 |
clearInterval(checkChatInterval);
|
|
|
24 |
const checkChatInterval = setInterval(() => {
|
|
|
25 |
axios.get("/chat/heart-beat").then((response) => {
|
|
|
26 |
const resData = response.data;
|
|
|
27 |
if (resData.success) {
|
|
|
28 |
resData.data.map((entity) => {
|
|
|
29 |
handleNewMessage(entity);
|
|
|
30 |
});
|
|
|
31 |
}
|
|
|
32 |
});
|
|
|
33 |
}, 1000);
|
|
|
34 |
return () => {
|
|
|
35 |
clearInterval(checkChatInterval);
|
|
|
36 |
};
|
|
|
37 |
}, [unreadMessages, setShouldAlertNewMessage]);
|
|
|
38 |
|
|
|
39 |
const handleNewMessage = async (entity) => {
|
|
|
40 |
const existingUnread = unreads.current.findIndex(
|
|
|
41 |
(unread) => unread === entity.id
|
|
|
42 |
);
|
|
|
43 |
if (entity.not_received_messages) {
|
|
|
44 |
const resData = (await axios.post(entity.url_mark_received)).data;
|
|
|
45 |
notifyAudio.play();
|
|
|
46 |
}
|
|
|
47 |
if (entity.not_seen_messages) {
|
|
|
48 |
if (existingUnread === -1) {
|
|
|
49 |
unreads.current = [...unreads.current, entity.id];
|
|
|
50 |
}
|
|
|
51 |
} else {
|
|
|
52 |
if (existingUnread !== -1) {
|
|
|
53 |
unreads.current = unreads.current.filter(
|
|
|
54 |
(unread) => unread !== entity.id
|
|
|
55 |
);
|
|
|
56 |
}
|
|
|
57 |
}
|
|
|
58 |
// redux new message
|
|
|
59 |
if (JSON.stringify(unreadMessages) !== JSON.stringify(unreads.current)) {
|
|
|
60 |
setUnreadMessages(unreads.current);
|
|
|
61 |
}
|
|
|
62 |
};
|
|
|
63 |
|
|
|
64 |
return <div></div>;
|
|
|
65 |
};
|
|
|
66 |
|
|
|
67 |
const mapStateToProps = (state) => ({
|
|
|
68 |
unreadMessages: state.chat.unreadMessages,
|
|
|
69 |
shouldAlertNewMessage: state.chat.shouldAlertNewMessage,
|
|
|
70 |
});
|
|
|
71 |
|
|
|
72 |
const mapDispatchToProps = {
|
|
|
73 |
setHaveNewMessage: (haveNewMessage) => setHaveNewMessage(haveNewMessage),
|
|
|
74 |
setUnreadMessages: (unreadMessages) => setUnreadMessages(unreadMessages),
|
|
|
75 |
setShouldAlertNewMessage: (shouldAlertNewMessage) =>
|
|
|
76 |
setShouldAlertNewMessage(shouldAlertNewMessage),
|
|
|
77 |
};
|
|
|
78 |
|
|
|
79 |
export default connect(mapStateToProps, mapDispatchToProps)(ChatHelper);
|