forked from ChickenAI/multizlogin
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy patheventListeners.js
More file actions
144 lines (125 loc) · 5.05 KB
/
eventListeners.js
File metadata and controls
144 lines (125 loc) · 5.05 KB
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
// eventListeners.js
import { getWebhookConfig, triggerN8nWebhook } from './helpers.js';
import fs from 'fs';
import { loginZaloAccount, zaloAccounts } from './api/zalo/zalo.js';
import { broadcastLoginSuccess } from './server.js';
import { addLog } from './routes-ui.js';
export const reloginAttempts = new Map();
const RELOGIN_COOLDOWN = 5 * 60 * 1000;
export function setupEventListeners(api, loginResolve) {
const ownId = api.getOwnId();
api.listener.on('message', (msg) => {
const config = getWebhookConfig(ownId);
const webhookUrl = config?.url;
// Log message
if (msg.isSelf) {
const content = msg.data?.content ? msg.data.content : (msg.data?.msgType === 'chat.photo' ? '[Hình ảnh]' : '[File/Khác]');
addLog('Gửi tin nhắn', content, ownId, { type: msg.data?.msgType, toId: msg.threadId, msgId: msg.data?.msgId });
} else {
const content = msg.data?.content ? msg.data.content : (msg.data?.msgType === 'chat.photo' ? '[Hình ảnh]' : '[File/Khác]');
addLog('Nhận tin nhắn', content, ownId, { type: msg.data?.msgType, fromId: msg.threadId, msgId: msg.data?.msgId });
}
if (webhookUrl) {
let isAPI = false;
if (msg.isSelf && msg.data?.content) {
const account = zaloAccounts.find((acc) => acc.ownId === ownId);
const lastMsg = (account?.lastAPIMessage || "").toString();
const currentContent = (msg.data?.content || "").toString();
if (lastMsg && lastMsg === currentContent)
isAPI = true;
}
triggerN8nWebhook({ ...msg, AccountID: ownId, isAPI, isself: msg.isSelf }, webhookUrl);
}
});
api.listener.on('group_event', (data) => {
const config = getWebhookConfig(ownId);
const webhookUrl = config?.url;
const receiveGroupEvent = config?.settings?.receiveGroupEvent ?? true;
if (webhookUrl && receiveGroupEvent) {
triggerN8nWebhook({ ...data, AccountID: ownId }, webhookUrl);
}
});
api.listener.on('reaction', (reaction) => {
const config = getWebhookConfig(ownId);
const webhookUrl = config?.url;
const receiveReaction = config?.settings?.receiveReaction ?? true;
console.log(`Nhận reaction cho ${ownId}:`, reaction);
if (webhookUrl && receiveReaction) {
triggerN8nWebhook({ ...reaction, AccountID: ownId }, webhookUrl);
}
});
api.listener.onConnected(() => {
console.log('Connected');
loginResolve('login_success');
broadcastLoginSuccess();
});
api.listener.onClosed((code, reason) => {
console.log(`Closed - API listener đã ngắt kết nối. Code: ${code}, Reason: ${reason}`);
// Nếu bị ngắt kết nối do trùng lặp (3000) hoặc bị đá (3003), báo cáo logout về webhook
if (code === 3000 || code === 3003) {
const config = getWebhookConfig(ownId);
if (config?.url) {
triggerN8nWebhook({
action: 'logout',
ownId: ownId,
reason: `Bị ngắt kết nối (Code: ${code}, Reason: ${reason})`
}, config.url);
}
}
handleRelogin(api);
});
api.listener.onError((error) => {
console.error('Error:', error);
if (error.message.includes('QR expired')) {
console.log('QR code đã hết hạn, thông báo cho client...');
broadcastLoginSuccess('qr_expired');
}
});
}
async function handleRelogin(api) {
try {
console.log('Đang thử đăng nhập lại...');
const ownId = api.getOwnId();
if (!ownId) {
console.error('Không thể xác định ownId, không thể đăng nhập lại');
return;
}
const lastReloginTime = reloginAttempts.get(ownId);
const now = Date.now();
if (lastReloginTime && now - lastReloginTime < RELOGIN_COOLDOWN) {
console.log(
`Bỏ qua việc đăng nhập lại tài khoản ${ownId}, đã thử cách đây ${Math.floor(
(now - lastReloginTime) / 1000
)} giây`
);
return;
}
reloginAttempts.set(ownId, now);
const accountInfo = zaloAccounts.find((acc) => acc.ownId === ownId);
const customProxy = accountInfo?.proxy || null;
const cookiesDir = '/app/cookies';
const cookieFile = `${cookiesDir}/cred_${ownId}.json`;
if (!fs.existsSync(cookieFile)) {
console.error(`Không tìm thấy file cookie cho tài khoản ${ownId}`);
return;
}
const cookie = JSON.parse(fs.readFileSync(cookieFile, 'utf-8'));
console.log(`Đang đăng nhập lại tài khoản ${ownId} với proxy ${customProxy || 'không có'}...`);
try {
await loginZaloAccount(customProxy, cookie);
console.log(`Đã đăng nhập lại thành công tài khoản ${ownId}`);
} catch (loginError) {
console.error(`Đăng nhập lại thất bại cho ${ownId}:`, loginError.message);
const config = getWebhookConfig(ownId);
if (config?.url) {
triggerN8nWebhook({
action: 'logout',
ownId: ownId,
reason: `Đăng nhập lại thất bại: ${loginError.message}`
}, config.url);
}
}
} catch (error) {
console.error('Lỗi khi thử đăng nhập lại:', error);
}
}