-
Notifications
You must be signed in to change notification settings - Fork 3
/
app-multiple-device.js
245 lines (206 loc) · 6.29 KB
/
app-multiple-device.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
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
const { Client, MessageMedia } = require('whatsapp-web.js');
const express = require('express');
const socketIO = require('socket.io');
const qrcode = require('qrcode');
const http = require('http');
const fs = require('fs');
const { phoneNumberFormatter } = require('./helpers/formatter');
const axios = require('axios');
const port = process.env.PORT || 8000;
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.sendFile('index-multiple-device.html', {
root: __dirname
});
});
const sessions = [];
const SESSIONS_FILE = './whatsapp-sessions.json';
const createSessionsFileIfNotExists = function() {
if (!fs.existsSync(SESSIONS_FILE)) {
try {
fs.writeFileSync(SESSIONS_FILE, JSON.stringify([]));
console.log('Sessions file created successfully.');
} catch(err) {
console.log('Failed to create sessions file: ', err);
}
}
}
createSessionsFileIfNotExists();
const setSessionsFile = function(sessions) {
fs.writeFile(SESSIONS_FILE, JSON.stringify(sessions), function(err) {
if (err) {
console.log(err);
}
});
}
const getSessionsFile = function() {
return JSON.parse(fs.readFileSync(SESSIONS_FILE));
}
const createSession = function(id, description) {
console.log('Creating session: ' + id);
const SESSION_FILE_PATH = `./whatsapp-session-${id}.json`;
let sessionCfg;
if (fs.existsSync(SESSION_FILE_PATH)) {
sessionCfg = require(SESSION_FILE_PATH);
}
const client = new Client({
restartOnAuthFail: true,
puppeteer: {
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process', // <- this one doesn't works in Windows
'--disable-gpu'
],
},
session: sessionCfg
});
client.initialize();
client.on('qr', (qr) => {
console.log('QR RECEIVED', qr);
qrcode.toDataURL(qr, (err, url) => {
io.emit('qr', { id: id, src: url });
io.emit('message', { id: id, text: 'QR Code received, scan please!' });
});
});
client.on('ready', () => {
io.emit('ready', { id: id });
io.emit('message', { id: id, text: 'Whatsapp is ready!' });
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
savedSessions[sessionIndex].ready = true;
setSessionsFile(savedSessions);
});
client.on('authenticated', (session) => {
io.emit('authenticated', { id: id });
io.emit('message', { id: id, text: 'Whatsapp is authenticated!' });
sessionCfg = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function(err) {
if (err) {
console.error(err);
}
});
});
client.on('auth_failure', function(session) {
io.emit('message', { id: id, text: 'Auth failure, restarting...' });
});
client.on('disconnected', (reason) => {
io.emit('message', { id: id, text: 'Whatsapp is disconnected!' });
fs.unlinkSync(SESSION_FILE_PATH, function(err) {
if(err) return console.log(err);
console.log('Session file deleted!');
});
client.destroy();
client.initialize();
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
savedSessions.splice(sessionIndex, 1);
setSessionsFile(savedSessions);
io.emit('remove-session', id);
});
sessions.push({
id: id,
description: description,
client: client
});
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
if (sessionIndex == -1) {
savedSessions.push({
id: id,
description: description,
ready: false,
});
setSessionsFile(savedSessions);
}
}
const init = function(socket) {
const savedSessions = getSessionsFile();
if (savedSessions.length > 0) {
if (socket) {
socket.emit('init', savedSessions);
} else {
savedSessions.forEach(sess => {
createSession(sess.id, sess.description);
});
}
}
}
init();
// Socket IO
io.on('connection', function(socket) {
init(socket);
socket.on('create-session', function(data) {
console.log('Create session: ' + data.id);
createSession(data.id, data.description);
});
});
// io.on('connection', function(socket) {
// socket.emit('message', 'Connecting...');
// client.on('qr', (qr) => {
// console.log('QR RECEIVED', qr);
// qrcode.toDataURL(qr, (err, url) => {
// socket.emit('qr', url);
// socket.emit('message', 'QR Code received, scan please!');
// });
// });
// client.on('ready', () => {
// socket.emit('ready', 'Whatsapp is ready!');
// socket.emit('message', 'Whatsapp is ready!');
// });
// client.on('authenticated', (session) => {
// socket.emit('authenticated', 'Whatsapp is authenticated!');
// socket.emit('message', 'Whatsapp is authenticated!');
// console.log('AUTHENTICATED', session);
// sessionCfg = session;
// fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function(err) {
// if (err) {
// console.error(err);
// }
// });
// });
// client.on('auth_failure', function(session) {
// socket.emit('message', 'Auth failure, restarting...');
// });
// client.on('disconnected', (reason) => {
// socket.emit('message', 'Whatsapp is disconnected!');
// fs.unlinkSync(SESSION_FILE_PATH, function(err) {
// if(err) return console.log(err);
// console.log('Session file deleted!');
// });
// client.destroy();
// client.initialize();
// });
// });
// Send message
app.post('/send-message', (req, res) => {
const sender = req.body.sender;
const number = phoneNumberFormatter(req.body.number);
const message = req.body.message;
const client = sessions.find(sess => sess.id == sender).client;
client.sendMessage(number, message).then(response => {
res.status(200).json({
status: true,
response: response
});
}).catch(err => {
res.status(500).json({
status: false,
response: err
});
});
});
server.listen(port, function() {
console.log('App running on *: ' + port);
});