forked from raweee/node-red-contrib-whatsapp-link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whatsappLink.js
239 lines (218 loc) · 9.21 KB
/
whatsappLink.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
module.exports = function(RED) {
const QRCode = require('qrcode');
const FS = require('node:fs')
const OS = require('os');
const Path = require('path');
let userDir = OS.homedir();
let whatsappLinkDir = Path.join(userDir, '.node-red', 'Whatsapp-Link');
let whatsappLinkDirSocket = Path.join(whatsappLinkDir, 'WA-Sockets');
// let whatsappLinkDirSocketLogs = Path.join(whatsappLinkDir, 'WA-Sockets-logs');
function RemoteClientNode(n) {
RED.nodes.createNode(this,n);
var WAnode = this;
var clientType = n.clientType;
var loopTime = n.loopTime;
loopTime = loopTime + Math.random();
loopTime = loopTime * 60 * 60 * 1000 || 3600000;
var onlineStatus = n.onlineStatus;
var whatsappConnectionStatus;
var client
if (clientType ==="waWebClient"){
const { Client, LocalAuth } = require('whatsapp-web.js');
var WAConnect = function(){
const webClient = new Client({
authStrategy : new LocalAuth({
dataPath : whatsappLinkDir
}),
puppeteer : {
headless : true,
args : ['--no-sandbox', '--disable-setuid-sandbox', '--user-data-dir=' + WAnode.id]
}
});
try {
webClient.initialize();
WAnode.log("Status : Initializing Whatsapp..");
}
catch(e) {
WAnode.log(`Error : Unable to start Whatsapp. Try Again..`);
};
return webClient ;
};
client = WAConnect();
WAnode.connectionSetupID = setInterval(connectionSetup, 10000);
async function pressenceUpdate(OLS){
try {
if (!OLS){
await client.sendPresenceUnavailable();
WAnode.log(`Whatsapp marked as Offline`)
} else {
await client.sendPresenceAvailable();
}
} catch (e){
WAnode.error("Error at pressence : " + e)
}
}
function WAClose(){
try {
client.destroy();
}
catch(e){
WAnode.err(`Error : Too many instructions! Try again.`)
}
};
var WARestart = function(){
WAClose();
WAConnect();
}
async function connectionSetup(){
try {
whatsappConnectionStatus = await client.getState();
if(whatsappConnectionStatus === "CONNECTED"){
clearInterval(WAnode.connectionSetupID);
}
else {
WAnode.log(`Status : Connecting to Whatsapp...`);
}
}
catch(e){
WAnode.log(`Error : Waiting for Initializion...`);
}
};
//QR-Code on Terminal and Ready Status.
client.on("qr", (qr)=>{
clearInterval(WAnode.connectionSetupID);
QRCode.toString(qr, {type : 'terminal', small:true }, function(err, QRTerminal){
WAnode.log(`To Connect, Scan the QR Code through your Whatsapp Mobile App.`)
console.log("");
console.log(QRTerminal);
});
});
client.on("ready", ()=>{
WAnode.log(`Status : Whatsapp Connected`);
pressenceUpdate(onlineStatus);
});
client.WAConnect = WAConnect;
client.WARestart = WARestart;
client.WAClose = WAClose;
client.clientType = clientType;
WAnode.client = client;
};
if (clientType === "waSocketClient"){
const makeWASocket = require('@adiwajshing/baileys');
const { useMultiFileAuthState } = makeWASocket;
const pino = require('pino');
async function connectSocketClient() {
const { state, saveCreds } = await useMultiFileAuthState(whatsappLinkDirSocket);
// const loggerFile = pino.destination(whatsappLinkDirSocketLogs);
const socketClient = makeWASocket.default({
printQRInTerminal: false,
logger:pino({level: "silent"}),
auth : state,
browser: ["Node-RED", "Chrome", "4.0.0"],
markOnlineOnConnect: onlineStatus,
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage || message.templateMessage || message.listMessage
);
if (requiresPatch) {
message = {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
};
}
return message;
},
})
socketClient.ev.on('creds.update', saveCreds);
socketClient.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if (connection === 'close') {
// reconnect if not logged out
if (
lastDisconnect &&
lastDisconnect.error &&
lastDisconnect.error.output &&
(lastDisconnect.error.output.statusCode === 410 ||
lastDisconnect.error.output.statusCode === 428 ||
lastDisconnect.error.output.statusCode === 515)
) {
connectSocketClient()
} else {
if (
lastDisconnect &&
lastDisconnect.error &&
lastDisconnect.error.output &&
lastDisconnect.error.output.statusCode === 401
) {
FS.rmSync(whatsappLinkDirSocket, {recursive : true, force: true})
connectSocketClient()
} else {
WAnode.log("Error : " + lastDisconnect?.error)
}
}
}
})
return socketClient
};
client = connectSocketClient();
client.onlineStatus = onlineStatus;
client.clientType = clientType;
client.clientStartFunction = connectSocketClient;
WAnode.client = client
};
async function loopStatusUpdate(){
try {
if (clientType === "waSocketClient"){
let myClient = await WAnode.client;
let id = myClient.user.id;
await myClient.sendPresenceUpdate("available", id)
if (!onlineStatus) {
setTimeout(()=> {
myClient.sendPresenceUpdate("unavailable", id)
},17000)
};
}
else {
await WAnode.client.sendPresenceAvailable();
if (!onlineStatus) {
setTimeout(()=> {
WAnode.client.sendPresenceUnavailable();
},17000)
};
}}
catch(e){
WAnode.error("Error in whatsapp Ping.")
}
}
var loopStatusUpdateID = setInterval(()=> {
loopStatusUpdate();
}, loopTime)
this.on('close', (removed, done)=>{
clearInterval(loopStatusUpdateID);
if(removed){
if(clientType === "waWebClient"){
clearInterval(WAnode.connectionSetupID);
WAnode.client.WAClose();
} else {
// WAnode.client.removeAllListeners();
WAnode.client.end();
}
}
else {
if(clientType === "waWebClient"){
clearInterval(WAnode.connectionSetupID);
WAnode.client.WAClose();
} else { WAnode.client.end() }
}
done();
});
}
RED.nodes.registerType("whatsappLink",RemoteClientNode);
}