-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
client.js
117 lines (92 loc) · 2.78 KB
/
client.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
module.exports = function (RED) {
'use strict'
const { ev, create } = require('@open-wa/wa-automate')
const patch = require('./patch')
const RETRY_TIMEOUT = 10000
const EVENTS = [
'onMessage',
'onAck',
'onAddedToGroup'
]
const noop = () => {}
function WhatsappClient (config) {
RED.nodes.createNode(this, config)
const node = this
var client = null
function registerEvents () {
for (const event of EVENTS) {
client[event](onEvent.bind(node, event))
}
}
function onEvent (eventName, ...args) {
node.emit('clientEvent', eventName, ...args)
}
function onQrCode (qrCode) {
node.emit('qrCode', qrCode)
}
async function startClient () {
ev.on(`qr.${config.session}`, onQrCode)
client = await create({
sessionId: config.session,
headless: config.headless,
devtools: config.devtools,
inDocker: config.inDocker,
useChrome: config.useChrome
})
node.log('Whatsapp client created for session ' + config.session)
// support for sendMessageToId
patch(client)
client.onStateChanged((state) => {
if (state === 'CONFLICT') {
client.forceRefocus()
}
node.emit('stateChange', state)
})
registerEvents()
node.emit('ready', client)
}
async function closeClient (done) {
done = done || noop
node.log('Closing Whatsapp client ' + config.session)
if (client) {
ev.removeAllListeners()
try {
await client.kill()
node.log('Session ' + config.session + ' closed')
} catch (err) {
node.error('Error while closing Whatsapp client "' + config.session + '": ' + err.message)
} finally {
done()
}
} else {
done()
}
}
node.on('close', closeClient)
process.on('SIGINT', function () {
closeClient()
})
// check for registered nodes using configuration
node.registeredNodeList = {}
// trick used to not start client if there are not nodes using this client
node.register = function (nodeToRegister) {
node.registeredNodeList[nodeToRegister.id] = nodeToRegister
if (Object.keys(node.registeredNodeList).length === 1) {
startClient()
.catch((err) => {
node.error('Error while starting Whatsapp client "' + config.session + '": ' + err.message)
// retry
setTimeout(node.register.bind(node, nodeToRegister), RETRY_TIMEOUT)
})
}
}
node.restart = async function () {
if (client) {
node.log('Restarting client ' + config.session)
await client.kill()
await startClient()
}
}
}
RED.nodes.registerType('whatsapp-client', WhatsappClient)
}