Spaces:
Running

File size: 9,995 Bytes
71601b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6529592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71601b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6529592
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
const User = require('../models/User');
const Message = require('../models/Message');
const Dialog = require('../models/Dialog');
const Room = require('../models/Room');
const { obscure } = require('../utils/crypto');
const { getDialogId } = require('../utils/dialog');
const { st } = require('../constants/translations');
const { getIO } = require('../socket/io');
const { sendPushNotification } = require('./push');

const broadcastSystemAction = async (sender, receiver, actionText) => {
    try {
        const io = getIO();
        const user = await User.findOne({ username: sender }).lean();
        const name = user?.displayName || sender;
        const finalText = `${name} ${actionText}`;
        const hiddenText = obscure(finalText);

        let dialogId = null;
        let targets = [];
        if (receiver.startsWith('room_')) {
            dialogId = receiver;
            const room = await Room.findOne({ roomId: receiver }).lean();
            if (room) targets = room.members;
        } else {
            dialogId = getDialogId(sender, receiver);
            targets = [sender, receiver];
        }

        const newMsgDoc = await Message.create({
            dialog_id: dialogId,
            sender: sender,
            receiver: receiver,
            text: hiddenText,
            isService: true,
            is_read: true,
            timestamp: new Date()
        });

        const msgData = {
            id: newMsgDoc._id.toString(),
            sender: sender,
            receiver: receiver,
            text: finalText,
            timestamp: newMsgDoc.timestamp,
            isVerified: user?.isVerified || false,
            isService: true,
            is_read: true,
            displayName: name,
            senderAvatar: user?.avatar || null
        };

        targets.forEach(m => {
            io.to(m).emit('new_message', msgData);
        });

        if (receiver.startsWith('room_')) {
            await Room.updateOne({ roomId: receiver }, { $set: { timestamp: newMsgDoc.timestamp } });
        } else {
            await Dialog.findOneAndUpdate(
                { dialog_id: dialogId },
                {
                    $set: {
                        participants: [sender, receiver],
                        lastMessageTimestamp: newMsgDoc.timestamp
                    }
                },
                { upsert: true }
            );
        }

        targets.forEach(m => {
            io.to(m).emit('update_chat_list');
        });
    } catch (e) { }
};

const sendLoginNotification = async (username, device, ip, lang = 'ru') => {
    try {
        const io = getIO();
        const systemUser = "4send_system";
        const text = `⚠️ ${st('Новый вход в аккаунт', lang)}\n\n${st('Устройство:', lang)} ${device}\n${st('IP-адрес:', lang)} ${ip}\n${st('Время:', lang)} ${new Date().toLocaleString(lang === 'en' ? 'en-US' : 'ru-RU')}\n\n${st('Если это были не вы, немедленно завершите сеанс в Настройки -> Конфиденциальность -> Активные сеансы и измените пароль.', lang)}`;
        const hiddenText = obscure(text);
        const dialogId = getDialogId(systemUser, username);

        const newMsgDoc = await Message.create({
            dialog_id: dialogId,
            sender: systemUser,
            receiver: username,
            text: hiddenText,
            is_read: false,
            read_by: [systemUser],
            timestamp: new Date()
        });

        await Dialog.findOneAndUpdate(
            { dialog_id: dialogId },
            {
                $set: {
                    participants: [systemUser, username],
                    lastMessageText: hiddenText,
                    lastSender: systemUser,
                    lastMessageTimestamp: newMsgDoc.timestamp,
                    lastIsAudio: false,
                    lastIsMusic: false,
                    lastIsVideoNote: false,
                    lastFileUrl: null,
                    lastFileName: null
                },
                $inc: { [`unreadCounts.${username}`]: 1 }
            },
            { upsert: true, new: true }
        );

        const msgData = {
            id: newMsgDoc._id.toString(),
            sender: systemUser,
            receiver: username,
            text: text,
            timestamp: newMsgDoc.timestamp,
            isVerified: true,
            is_read: false,
            displayName: st('Системные уведомления', 'ru')
        };

        if (io) {
            io.to(username).emit('new_message', msgData);
            io.to(username).emit('update_chat_list');
        }
    } catch (err) {}
};

const sendOAuthCode = async (username, appName, code, device, ip, lang = 'ru') => {
    try {
        const io = getIO();
        const systemUser = '4send_system';
        const app = String(appName || '4SEND').slice(0, 48);
        const text = `${st('Код для входа', lang)} · ${app}\n\n${code}\n\n${st('Код действует 10 минут. Никому его не сообщайте.', lang)}\n${st('Если это были не вы, смените пароль.', lang)}\n\n${st('Устройство:', lang)} ${device}\n${st('IP-адрес:', lang)} ${ip}\n${st('Время:', lang)} ${new Date().toLocaleString(lang === 'en' ? 'en-US' : 'ru-RU')}`;
        const hiddenText = obscure(text);
        const dialogId = getDialogId(systemUser, username);

        const newMsgDoc = await Message.create({
            dialog_id: dialogId,
            sender: systemUser,
            receiver: username,
            text: hiddenText,
            is_read: false,
            read_by: [systemUser],
            timestamp: new Date()
        });

        await Dialog.findOneAndUpdate(
            { dialog_id: dialogId },
            {
                $set: {
                    participants: [systemUser, username],
                    lastMessageText: hiddenText,
                    lastSender: systemUser,
                    lastMessageTimestamp: newMsgDoc.timestamp,
                    lastIsAudio: false,
                    lastIsMusic: false,
                    lastIsVideoNote: false,
                    lastFileUrl: null,
                    lastFileName: null
                },
                $inc: { [`unreadCounts.${username}`]: 1 }
            },
            { upsert: true, new: true }
        );

        const msgData = {
            id: newMsgDoc._id.toString(),
            sender: systemUser,
            receiver: username,
            text,
            timestamp: newMsgDoc.timestamp,
            isVerified: true,
            is_read: false,
            displayName: st('Системные уведомления', lang)
        };

        if (io) {
            io.to(username).emit('new_message', msgData);
            io.to(username).emit('update_chat_list');
        }

        await sendPushNotification(username, {
            notification: { title: `4SEND · ${app}`, body: `${st('Код входа:', lang)} ${code}` },
            android: { notification: { channelId: '4send_channel', priority: 'high', sound: 'default', icon: '/ico.png' } },
            webpush: { notification: { icon: '/ico.png', badge: '/ico.png' } }
        });
    } catch {}
};

const sendInternalNotification = async (text) => {
    try {
        const io = getIO();
        const systemUser = "4send_system";
        const admins = await User.find({ role: 'admin' }).lean();
        if (!admins.length) return;

        const hiddenText = obscure(text);
        const timestamp = new Date();

        for (const adminUser of admins) {
            const adminName = adminUser.username;
            const dialogId = getDialogId(systemUser, adminName);

            const newMsgDoc = await Message.create({
                dialog_id: dialogId,
                sender: systemUser,
                receiver: adminName,
                text: hiddenText,
                is_read: false,
                read_by: [systemUser],
                timestamp: timestamp
            });

            await Dialog.findOneAndUpdate(
                { dialog_id: dialogId },
                {
                    $set: {
                        participants: [systemUser, adminName],
                        lastMessageText: hiddenText,
                        lastSender: systemUser,
                        lastMessageTimestamp: timestamp,
                        lastIsAudio: false,
                        lastIsMusic: false,
                        lastIsVideoNote: false,
                        lastFileUrl: null,
                        lastFileName: null
                    },
                    $inc: { [`unreadCounts.${adminName}`]: 1 }
                },
                { upsert: true, new: true }
            );

            const msgData = {
                id: newMsgDoc._id.toString(),
                sender: systemUser,
                receiver: adminName,
                text: text,
                timestamp: timestamp,
                isVerified: true,
                is_read: false,
                displayName: st('Системные уведомления', 'ru')
            };

            if (io) {
                io.to(adminName).emit('new_message', msgData);
                io.to(adminName).emit('update_chat_list');
            }

            await sendPushNotification(adminName, {
                notification: { title: st('Системное уведомление', 'ru'), body: text.substring(0, 60) + '...' },
                android: { notification: { channelId: '4send_channel', priority: 'high', sound: 'default', icon: '/ico.png' } },
                webpush: { notification: { icon: '/ico.png', badge: '/ico.png' } }
            });
        }
    } catch (err) {}
};

module.exports = { broadcastSystemAction, sendLoginNotification, sendOAuthCode, sendInternalNotification };