-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
listener.layer.ts
569 lines (536 loc) · 16.9 KB
/
listener.layer.ts
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*
* This file is part of WPPConnect.
*
* WPPConnect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WPPConnect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/
import { EventEmitter, captureRejectionSymbol } from 'events';
import { Page } from 'puppeteer';
import { CreateConfig } from '../../config/create-config';
import { evaluateAndReturn } from '../helpers';
import { ExposedFn } from '../helpers/exposed.enum';
import {
Ack,
Chat,
LiveLocation,
Message,
ParticipantEvent,
PresenceEvent,
} from '../model';
import { MessageType, SocketState, SocketStream } from '../model/enum';
import { InterfaceMode } from '../model/enum/interface-mode';
import { InterfaceState } from '../model/enum/interface-state';
import { ProfileLayer } from './profile.layer';
declare global {
interface Window {
onMessage: any;
onAnyMessage: any;
onStateChange: any;
onStreamChange: any;
onIncomingCall: any;
onAck: any;
}
}
export class ListenerLayer extends ProfileLayer {
private listenerEmitter = new EventEmitter({
captureRejections: true,
});
constructor(public page: Page, session?: string, options?: CreateConfig) {
super(page, session, options);
this.listenerEmitter.on(ExposedFn.onInterfaceChange, (state) => {
this.log('http', `Current state: ${state.mode} (${state.displayInfo})`);
});
this.listenerEmitter[captureRejectionSymbol] = (
reason: any,
event: string
) => {
let message = `Unhandled Rejection in a ${event} event: `;
if (reason instanceof Error) {
if (reason.stack) {
message += reason.stack;
} else {
message += reason.toString();
}
} else {
message += JSON.stringify(reason);
}
this.log('error', reason);
};
}
protected async afterPageScriptInjected() {
await super.afterPageScriptInjected();
const functions = [
...Object.values(ExposedFn),
'onAddedToGroup',
'onIncomingCall',
'onRevokedMessage',
'onReactionMessage',
];
for (const func of functions) {
const has = await this.page
.evaluate((func) => typeof window[func] === 'function', func)
.catch(() => false);
if (!has) {
this.log('debug', `Exposing ${func} function`);
await this.page
.exposeFunction(func, (...args) =>
this.listenerEmitter.emit(func, ...args)
)
.catch(() => {});
}
}
await this.page
.evaluate(() => {
try {
if (!window['onMessage'].exposed) {
WPP.on('chat.new_message', (msg) => {
if (msg.isSentByMe || msg.isStatusV3) {
return;
}
const serialized = WAPI.processMessageObj(msg, false, false);
if (serialized) {
window['onMessage'](serialized);
}
});
window['onMessage'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onAck'].exposed) {
window.WAPI.waitNewAcknowledgements(window['onAck']);
window['onAck'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onAnyMessage'].exposed) {
WPP.on('chat.new_message', (msg) => {
const serialized = WAPI.processMessageObj(msg, true, false);
if (serialized) {
window['onAnyMessage'](serialized);
}
});
window['onAnyMessage'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onStateChange'].exposed) {
window.WAPI.onStateChange(window['onStateChange']);
window['onStateChange'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onStreamChange'].exposed) {
window.WAPI.onStreamChange(window['onStreamChange']);
window['onStreamChange'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onAddedToGroup'].exposed) {
window.WAPI.onAddedToGroup(window['onAddedToGroup']);
window['onAddedToGroup'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onIncomingCall'].exposed) {
window.WAPI.onIncomingCall(window['onIncomingCall']);
window['onIncomingCall'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onInterfaceChange'].exposed) {
window.WAPI.onInterfaceChange(window['onInterfaceChange']);
window['onInterfaceChange'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onNotificationMessage'].exposed) {
window.WAPI.onNotificationMessage(window['onNotificationMessage']);
window['onNotificationMessage'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onPresenceChanged'].exposed) {
WPP.on('chat.presence_change', window['onPresenceChanged']);
window['onPresenceChanged'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onLiveLocation'].exposed) {
window.WAPI.onLiveLocation(window['onLiveLocation']);
window['onLiveLocation'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onRevokedMessage'].exposed) {
WPP.on('chat.msg_revoke', (data) => {
const eventData = {
author: data.author,
from: data.from,
to: data.to,
id: data.id._serialized,
refId: data.refId._serialized,
};
window['onRevokedMessage'](eventData);
});
window['onRevokedMessage'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onReactionMessage'].exposed) {
WPP.on('chat.new_reaction', (data) => {
const eventData = {
id: data.id,
msgId: data.msgId,
reactionText: data.reactionText,
read: data.read,
orphan: data.orphan,
orphanReason: data.orphanReason,
timestamp: data.timestamp,
};
window['onReactionMessage'](eventData);
});
window['onReactionMessage'].exposed = true;
}
} catch (error) {
console.error(error);
}
try {
if (!window['onParticipantsChanged'].exposed) {
WPP.on('group.participant_changed', (participantChangedEvent) => {
window['onParticipantsChanged'](participantChangedEvent);
});
window['onParticipantsChanged'].exposed = true;
}
} catch (error) {
console.error(error);
}
})
.catch(() => {});
}
/**
* Register the event and create a disposable object to stop the listening
* @param event Name of event
* @param listener The function to execute
* @returns Disposable object to stop the listening
*/
protected registerEvent(
event: string | symbol,
listener: (...args: any[]) => void
) {
this.listenerEmitter.on(event, listener);
return {
dispose: () => {
this.listenerEmitter.off(event, listener);
},
};
}
/**
* @event Listens to all new messages received only.
* @returns Disposable object to stop the listening
*/
public onMessage(callback: (message: Message) => void) {
return this.registerEvent(ExposedFn.OnMessage, callback);
}
/**
* @event Listens to all new messages, sent and received.
* @param to callback
* @fires Message
* @returns Disposable object to stop the listening
*/
public onAnyMessage(callback: (message: Message) => void) {
return this.registerEvent(ExposedFn.OnAnyMessage, callback);
}
/**
* @event Listens to all notification messages, like group changes, join, leave
* @param to callback
* @fires Message
* @returns Disposable object to stop the listening
*/
public onNotificationMessage(callback: (message: Message) => void) {
return this.registerEvent(ExposedFn.onNotificationMessage, callback);
}
/**
* @event Listens List of mobile states
* @returns Disposable object to stop the listening
*/
public onStateChange(callback: (state: SocketState) => void) {
return this.registerEvent(ExposedFn.onStateChange, callback);
}
/**
* @event Returns the current state of the connection
* @returns Disposable object to stop the listening
*/
public onStreamChange(callback: (state: SocketStream) => void) {
return this.registerEvent(ExposedFn.onStreamChange, callback);
}
/**
* @event Listens to interface mode change See {@link InterfaceState} and {@link InterfaceMode} for details
* @returns Disposable object to stop the listening
*/
public onInterfaceChange(
callback: (state: {
displayInfo: InterfaceState;
mode: InterfaceMode;
}) => void
) {
return this.registerEvent(ExposedFn.onInterfaceChange, callback);
}
/**
* @event Listens to messages acknowledgement Changes
* @returns Disposable object to stop the listening
*/
public onAck(callback: (ack: Ack) => void) {
return this.registerEvent(ExposedFn.onAck, callback);
}
/**
* Escuta os eventos de Localização em tempo real de todos os chats
* @event Eventos de Localização em tempo real
* @param callback Função para ser executada quando houver alterações
* @returns Objeto descartável para parar de ouvir
*/
public onLiveLocation(callback: (liveLocationEvent: LiveLocation) => void): {
dispose: () => void;
};
/**
* Escuta os eventos de Localização em tempo real
* @event Eventos de Localização em tempo real
* @param id Único ID ou lista de IDs de contatos para acompanhar a localização
* @param callback Função para ser executada quando houver alterações
* @returns Objeto descartável para parar de ouvir
*/
public onLiveLocation(
id: string | string[],
callback: (liveLocationEvent: LiveLocation) => void
): { dispose: () => void };
public onLiveLocation(
id: any,
callback?: (liveLocationEvent: LiveLocation) => void
) {
const ids: string[] = [];
if (typeof id === 'function') {
callback = id;
} else if (Array.isArray(id)) {
ids.push(...id);
} else {
ids.push(id);
}
return this.registerEvent(
ExposedFn.onLiveLocation,
(event: LiveLocation) => {
// Only group events
if (ids.length && !ids.includes(event.id)) {
return;
}
callback(event);
}
);
}
/**
* @event Listens to participants changed
* @param to callback
* @returns Stream of ParticipantEvent
*/
public onParticipantsChanged(callback: (evData: ParticipantEvent) => void): {
dispose: () => void;
};
/**
* @event Listens to participants changed
* @param to group id: xxxxx-yyyy@us.c
* @param to callback
* @returns Stream of ParticipantEvent
*/
public onParticipantsChanged(
groupId: string,
callback: (evData: ParticipantEvent) => void
): { dispose: () => void };
public onParticipantsChanged(
groupId: any,
callback?: (evData: ParticipantEvent) => void
): { dispose: () => void } {
if (typeof groupId === 'function') {
callback = groupId;
groupId = null;
}
return this.registerEvent(ExposedFn.onParticipantsChanged, (evData) => {
if (groupId && groupId !== evData.groupId) {
return;
}
callback({
by: evData.author,
byPushName: evData.authorPushName,
groupId: evData.groupId,
action: evData.action,
operation: evData.operation,
who: evData.participants,
});
});
}
/**
* @event Fires callback with Chat object every time the host phone is added to a group.
* @param to callback
* @returns Disposable object to stop the listening
*/
public onAddedToGroup(callback: (chat: Chat) => any) {
return this.registerEvent('onAddedToGroup', callback);
}
/**
* @event Escuta por ligações recebidas, seja de áudio ou vídeo.
*
* Para recusar a ligação, basta chamar o `rejectCall` {@link rejectCall}
*
* @returns Objeto descartável para parar de ouvir
*/
public onIncomingCall(callback: (call: any) => any) {
return this.registerEvent('onIncomingCall', callback);
}
/**
* Listens to presence changed, by default, it will triggered for active chats only or contacts subscribed (see {@link subscribePresence})
* @event Listens to presence changed
* @param callback Callback of on presence changed
* @returns Disposable object to stop the listening
*/
public onPresenceChanged(
callback: (presenceChangedEvent: PresenceEvent) => void
): { dispose: () => void };
/**
* Listens to presence changed, the callback will triggered only for passed IDs
* @event Listens to presence changed
* @param id contact id (xxxxx@c.us) or group id: xxxxx-yyyy@g.us
* @param callback Callback of on presence changed
* @returns Disposable object to stop the listening
*/
public onPresenceChanged(
id: string | string[],
callback: (presenceChangedEvent: PresenceEvent) => void
): { dispose: () => void };
public onPresenceChanged(
id: any,
callback?: (presenceChangedEvent: PresenceEvent) => void
): { dispose: () => void } {
const ids = [];
if (typeof id === 'function') {
callback = id;
} else if (Array.isArray(id)) {
ids.push(...id);
} else {
ids.push(id);
}
if (ids.length) {
this.subscribePresence(ids);
}
return this.registerEvent(
ExposedFn.onPresenceChanged,
(presence: PresenceEvent) => {
// Only group events
if (ids.length && !ids.includes(presence.id)) {
return;
}
callback(presence);
}
);
}
/**
* Subscribe presence of a contact or group to use in onPresenceChanged (see {@link onPresenceChanged})
*
* ```typescript
* // subcribe all contacts
* const contacts = await client.getAllContacts();
* await client.subscribePresence(contacts.map((c) => c.id._serialized));
*
* // subcribe all groups participants
* const chats = await client.getAllGroups(false);
* for (const c of chats) {
* const ids = c.groupMetadata.participants.map((p) => p.id._serialized);
* await client.subscribePresence(ids);
* }
* ```
*
* @param id contact id (xxxxx@c.us) or group id: xxxxx-yyyy@g.us
* @returns number of subscribed
*/
public async subscribePresence(id: string | string[]): Promise<number> {
return await evaluateAndReturn(
this.page,
(id) => WAPI.subscribePresence(id),
id
);
}
/**
* Unsubscribe presence of a contact or group to use in onPresenceChanged (see {@link onPresenceChanged})
* @param id contact id (xxxxx@c.us) or group id: xxxxx-yyyy@g.us
* @returns number of unsubscribed
*/
public async unsubscribePresence(id: string | string[]): Promise<number> {
return await evaluateAndReturn(
this.page,
(id) => WAPI.unsubscribePresence(id),
id
);
}
/**
* @event Listens to revoked messages
* @returns Disposable object to stop the listening
*/
public onRevokedMessage(
callback: (data: {
author?: string;
from: string;
to: string;
id: string;
refId: String;
}) => any
) {
return this.registerEvent('onRevokedMessage', callback);
}
/**
* @event Listens to reaction messages
* @returns Disposable object to stop the listening
*/
public onReactionMessage(
callback: (data: {
id: string;
msgId: string;
reactionText: string;
read: boolean;
orphan: number;
orphanReason: any;
timestamp: number;
}) => any
) {
return this.registerEvent('onReactionMessage', callback);
}
}