Spaces:
Running

File size: 2,150 Bytes
71601b1
 
 
 
 
 
 
 
 
 
 
 
 
33985fa
71601b1
 
 
 
 
33985fa
71601b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb97224
71601b1
 
 
 
 
 
 
 
 
 
 
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
const Message = require('../models/Message');
const Dialog = require('../models/Dialog');

const getDialogId = (u1, u2) => [String(u1).toLowerCase(), String(u2).toLowerCase()].sort().join('_');

const updateDialogLastMessage = async (dialogId) => {
    try {
        const lastMsg = await Message.findOne({ dialog_id: dialogId, isService: { $ne: true } }).sort({ timestamp: -1 }).lean();
        if (lastMsg) {
            await Dialog.updateOne(
                { dialog_id: dialogId },
                {
                    $set: {
                        lastMessageText: lastMsg.is_encrypted ? '🔒' : lastMsg.text,
                        lastSender: lastMsg.sender,
                        lastMessageTimestamp: lastMsg.timestamp,
                        lastIsAudio: lastMsg.isAudio || false,
                        lastIsMusic: lastMsg.isMusic || false,
                        lastIsVideoNote: lastMsg.isVideoNote || false,
                        lastIsEncrypted: lastMsg.is_encrypted || false,
                        lastFileUrl: lastMsg.fileUrls && lastMsg.fileUrls.length > 0 ? lastMsg.fileUrls[0] : (lastMsg.fileUrl || null),
                        lastFileName: lastMsg.fileName || null
                    },
                    $unset: { lastCallType: '', lastCallDuration: '', lastCallWithVideo: '' }
                }
            );
        } else {
            await Dialog.updateOne(
                { dialog_id: dialogId },
                {
                    $set: {
                        lastMessageText: '',
                        lastSender: null,
                        lastMessageTimestamp: new Date(0),
                        lastIsAudio: false,
                        lastIsMusic: false,
                        lastIsVideoNote: false,
                        lastIsEncrypted: false,
                        lastFileUrl: null,
                        lastFileName: null
                    },
                    $unset: { lastCallType: '', lastCallDuration: '', lastCallWithVideo: '' }
                }
            );
        }
    } catch {}
};

module.exports = { getDialogId, updateDialogLastMessage };