forked from ChickenAI/multizlogin
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathserver.js
More file actions
129 lines (110 loc) · 4.01 KB
/
server.js
File metadata and controls
129 lines (110 loc) · 4.01 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
import dotenv from 'dotenv';
import express from 'express';
import routes from './routes.js';
import fs from 'fs';
import { zaloAccounts, loginZaloAccount } from './api/zalo/zalo.js';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import fileUpload from 'express-fileupload';
import session from 'express-session';
import { startTaskPuller } from './taskPuller.js';
import { startHealthCheck } from './healthCheck.js';
import { addLog } from './routes-ui.js';
// Load biến môi trường từ file .env
dotenv.config();
const app = express();
const LISTEN_IP = '0.0.0.0';
const INTERNAL_PORT = 3000;
export const server = createServer(app); // Export server
export const wss = new WebSocketServer({ server }); // Export wss
wss.on('connection', (ws) => {
console.log('Client connected to WebSocket');
ws.on('close', () => console.log('Client disconnected'));
});
wss.on('error', (error) => {
console.error('WebSocket error:', error);
});
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: process.env.NODE_ENV === 'production', maxAge: 24 * 60 * 60 * 1000 }
}));
app.use(fileUpload());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/', routes);
export function broadcastEvent(event, data = {}) {
const payload = JSON.stringify({ event, ...data });
wss.clients.forEach((client) => {
if (client.readyState === client.OPEN) {
client.send(payload);
}
});
}
export function broadcastLoginSuccess() {
broadcastEvent('login_success');
}
// Async wrapper for cookie loading
async function loadCookies() {
try {
const cookiesDir = '/app/cookies';
if (!fs.existsSync(cookiesDir)) {
console.log('Cookies directory not found, skipping cookie loading');
return;
}
const cookieFiles = fs.readdirSync(cookiesDir);
if (zaloAccounts.length >= cookieFiles.length) {
console.log('No new cookies to load');
return;
}
console.log('Đang đăng nhập lại từ cookie...');
for (const file of cookieFiles) {
if (file.startsWith('cred_') && file.endsWith('.json')) {
const ownId = file.substring(5, file.length - 5);
try {
const cookie = JSON.parse(fs.readFileSync(`${cookiesDir}/${file}`, 'utf-8'));
await loginZaloAccount(null, cookie, (event) => {
// Handle background events during auto-reconnect
if (event.type === 'error') {
console.error(`[Zalo:${ownId}] Background error:`, event.data.message);
}
broadcastEvent('zalo_status', { ownId, ...event });
});
console.log(`Đã đăng nhập lại tài khoản ${ownId} từ cookie.`);
addLog('Auth', `Tài khoản ${ownId} đã đăng nhập lại từ cookie`);
} catch (error) {
console.error(`Lỗi khi đăng nhập lại tài khoản ${ownId}:`, error);
addLog('Auth Error', `Lỗi đăng nhập tài khoản ${ownId}: ${error.message}`);
}
}
}
} catch (error) {
console.error('Error in loadCookies:', error);
}
}
// Start server after loading cookies
async function startServer() {
try {
await loadCookies();
server.listen(INTERNAL_PORT, LISTEN_IP, () => {
console.log(`Actually listening on port ${INTERNAL_PORT}`);
addLog('System', `Server đang lắng nghe trên cổng ${INTERNAL_PORT}`);
startTaskPuller();
startHealthCheck();
});
server.on('error', (error) => {
console.error('Server error:', error);
});
} catch (error) {
console.error('Error starting server:', error);
process.exit(1);
}
}
startServer();
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
});