forked from danielcardeenas/sulla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-unread-messages.js
93 lines (89 loc) Β· 2.5 KB
/
get-unread-messages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Retrieves all undread Messages
* @param {boolean} includeMe
* @param {boolean} includeNotifications
* @param {boolean} useUnreadCount
* @param {Function} done Optional callback
*/
export function getUnreadMessages(
includeMe,
includeNotifications,
useUnreadCount,
done
) {
const chats = window.Store.Chat.models;
const output = [];
for (const chat in chats) {
if (isNaN(chat)) {
continue;
}
const messageGroupObj = chats[chat];
let messageGroup = WAPI._serializeChatObj(messageGroupObj);
messageGroup.messages = [];
const messages = messageGroupObj.msgs._models;
for (let i = messages.length - 1; i >= 0; i--) {
const messageObj = messages[i];
if (
typeof messageObj.isNewMsg != 'boolean' ||
messageObj.isNewMsg === false
) {
continue;
} else {
messageObj.isNewMsg = false;
let message = WAPI.processMessageObj(
messageObj,
includeMe,
includeNotifications
);
if (message) {
messageGroup.messages.push(message);
}
}
}
if (messageGroup.messages.length > 0) {
output.push(messageGroup);
} else {
// No messages with isNewMsg true
if (useUnreadCount) {
// Will use unreadCount attribute to fetch last n messages from sender
let n = messageGroupObj.unreadCount;
for (let i = messages.length - 1; i >= 0; i--) {
const messageObj = messages[i];
if (n > 0) {
if (!messageObj.isSentByMe) {
let message = WAPI.processMessageObj(
messageObj,
includeMe,
includeNotifications
);
messageGroup.messages.unshift(message);
n -= 1;
}
} else if (n === -1) {
// chat was marked as unread so will fetch last message as unread
if (!messageObj.isSentByMe) {
let message = WAPI.processMessageObj(
messageObj,
includeMe,
includeNotifications
);
messageGroup.messages.unshift(message);
break;
}
} else {
// unreadCount = 0
break;
}
}
if (messageGroup.messages.length > 0) {
messageGroupObj.unreadCount = 0; // reset unread counter
output.push(messageGroup);
}
}
}
}
if (done !== undefined) {
done(output);
}
return output;
}