Spaces:
Runtime error
Runtime error
File size: 54,597 Bytes
4327358 |
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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 |
import { isJidGroup, isJidStatusBroadcast } from '@adiwajshing/baileys';
import { UnprocessableEntityException } from '@nestjs/common';
import {
getChannelInviteLink,
WhatsappSession,
} from '@waha/core/abc/session.abc';
import {
getFromToParticipant,
toCusFormat,
} from '@waha/core/engines/noweb/session.noweb.core';
import {
ReceiptEvent,
TagReceiptNodeToReceiptEvent,
} from '@waha/core/engines/webjs/ack.webjs';
import {
ToGroupV2JoinEvent,
ToGroupV2LeaveEvent,
ToGroupV2ParticipantsEvent,
ToGroupV2UpdateEvent,
} from '@waha/core/engines/webjs/groups.webjs';
import { LocalAuth } from '@waha/core/engines/webjs/LocalAuth';
import {
TagChatstateToPresence,
TagPresenceToPresence,
} from '@waha/core/engines/webjs/presence';
import { WebjsClientCore } from '@waha/core/engines/webjs/WebjsClientCore';
import {
CallErrorEvent,
PAGE_CALL_ERROR_EVENT,
} from '@waha/core/engines/webjs/WPage';
import {
AvailableInPlusVersion,
NotImplementedByEngineError,
} from '@waha/core/exceptions';
import { IMediaEngineProcessor } from '@waha/core/media/IMediaEngineProcessor';
import { QR } from '@waha/core/QR';
import { StatusToAck } from '@waha/core/utils/acks';
import {
parseMessageIdSerialized,
SerializeMessageKey,
} from '@waha/core/utils/ids';
import { DistinctAck } from '@waha/core/utils/reactive';
import { splitAt } from '@waha/helpers';
import { PairingCodeResponse } from '@waha/structures/auth.dto';
import {
Channel,
ChannelListResult,
ChannelMessage,
ChannelRole,
ChannelSearchByText,
ChannelSearchByView,
CreateChannelRequest,
ListChannelsQuery,
PreviewChannelMessages,
} from '@waha/structures/channels.dto';
import {
ChatSortField,
ChatSummary,
GetChatMessageQuery,
GetChatMessagesFilter,
GetChatMessagesQuery,
OverviewFilter,
ReadChatMessagesQuery,
ReadChatMessagesResponse,
} from '@waha/structures/chats.dto';
import {
ChatRequest,
CheckNumberStatusQuery,
EditMessageRequest,
MessageButtonReply,
MessageFileRequest,
MessageForwardRequest,
MessageImageRequest,
MessageLocationRequest,
MessageReactionRequest,
MessageReplyRequest,
MessageStarRequest,
MessageTextRequest,
MessageVoiceRequest,
SendSeenRequest,
WANumberExistResult,
} from '@waha/structures/chatting.dto';
import {
ContactQuery,
ContactRequest,
ContactUpdateBody,
} from '@waha/structures/contacts.dto';
import {
ACK_UNKNOWN,
SECOND,
WAHAEngine,
WAHAEvents,
WAHAPresenceStatus,
WAHASessionStatus,
WAMessageAck,
} from '@waha/structures/enums.dto';
import { BinaryFile, RemoteFile } from '@waha/structures/files.dto';
import {
CreateGroupRequest,
GroupSortField,
ParticipantsRequest,
SettingsSecurityChangeInfo,
} from '@waha/structures/groups.dto';
import { Label, LabelDTO, LabelID } from '@waha/structures/labels.dto';
import { LidToPhoneNumber } from '@waha/structures/lids.dto';
import { WAMedia } from '@waha/structures/media.dto';
import { ReplyToMessage } from '@waha/structures/message.dto';
import { PaginationParams, SortOrder } from '@waha/structures/pagination.dto';
import {
WAHAChatPresences,
WAHAPresenceData,
} from '@waha/structures/presence.dto';
import { WAMessage, WAMessageReaction } from '@waha/structures/responses.dto';
import { BrowserTraceQuery } from '@waha/structures/server.debug.dto';
import { MeInfo } from '@waha/structures/sessions.dto';
import { StatusRequest, TextStatus } from '@waha/structures/status.dto';
import {
EnginePayload,
WAMessageAckBody,
WAMessageEditedBody,
WAMessageRevokedBody,
} from '@waha/structures/webhooks.dto';
import { PaginatorInMemory } from '@waha/utils/Paginator';
import { sleep, waitUntil } from '@waha/utils/promiseTimeout';
import { SingleDelayedJobRunner } from '@waha/utils/SingleDelayedJobRunner';
import { TmpDir } from '@waha/utils/tmpdir';
import * as lodash from 'lodash';
import * as path from 'path';
import { ProtocolError } from 'puppeteer';
import { filter, fromEvent, merge, mergeMap, Observable, share } from 'rxjs';
import { map } from 'rxjs/operators';
import {
AuthStrategy,
Call,
Channel as WEBJSChannel,
Chat,
ClientOptions,
Contact,
Events,
GroupChat,
GroupNotification,
Label as WEBJSLabel,
Location,
Message,
MessageMedia,
Reaction,
WAState,
} from 'whatsapp-web.js';
import { Message as MessageInstance } from 'whatsapp-web.js/src/structures';
import { WAJSPresenceChatStateType, WebJSPresence } from './types';
export interface WebJSConfig {
webVersion?: string;
cacheType: 'local' | 'none';
}
export class WhatsappSessionWebJSCore extends WhatsappSession {
private START_ATTEMPT_DELAY_SECONDS = 2;
engine = WAHAEngine.WEBJS;
protected engineConfig?: WebJSConfig;
private startDelayedJob: SingleDelayedJobRunner;
private engineStateCheckDelayedJob: SingleDelayedJobRunner;
private shouldRestart: boolean;
private lastQRDate: Date = null;
whatsapp: WebjsClientCore;
protected qr: QR;
public constructor(config) {
super(config);
this.qr = new QR();
this.shouldRestart = true;
// Restart job if session failed
this.startDelayedJob = new SingleDelayedJobRunner(
'start-engine',
this.START_ATTEMPT_DELAY_SECONDS * SECOND,
this.logger,
);
this.engineStateCheckDelayedJob = new SingleDelayedJobRunner(
'engine-state-check',
2 * SECOND,
this.logger,
);
}
/**
* Folder with the current class
*/
protected getClassDirName() {
return __dirname;
}
protected getClientOptions(): ClientOptions {
const path = this.getClassDirName();
const webVersion =
this.engineConfig?.webVersion || '2.3000.1018072227-alpha';
const cacheType = this.engineConfig?.cacheType || 'none';
this.logger.info(`Using cache type: '${cacheType}'`);
if (cacheType === 'local') {
this.logger.info(`Using web version: '${webVersion}'`);
}
const args = this.getBrowserArgsForPuppeteer();
// add at the start
args.unshift(`--a-waha-timestamp=${new Date()}`);
args.unshift(`--a-waha-session=${this.name}`);
return {
puppeteer: {
protocolTimeout: 300_000,
headless: true,
executablePath: this.getBrowserExecutablePath(),
args: args,
dumpio: this.isDebugEnabled(),
},
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
webVersion: webVersion,
webVersionCache: {
type: cacheType,
path: path,
strict: true,
},
};
}
protected async buildClient() {
const clientOptions = this.getClientOptions();
const base = process.env.WAHA_LOCAL_STORE_BASE_DIR || './.sessions';
clientOptions.authStrategy = new LocalAuth({
clientId: this.name,
dataPath: `${base}/webjs/default`,
logger: this.logger,
rmMaxRetries: undefined,
});
this.addProxyConfig(clientOptions);
return new WebjsClientCore(clientOptions, this.getWebjsTagsFlag());
}
protected getWebjsTagsFlag() {
// Emit 'tag:*' events only when explicitly enabled in session config.
// This flag is required for presence.update and message.ack events.
// Disabled by default for performance and stability reasons.
return !!this.sessionConfig?.webjs?.tagsEventsOn;
}
private restartClient() {
if (!this.shouldRestart) {
this.logger.debug(
'Should not restart the client, ignoring restart request',
);
this.end().catch((error) => {
this.logger.error(error, 'Failed to end() the client');
});
return;
}
this.startDelayedJob.schedule(async () => {
if (!this.shouldRestart) {
this.logger.warn(
'Should not restart the client, ignoring restart request',
);
return;
}
await this.end();
await this.start();
});
}
protected addProxyConfig(clientOptions: ClientOptions) {
if (this.proxyConfig?.server !== undefined) {
// push the proxy server to the args
clientOptions.puppeteer.args.push(
`--proxy-server=${this.proxyConfig?.server}`,
);
// Authenticate
if (this.proxyConfig?.username && this.proxyConfig?.password) {
clientOptions.proxyAuthentication = {
username: this.proxyConfig?.username,
password: this.proxyConfig?.password,
};
}
}
}
protected async init() {
this.shouldRestart = true;
this.whatsapp = await this.buildClient();
this.whatsapp
.initialize()
.then(() => {
// Listen for browser disconnected event
this.whatsapp.pupBrowser.on('disconnected', () => {
if (this.shouldRestart) {
this.logger.error('The browser has been disconnected');
} else {
this.logger.info('The browser has been disconnected');
}
this.failed();
});
// Listen for page close event
this.whatsapp.pupPage.on('close', () => {
this.logger.error('The WhatsApp Web page has been closed');
this.failed();
});
// Listen for function call errors
this.whatsapp.events.on(
PAGE_CALL_ERROR_EVENT,
(event: CallErrorEvent) => {
if (event.error instanceof ProtocolError) {
this.logger.error(
`ProtocolError when calling page method: ${String(
event.method,
)}, restarting client...`,
);
this.logger.error(event.error);
this.failed();
}
},
);
// Listen for page error event
if (this.isDebugEnabled()) {
this.logger.debug("Logging 'console' event for web page");
this.whatsapp.pupPage.on('console', (msg) =>
this.logger.debug(`WEBJS page log: ${msg.text()}`),
);
this.whatsapp.pupPage.evaluate(() =>
console.log(`url is ${location.href}`),
);
}
})
.catch((error) => {
this.logger.error(error);
this.failed();
return;
});
if (this.isDebugEnabled()) {
this.listenEngineEventsInDebugMode();
}
this.listenConnectionEvents();
this.subscribeEngineEvents2();
}
async start() {
this.status = WAHASessionStatus.STARTING;
await this.init().catch((err) => {
this.logger.error('Failed to start the client');
this.logger.error(err, err.stack);
this.failed();
});
return this;
}
async stop() {
this.shouldRestart = false;
this.status = WAHASessionStatus.STOPPED;
this.stopEvents();
this.startDelayedJob.cancel();
this.mediaManager.close();
await this.end();
}
protected failed() {
// We'll restart the client if it's in the process of unpairing
this.status = WAHASessionStatus.FAILED;
this.restartClient();
}
async unpair() {
this.unpairing = true;
this.shouldRestart = false;
await this.whatsapp.unpair();
// Wait for unpairing to complete
await sleep(2_000);
}
private async end() {
this.engineStateCheckDelayedJob.cancel();
this.whatsapp?.removeAllListeners();
this.whatsapp?.pupBrowser?.removeAllListeners();
this.whatsapp?.pupPage?.removeAllListeners();
try {
// It's possible that browser yet starting
await waitUntil(
async () => {
const result = !!this.whatsapp.pupBrowser;
this.logger.debug(`Browser is ready to be closed: ${result}`);
return result;
},
1_000,
10_000,
);
this.logger.debug(
'Successfully waited for browser to be ready for closing',
);
} catch (error) {
this.logger.error(
error,
'Failed while waiting for browser to be ready for closing',
);
}
try {
await this.whatsapp?.destroy();
this.logger.debug('Successfully destroyed whatsapp client');
} catch (error) {
this.logger.error(error, 'Failed to destroy whatsapp client');
}
try {
// @ts-ignore
const strategy: AuthStrategy = this.whatsapp?.authStrategy;
await strategy?.destroy();
this.logger.debug('Successfully destroyed auth strategy');
} catch (error) {
this.logger.error(error, 'Failed to destroy auth strategy');
}
}
getSessionMeInfo(): MeInfo | null {
const clientInfo = this.whatsapp?.info;
if (!clientInfo) {
return null;
}
const wid = clientInfo.wid;
return {
id: wid?._serialized,
pushName: clientInfo?.pushname,
};
}
protected listenEngineEventsInDebugMode() {
// Iterate over Events enum and log with debug level all incoming events
// This is useful for debugging
for (const key in Events) {
const event = Events[key];
this.whatsapp.on(event, (...data: any[]) => {
const log = { event: event, data: data };
this.logger.debug({ event: log }, `WEBJS event`);
});
}
}
protected listenConnectionEvents() {
this.whatsapp.on(Events.QR_RECEIVED, async (qr) => {
this.logger.debug('QR received');
// Convert to image and save
this.qr.save(qr);
this.printQR(this.qr);
this.status = WAHASessionStatus.SCAN_QR_CODE;
this.lastQRDate = new Date();
});
this.whatsapp.on(Events.READY, () => {
this.status = WAHASessionStatus.WORKING;
this.qr.save('');
this.logger.info(`Session '${this.name}' is ready!`);
});
//
// Temp fix for hiding "Fresh look" modal
// https://github.com/devlikeapro/waha/issues/987
//
this.whatsapp.on(Events.READY, async () => {
try {
const hidden = await this.whatsapp.hideUXFreshLook();
if (hidden) {
this.logger.info('"Fresh look" modal has been hidden');
}
} catch (err) {
this.logger.warn('Failed to hide "Fresh look" modal');
this.logger.warn(err, err.stack);
}
});
this.whatsapp.on(Events.AUTHENTICATED, (args) => {
this.qr.save('');
this.logger.info({ args: args }, `Session has been authenticated!`);
});
this.whatsapp.on(Events.AUTHENTICATION_FAILURE, (args) => {
this.qr.save('');
this.shouldRestart = false;
this.logger.info({ args: args }, `Session has failed to authenticate!`);
this.failed();
});
this.whatsapp.on(Events.DISCONNECTED, (args) => {
if (args === 'LOGOUT') {
this.logger.warn({ args: args }, `Session has been logged out!`);
this.shouldRestart = false;
}
this.qr.save('');
this.logger.info({ args: args }, `Session has been disconnected!`);
this.failed();
});
this.whatsapp.on(Events.STATE_CHANGED, (state: WAState) => {
const badStates = [WAState.OPENING, WAState.TIMEOUT];
const log = this.logger.child({ state: state, event: 'change_state' });
log.info('Session engine state changed');
if (!badStates.includes(state)) {
return;
}
log.info(`Session state changed to bad state, waiting for recovery...`);
this.engineStateCheckDelayedJob.schedule(async () => {
if (this.startDelayedJob.scheduled) {
log.info('Session is restarting already, skip check.');
return;
}
if (!this.whatsapp) {
log.warn('Session is not initialized, skip recovery.');
return;
}
const currentState = await this.whatsapp.getState().catch((error) => {
log.error('Failed to get current state');
log.error(error, error.stack);
return null;
});
log.setBindings({ currentState: currentState });
if (!currentState) {
log.warn('Session has no current state, restarting...');
this.restartClient();
return;
} else if (badStates.includes(currentState)) {
log.info('Session is still in bad state, restarting...');
this.restartClient();
return;
}
log.info('Session has recovered, no need to restart.');
});
});
}
/**
* START - Methods for API
*/
public async browserTrace(query: BrowserTraceQuery): Promise<string> {
const tmpdir = new TmpDir(
this.logger,
`waha-browser-trace-${this.name}-`,
(10 * query.seconds + 120) * 1000,
);
const page = this.whatsapp.pupPage;
return await tmpdir.use(async (dir) => {
this.logger.info({ query }, `Starting browser tracing...`);
const filepath = path.join(dir, 'trace.json');
await page.tracing.start({ path: filepath });
await sleep(query.seconds * 1000);
await page.tracing.stop();
this.logger.info(`Browser tracing finished, saved to ${filepath}`);
return filepath;
});
}
/**
* Auth methods
*/
public getQR(): QR {
return this.qr;
}
public async requestCode(
phoneNumber: string,
method: string,
params?: any,
): Promise<PairingCodeResponse> {
const code = await this.whatsapp.requestPairingCode(phoneNumber, true);
// show it as ABCD-ABCD
const parts = splitAt(code, 4);
const codeRepr = parts.join('-');
this.logger.debug(`Your code: ${codeRepr}`);
return { code: codeRepr };
}
async getScreenshot(): Promise<Buffer> {
const screenshot = await this.whatsapp.pupPage.screenshot({
encoding: 'binary',
});
return screenshot as Buffer;
}
async checkNumberStatus(
request: CheckNumberStatusQuery,
): Promise<WANumberExistResult> {
const phone = request.phone.split('@')[0];
const result = await this.whatsapp.getNumberId(phone);
if (!result) {
return {
numberExists: false,
};
}
return {
numberExists: true,
chatId: result._serialized,
};
}
/**
* Profile methods
*/
public async setProfileName(name: string): Promise<boolean> {
await this.whatsapp.setPushName(name);
return true;
}
public async setProfileStatus(status: string): Promise<boolean> {
await this.whatsapp.setStatus(status);
return true;
}
protected setProfilePicture(file: BinaryFile | RemoteFile): Promise<boolean> {
throw new AvailableInPlusVersion();
}
protected deleteProfilePicture(): Promise<boolean> {
throw new AvailableInPlusVersion();
}
/**
* Other methods
*/
sendText(request: MessageTextRequest) {
const options = this.getMessageOptions(request);
return this.whatsapp.sendMessage(
this.ensureSuffix(request.chatId),
request.text,
options,
);
}
public deleteMessage(chatId: string, messageId: string) {
const message = this.recreateMessage(messageId);
return message.delete(true);
}
public editMessage(
chatId: string,
messageId: string,
request: EditMessageRequest,
) {
const message = this.recreateMessage(messageId);
const options = {
// It's fine to sent just ids instead of Contact object
mentions: request.mentions as unknown as string[],
linkPreview: request.linkPreview,
};
return message.edit(request.text, options);
}
reply(request: MessageReplyRequest) {
const options = this.getMessageOptions(request);
return this.whatsapp.sendMessage(
this.ensureSuffix(request.chatId),
request.text,
options,
);
}
sendImage(request: MessageImageRequest) {
throw new AvailableInPlusVersion();
}
sendFile(request: MessageFileRequest) {
throw new AvailableInPlusVersion();
}
sendVoice(request: MessageVoiceRequest) {
throw new AvailableInPlusVersion();
}
sendButtonsReply(request: MessageButtonReply) {
throw new AvailableInPlusVersion();
}
async sendLocation(request: MessageLocationRequest) {
const location = new Location(request.latitude, request.longitude, {
name: request.title,
});
const options = this.getMessageOptions(request);
return this.whatsapp.sendMessage(
this.ensureSuffix(request.chatId),
location,
options,
);
}
async forwardMessage(request: MessageForwardRequest): Promise<WAMessage> {
const forwardMessage = this.recreateMessage(request.messageId);
const msg = await forwardMessage.forward(this.ensureSuffix(request.chatId));
// Return "sent: true" for now
// need to research how to get the data from WebJS
// @ts-ignore
return { sent: msg || false };
}
async sendSeen(request: SendSeenRequest) {
const chat: Chat = await this.whatsapp.getChatById(
this.ensureSuffix(request.chatId),
);
await chat.sendSeen();
}
async startTyping(request: ChatRequest) {
const chat: Chat = await this.whatsapp.getChatById(
this.ensureSuffix(request.chatId),
);
await chat.sendStateTyping();
}
async stopTyping(request: ChatRequest) {
const chat: Chat = await this.whatsapp.getChatById(
this.ensureSuffix(request.chatId),
);
await chat.clearState();
}
async setReaction(request: MessageReactionRequest) {
const message = this.recreateMessage(request.messageId);
return message.react(request.reaction);
}
/**
* Recreate message instance from id
*/
private recreateMessage(msgId: string): MessageInstance {
const messageId = this.deserializeId(msgId);
const data = {
id: messageId,
};
return new MessageInstance(this.whatsapp, data);
}
async setStar(request: MessageStarRequest) {
const message = this.recreateMessage(request.messageId);
if (request.star) {
await message.star();
} else {
await message.unstar();
}
}
/**
* Chats methods
*/
getChats(pagination: PaginationParams, filter: OverviewFilter | null = null) {
switch (pagination.sortBy) {
case ChatSortField.ID:
pagination.sortBy = 'id._serialized';
break;
case ChatSortField.CONVERSATION_TIMESTAMP:
pagination.sortBy = 't';
break;
}
return this.whatsapp.getChats(pagination, filter);
}
public async getChatsOverview(
pagination: PaginationParams,
filter?: OverviewFilter,
): Promise<ChatSummary[]> {
pagination = {
...pagination,
sortBy: ChatSortField.CONVERSATION_TIMESTAMP,
sortOrder: SortOrder.DESC,
};
const chats = await this.getChats(pagination, filter);
const promises = [];
for (const chat of chats) {
promises.push(this.fetchChatSummary(chat));
}
const result = await Promise.all(promises);
return result;
}
protected async fetchChatSummary(chat: Chat): Promise<ChatSummary> {
const picture = await this.getContactProfilePicture(
chat.id._serialized,
false,
);
const lastMessage = chat.lastMessage
? this.toWAMessage(chat.lastMessage)
: null;
return {
id: chat.id._serialized,
name: chat.name || null,
picture: picture,
lastMessage: lastMessage,
_chat: chat,
};
}
public async getChatMessages(
chatId: string,
query: GetChatMessagesQuery,
filter: GetChatMessagesFilter,
) {
if (chatId == 'all') {
throw new NotImplementedByEngineError(
"Can not get messages from 'all' in WEBJS",
);
}
const downloadMedia = query.downloadMedia;
// Test there's chat with id
await this.whatsapp.getChatById(this.ensureSuffix(chatId));
const pagination: PaginationParams = query;
const messages = await this.whatsapp.getMessages(
this.ensureSuffix(chatId),
filter,
pagination,
);
const promises = [];
for (const msg of messages) {
promises.push(this.processIncomingMessage(msg, downloadMedia));
}
let result = await Promise.all(promises);
result = result.filter(Boolean);
return result;
}
public async readChatMessages(
chatId: string,
request: ReadChatMessagesQuery,
): Promise<ReadChatMessagesResponse> {
const chat: Chat = await this.whatsapp.getChatById(
this.ensureSuffix(chatId),
);
await chat.sendSeen();
return { ids: null };
}
public async getChatMessage(
chatId: string,
messageId: string,
query: GetChatMessageQuery,
): Promise<null | WAMessage> {
const message = await this.whatsapp.getMessageById(messageId);
if (!message) return null;
if (
isJidGroup(message.id.remote) ||
isJidStatusBroadcast(message.id.remote)
) {
// @ts-ignore
message.rawData.receipts = await message.getInfo().catch((error) => {
this.logger.error(
{ error: error, msg: message.id._serialized },
'Failed to get receipts',
);
return null;
});
}
return await this.processIncomingMessage(message, query.downloadMedia);
}
public async pinMessage(
chatId: string,
messageId: string,
duration: number,
): Promise<boolean> {
const message = await this.whatsapp.getMessageById(messageId);
return message.pin(duration);
}
public async unpinMessage(
chatId: string,
messageId: string,
): Promise<boolean> {
const message = await this.whatsapp.getMessageById(messageId);
return message.unpin();
}
async deleteChat(chatId) {
const chat = await this.whatsapp.getChatById(this.ensureSuffix(chatId));
return chat.delete();
}
async clearMessages(chatId) {
const chat = await this.whatsapp.getChatById(chatId);
return chat.clearMessages();
}
public chatsArchiveChat(chatId: string): Promise<any> {
const id = this.ensureSuffix(chatId);
return this.whatsapp.archiveChat(id);
}
public chatsUnarchiveChat(chatId: string): Promise<any> {
const id = this.ensureSuffix(chatId);
return this.whatsapp.unarchiveChat(id);
}
public chatsUnreadChat(chatId: string): Promise<any> {
const id = this.ensureSuffix(chatId);
return this.whatsapp.markChatUnread(id);
}
/**
*
* Label methods
*/
public async getLabels(): Promise<Label[]> {
const labels = await this.whatsapp.getLabels();
return labels.map(this.toLabel);
}
public async createLabel(label: LabelDTO): Promise<Label> {
const labelId = await this.whatsapp.createLabel(label.name, label.color);
return {
id: labelId.toString(),
name: label.name,
color: label.color,
colorHex: Label.toHex(label.color),
};
}
public async updateLabel(label: Label): Promise<Label> {
return await this.whatsapp.updateLabel(label);
}
public deleteLabel(label: Label): Promise<void> {
return this.whatsapp.deleteLabel(label);
}
public getChatsByLabelId(labelId: string) {
return this.whatsapp.getChatsByLabelId(labelId);
}
public async getChatLabels(chatId: string): Promise<Label[]> {
const id = this.ensureSuffix(chatId);
const labels = await this.whatsapp.getChatLabels(id);
return labels.map(this.toLabel);
}
public async putLabelsToChat(chatId: string, labels: LabelID[]) {
const labelIds = labels.map((label) => label.id);
const chatIds = [this.ensureSuffix(chatId)];
await this.whatsapp.addOrRemoveLabels(labelIds, chatIds);
}
protected toLabel(label: WEBJSLabel): Label {
const color = label.colorIndex;
return {
id: label.id,
name: label.name,
color: color,
colorHex: Label.toHex(color),
};
}
/**
* Contacts methods
*/
public async upsertContact(chatId: string, body: ContactUpdateBody) {
const phoneNumber = chatId.split('@')[0];
await this.whatsapp.saveOrEditAddressbookContact(
phoneNumber,
body.firstName,
body.lastName,
true,
);
}
getContact(query: ContactQuery) {
return this.whatsapp
.getContactById(this.ensureSuffix(query.contactId))
.then(this.toWAContact);
}
async getContacts(pagination: PaginationParams) {
const contactsWEBJS = await this.whatsapp.getContacts();
const contacts = contactsWEBJS.map(this.toWAContact);
const paginator = new PaginatorInMemory(pagination);
return paginator.apply(contacts);
}
public async getContactAbout(query: ContactQuery) {
const contact = await this.whatsapp.getContactById(
this.ensureSuffix(query.contactId),
);
return { about: await contact.getAbout() };
}
public async fetchContactProfilePicture(id: string) {
const contact = await this.whatsapp.getContactById(this.ensureSuffix(id));
const url = await contact.getProfilePicUrl();
return url;
}
public async blockContact(request: ContactRequest) {
const contact = await this.whatsapp.getContactById(
this.ensureSuffix(request.contactId),
);
await contact.block();
}
public async unblockContact(request: ContactRequest) {
const contact = await this.whatsapp.getContactById(
this.ensureSuffix(request.contactId),
);
await contact.unblock();
}
/**
* Lid to Phone Number methods
*/
public async getAllLids(
pagination: PaginationParams,
): Promise<Array<LidToPhoneNumber>> {
return this.whatsapp.getAllLids(pagination);
}
public async getLidsCount(): Promise<number> {
return this.whatsapp.getLidsCount();
}
public async findPNByLid(lid: string): Promise<LidToPhoneNumber> {
const phoneNumber = await this.whatsapp.findPNByLid(lid);
return {
lid: lid,
pn: phoneNumber,
};
}
public async findLIDByPhoneNumber(
phoneNumber: string,
): Promise<LidToPhoneNumber> {
const pn = toCusFormat(phoneNumber);
const lid = await this.whatsapp.findLIDByPhoneNumber(pn);
return {
lid: lid,
pn: pn,
};
}
/**
* Group methods
*/
public createGroup(request: CreateGroupRequest) {
const participantIds = request.participants.map(
(participant) => participant.id,
);
return this.whatsapp.createGroup(request.name, participantIds);
}
public joinGroup(code: string) {
return this.whatsapp.acceptInvite(code);
}
public joinInfoGroup(code: string) {
return this.whatsapp.getInviteInfo(code);
}
public async getInfoAdminsOnly(id): Promise<SettingsSecurityChangeInfo> {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return {
// Undocumented property, can be changed in the future
// @ts-ignore
adminsOnly: groupChat.groupMetadata.restrict,
};
}
public async setInfoAdminsOnly(id, value) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.setInfoAdminsOnly(value);
}
public async getMessagesAdminsOnly(id): Promise<SettingsSecurityChangeInfo> {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
// @ts-ignore
return {
// Undocumented property, can be changed in the future
// @ts-ignore
adminsOnly: groupChat.groupMetadata.announce,
};
}
public async setMessagesAdminsOnly(id, value) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.setMessagesAdminsOnly(value);
}
public async getGroups(pagination: PaginationParams) {
const chats = await this.whatsapp.getChats();
const groups = lodash.filter(chats, (chat) => chat.isGroup);
switch (pagination.sortBy) {
case GroupSortField.ID:
pagination.sortBy = 'id._serialized';
break;
case GroupSortField.SUBJECT:
pagination.sortBy = 'groupMetadata.subject';
break;
}
const paginator = new PaginatorInMemory(pagination);
return paginator.apply(groups);
}
protected removeGroupsFieldParticipant(group: any) {
delete group.groupMetadata?.participants;
delete group.groupMetadata?.pendingParticipants;
delete group.groupMetadata?.pastParticipants;
delete group.groupMetadata?.membershipApprovalRequests;
}
public async refreshGroups(): Promise<boolean> {
return true;
}
public getGroup(id) {
return this.whatsapp.getChatById(id);
}
public async deleteGroup(id) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.delete();
}
public async leaveGroup(id) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.leave();
}
public async setDescription(id, description) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.setDescription(description);
}
public async setSubject(id, subject) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.setSubject(subject);
}
public async getInviteCode(id): Promise<string> {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.getInviteCode();
}
public async revokeInviteCode(id): Promise<string> {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
await groupChat.revokeInvite();
return groupChat.getInviteCode();
}
public async getParticipants(id) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
return groupChat.participants;
}
public async addParticipants(id, request: ParticipantsRequest) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
const participantIds = request.participants.map(
(participant) => participant.id,
);
return groupChat.addParticipants(participantIds);
}
public async removeParticipants(id, request: ParticipantsRequest) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
const participantIds = request.participants.map(
(participant) => participant.id,
);
return groupChat.removeParticipants(participantIds);
}
public async promoteParticipantsToAdmin(id, request: ParticipantsRequest) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
const participantIds = request.participants.map(
(participant) => participant.id,
);
return groupChat.promoteParticipants(participantIds);
}
public async demoteParticipantsToUser(id, request: ParticipantsRequest) {
const groupChat = (await this.whatsapp.getChatById(id)) as GroupChat;
const participantIds = request.participants.map(
(participant) => participant.id,
);
return groupChat.demoteParticipants(participantIds);
}
/**
* Channels methods
*/
public searchChannelsByView(
query: ChannelSearchByView,
): Promise<ChannelListResult> {
throw new AvailableInPlusVersion();
}
public searchChannelsByText(
query: ChannelSearchByText,
): Promise<ChannelListResult> {
throw new AvailableInPlusVersion();
}
public async previewChannelMessages(
inviteCode: string,
query: PreviewChannelMessages,
): Promise<ChannelMessage[]> {
throw new AvailableInPlusVersion();
}
protected ChatToChannel(chat: WEBJSChannel): Channel {
// @ts-ignore
const metadata = chat.channelMetadata;
let role = metadata.membershipType.toUpperCase();
if (role === 'VIEWER') {
role = ChannelRole.GUEST;
}
return {
id: chat.id._serialized,
name: chat.name,
description: chat.description,
invite: getChannelInviteLink(metadata.inviteCode),
preview: null,
picture: null,
verified: metadata.verified,
role: role,
subscribersCount: null,
};
}
protected ChannelMetadataToChannel(metadata: any): Channel {
let role = metadata.membershipType.toUpperCase();
if (role === 'VIEWER') {
role = ChannelRole.GUEST;
}
return {
id: metadata.id,
name: metadata.titleMetadata.title,
description: metadata.descriptionMetadata.description,
invite: metadata.inviteLink,
preview: metadata.pictureUrl,
picture: metadata.pictureUrl,
verified: metadata.isVerified,
role: role,
subscribersCount: metadata.subscribersCount,
};
}
public async channelsList(query: ListChannelsQuery): Promise<Channel[]> {
const data = await this.whatsapp.getChannels();
let channels = data.map(this.ChatToChannel);
if (query.role) {
// @ts-ignore
channels = channels.filter((channel) => channel.role === query.role);
}
// Exclude GUEST, browser saves the data
// when we search channels or getting messages
channels = channels.filter((channel) => channel.role !== 'GUEST');
const promises = channels.map(async (channel) =>
this.whatsapp.getProfilePicUrl(channel.id),
);
const pictures = await Promise.all(promises);
channels = channels.map((channel, index) => {
channel.picture = pictures[index] || null;
channel.preview = channel.picture;
return channel;
});
return channels;
}
public channelsCreateChannel(
request: CreateChannelRequest,
): Promise<Channel> {
throw new NotImplementedByEngineError();
}
public async channelsGetChannel(id: string): Promise<Channel> {
return await this.channelsGetChannelByInviteCode(id);
}
public async channelsGetChannelByInviteCode(
inviteCode: string,
): Promise<Channel> {
const metadata = await this.whatsapp.getChannelByInviteCode(inviteCode);
const channel = this.ChannelMetadataToChannel(metadata);
channel.preview =
(await this.whatsapp.getProfilePicUrl(channel.id)) || null;
channel.picture = channel.preview;
return channel;
}
public channelsDeleteChannel(id: string): Promise<void> {
throw new NotImplementedByEngineError();
}
public channelsFollowChannel(id: string): Promise<void> {
throw new NotImplementedByEngineError();
}
public channelsUnfollowChannel(id: string): Promise<void> {
throw new NotImplementedByEngineError();
}
public channelsMuteChannel(id: string): Promise<void> {
throw new NotImplementedByEngineError();
}
public channelsUnmuteChannel(id: string): Promise<void> {
throw new NotImplementedByEngineError();
}
/**
* Presences methods
*/
public async setPresence(presence: WAHAPresenceStatus, chatId?: string) {
let chat: Chat;
switch (presence) {
case WAHAPresenceStatus.ONLINE:
await this.whatsapp.sendPresenceAvailable();
break;
case WAHAPresenceStatus.OFFLINE:
await this.whatsapp.sendPresenceUnavailable();
break;
case WAHAPresenceStatus.TYPING:
chat = await this.whatsapp.getChatById(chatId);
await chat.sendStateTyping();
break;
case WAHAPresenceStatus.RECORDING:
chat = await this.whatsapp.getChatById(chatId);
await chat.sendStateRecording();
break;
case WAHAPresenceStatus.PAUSED:
chat = await this.whatsapp.getChatById(chatId);
await chat.clearState();
break;
default:
throw new NotImplementedByEngineError(
`WEBJS engine doesn't support '${presence}' presence.`,
);
}
}
public getPresences(): Promise<WAHAChatPresences[]> {
throw new NotImplementedByEngineError();
}
public async getPresence(id: string): Promise<WAHAChatPresences> {
const chatId = toCusFormat(id);
const presences = await this.whatsapp.getPresence(chatId);
return this.toWahaPresences(chatId, presences);
}
public async subscribePresence(id: string): Promise<any> {
const chatId = toCusFormat(id);
await this.whatsapp.subscribePresence(chatId);
}
private toWahaPresences(
chatId: string,
data: WebJSPresence[],
): WAHAChatPresences {
const presences: WAHAPresenceData[] = data.map((presence) => {
let status: WAHAPresenceStatus = WAHAPresenceStatus.OFFLINE;
switch (presence.state) {
case WAJSPresenceChatStateType.AVAILABLE:
status = WAHAPresenceStatus.ONLINE;
break;
case WAJSPresenceChatStateType.UNAVAILABLE:
status = WAHAPresenceStatus.OFFLINE;
break;
case WAJSPresenceChatStateType.TYPING:
status = WAHAPresenceStatus.TYPING;
break;
case WAJSPresenceChatStateType.RECORDING_AUDIO:
status = WAHAPresenceStatus.RECORDING;
}
return {
participant: presence.participant,
lastSeen: presence.lastSeen || null,
lastKnownPresence: status,
};
});
return {
id: toCusFormat(chatId),
presences: presences,
};
}
/**
* Status methods
*/
protected checkStatusRequest(request: StatusRequest) {
if (request.contacts && request.contacts?.length > 0) {
const msg =
"WEBJS doesn't accept 'contacts'. Remove the field to send status to all contacts.";
throw new UnprocessableEntityException(msg);
}
}
public sendTextStatus(status: TextStatus) {
this.checkStatusRequest(status);
return this.whatsapp.sendTextStatus(status);
}
/**
* END - Methods for API
*/
subscribeEngineEvents2() {
// Save sent message in cache
this.whatsapp.events.on('message.id', (data) => {
this.saveSentMessageId(data.id);
});
//
// All
//
const events: Observable<EnginePayload>[] = [];
for (const key in Events) {
const event = Events[key];
const event$ = fromEvent(this.whatsapp, event);
events.push(
event$.pipe(
map((data) => {
return {
event: event,
data: data,
};
}),
),
);
}
const all$ = merge(...events);
this.events2.get(WAHAEvents.ENGINE_EVENT).switch(all$);
//
// Messages
//
const messageReceived$ = fromEvent(this.whatsapp, Events.MESSAGE_RECEIVED);
const messagesFromOthers$ = messageReceived$.pipe(
filter((msg: Message) => this.jids.include(msg?.id?.remote)),
mergeMap((msg: any) => this.processIncomingMessage(msg, true)),
share(),
);
this.events2.get(WAHAEvents.MESSAGE).switch(messagesFromOthers$);
const messageCreate$ = fromEvent(this.whatsapp, Events.MESSAGE_CREATE);
const messagesFromAll$ = messageCreate$.pipe(
filter((msg: Message) => this.jids.include(msg?.id?.remote)),
mergeMap((msg: any) => this.processIncomingMessage(msg, true)),
share(),
);
this.events2.get(WAHAEvents.MESSAGE_ANY).switch(messagesFromAll$);
const messageCiphertext$ = fromEvent(
this.whatsapp,
Events.MESSAGE_CIPHERTEXT,
);
const messagesWaiting$ = messageCiphertext$.pipe(
filter((msg: Message) => this.jids.include(msg?.id?.remote)),
mergeMap((msg: any) => this.processIncomingMessage(msg, false)),
share(),
);
this.events2.get(WAHAEvents.MESSAGE_WAITING).switch(messagesWaiting$);
const messageRevoked$ = fromEvent(
this.whatsapp,
Events.MESSAGE_REVOKED_EVERYONE,
(after, before) => {
return { after, before };
},
);
const messagesRevoked$ = messageRevoked$.pipe(
filter((evt: any) =>
this.jids.include(evt?.after?.id?.remote || evt?.before?.id?.remote),
),
map((event): WAMessageRevokedBody => {
const afterMessage = event.after ? this.toWAMessage(event.after) : null;
const beforeMessage = event.before
? this.toWAMessage(event.before)
: null;
// Extract the revoked message ID from the protocolMessageKey.id field
const revokedMessageId = afterMessage?._data?.protocolMessageKey?.id;
return {
after: afterMessage,
before: beforeMessage,
revokedMessageId: revokedMessageId,
};
}),
);
this.events2.get(WAHAEvents.MESSAGE_REVOKED).switch(messagesRevoked$);
const messageReaction$ = fromEvent(this.whatsapp, 'message_reaction');
const messagesReaction$ = messageReaction$.pipe(
filter((reaction: Reaction) => this.jids.include(reaction?.id?.remote)),
map(this.processMessageReaction.bind(this)),
filter(Boolean),
);
this.events2.get(WAHAEvents.MESSAGE_REACTION).switch(messagesReaction$);
const messageEdit$ = fromEvent(
this.whatsapp,
Events.MESSAGE_EDIT,
(message, newBody, prevBody) => {
return { message, newBody, prevBody };
},
);
const messagesEdit$ = messageEdit$.pipe(
filter((event: any) => this.jids.include(event?.message?.id?.remote)),
map((event): WAMessageEditedBody => {
const message = this.toWAMessage(event.message);
return {
...message,
body: event.newBody,
editedMessageId: message._data?.id?.id,
_data: event,
};
}),
);
this.events2.get(WAHAEvents.MESSAGE_EDITED).switch(messagesEdit$);
const messageAckWEBJS$ = fromEvent(
this.whatsapp,
Events.MESSAGE_ACK,
(message, ack) => {
return { message, ack };
},
);
const messagesAckDM$ = messageAckWEBJS$.pipe(
map((event) => event.message),
map<any, WAMessage>(this.toWAMessage.bind(this)),
filter((ack) => !isJidGroup(ack.to) && !isJidStatusBroadcast(ack.to)),
filter((ack) => this.jids.include(ack.to)),
);
const tagReceiptNode$ = fromEvent(this.whatsapp, Events.TAG_RECEIPT);
const messageAckGroups$ = tagReceiptNode$.pipe(
mergeMap((node) =>
TagReceiptNodeToReceiptEvent(node as any, this.getSessionMeInfo()),
),
filter(Boolean),
mergeMap(this.TagReceiptToMessageAck.bind(this)),
filter((ack) => isJidGroup(ack.to) || isJidStatusBroadcast(ack.to)),
filter((ack) => this.jids.include(ack.to)),
);
const messageAckAll$ = merge(messagesAckDM$, messageAckGroups$);
const messageAck$ = messageAckAll$.pipe(DistinctAck());
this.events2.get(WAHAEvents.MESSAGE_ACK).switch(messageAck$);
//
// Others
//
const stateChanged$ = fromEvent(this.whatsapp, Events.STATE_CHANGED);
this.events2.get(WAHAEvents.STATE_CHANGE).switch(stateChanged$);
//
// Presence
//
const tagPresenceNode$ = fromEvent(this.whatsapp, Events.TAG_PRESENCE);
const presences$ = tagPresenceNode$.pipe(
map(TagPresenceToPresence),
filter(Boolean),
filter((presence: any) => this.jids.include(presence.id)),
);
const tagChatstateNode$ = fromEvent(this.whatsapp, 'tag:chatstate');
const chatstatePresences$ = tagChatstateNode$.pipe(
map(TagChatstateToPresence),
filter(Boolean),
filter((presence: any) => this.jids.include(presence.id)),
);
const presenceUpdate$ = merge(presences$, chatstatePresences$);
this.events2.get(WAHAEvents.PRESENCE_UPDATE).switch(presenceUpdate$);
//
// Groups
//
const groupJoin$ = fromEvent<GroupNotification>(
this.whatsapp,
Events.GROUP_JOIN,
);
this.events2.get(WAHAEvents.GROUP_JOIN).switch(groupJoin$); // v1
const groupV2Join$ = groupJoin$.pipe(
mergeMap((evt) =>
ToGroupV2JoinEvent(this.whatsapp, this.getSessionMeInfo().id, evt),
),
filter(Boolean),
);
this.events2.get(WAHAEvents.GROUP_V2_JOIN).switch(groupV2Join$);
const groupLeave$ = fromEvent<GroupNotification>(
this.whatsapp,
Events.GROUP_LEAVE,
);
this.events2.get(WAHAEvents.GROUP_LEAVE).switch(groupLeave$); // v1
const groupV2Leave$ = groupLeave$.pipe(
map((evt) => ToGroupV2LeaveEvent(this.getSessionMeInfo().id, evt)),
filter(Boolean),
);
this.events2.get(WAHAEvents.GROUP_V2_LEAVE).switch(groupV2Leave$);
const groupAdminChanged$ = fromEvent(
this.whatsapp,
Events.GROUP_ADMIN_CHANGED,
);
const groupV2Participants = merge(
groupJoin$,
groupLeave$,
groupAdminChanged$,
).pipe(map(ToGroupV2ParticipantsEvent), filter(Boolean));
this.events2
.get(WAHAEvents.GROUP_V2_PARTICIPANTS)
.switch(groupV2Participants);
const groupUpdate$ = fromEvent<GroupNotification>(
this.whatsapp,
Events.GROUP_UPDATE,
);
const groupV2Update$ = groupUpdate$.pipe(
mergeMap((evt) => ToGroupV2UpdateEvent(this.whatsapp, evt)),
filter(Boolean),
);
this.events2.get(WAHAEvents.GROUP_V2_UPDATE).switch(groupV2Update$);
//
// Chats
//
const chatArchived$ = fromEvent(
this.whatsapp,
'chat_archived',
(chat, archived, _) => {
return {
chat: chat,
archived: archived,
};
},
);
const chatsArchived$ = chatArchived$.pipe(
filter((event: any) => this.jids.include(event?.chat?.id?._serialized)),
map((event) => {
return {
id: event.chat.id._serialized,
archived: event.archived,
timestamp: event.chat.timestamp,
};
}),
);
this.events2.get(WAHAEvents.CHAT_ARCHIVE).switch(chatsArchived$);
//
// Calls
//
const call$ = fromEvent(this.whatsapp, 'call');
const calls$ = call$.pipe(
filter((call: Call) => this.jids.include((call as any)?.from)),
map((call: Call) => {
return {
id: call.id,
from: call.from,
timestamp: call.timestamp,
isVideo: call.isVideo,
isGroup: call.isGroup,
};
}),
);
this.events2.get(WAHAEvents.CALL_RECEIVED).switch(calls$);
}
protected async processIncomingMessage(
message: Message,
downloadMedia = true,
) {
// Convert
const wamessage = this.toWAMessage(message);
// Media
if (downloadMedia) {
const media = await this.downloadMediaSafe(message);
wamessage.media = media;
}
return wamessage;
}
private processMessageReaction(reaction: Reaction): WAMessageReaction {
if (this.lastQRDate) {
// If it's timestamp before last qr - ignore it
// Fixes: https://github.com/devlikeapro/waha/issues/494
if (reaction.timestamp < this.lastQRDate.getTime() / 1000) {
return null;
}
}
const source = this.getMessageSource(reaction.id.id);
return {
id: reaction.id._serialized,
from: reaction.senderId,
fromMe: reaction.id.fromMe,
source: source,
participant: reaction.senderId,
to: reaction.id.remote,
timestamp: reaction.timestamp,
reaction: {
text: reaction.reaction,
messageId: reaction.msgId._serialized,
},
};
}
protected TagReceiptToMessageAck(receipt: ReceiptEvent): WAMessageAckBody[] {
const ids = receipt.messageIds;
const acks = [];
for (const id_ of ids) {
const messageKey = {
fromMe: receipt.key.fromMe,
remoteJid: toCusFormat(receipt.key.remoteJid),
participant: toCusFormat(receipt.key.participant),
id: id_,
};
const fromToParticipant = getFromToParticipant(messageKey);
const id = SerializeMessageKey(messageKey);
const ack = StatusToAck(receipt.status);
acks.push({
id: id,
from: fromToParticipant.from,
to: fromToParticipant.to,
participant: toCusFormat(receipt.participant),
fromMe: !receipt.key.fromMe, // reverted, it's right
ack: ack,
ackName: WAMessageAck[ack] || ACK_UNKNOWN,
_data: receipt._node,
});
}
return acks;
}
protected toWAMessage(message: Message): WAMessage {
const replyTo = this.extractReplyTo(message);
const source = this.getMessageSource(message.id.id);
const key = parseMessageIdSerialized(message.id._serialized);
// @ts-ignore
return {
id: message.id._serialized,
timestamp: message.timestamp,
from: message.from,
fromMe: message.fromMe,
participant: toCusFormat(key.participant),
source: source,
to: message.to,
body: message.body,
// Media
// @ts-ignore
hasMedia: Boolean(message.hasMedia),
media: null,
// @ts-ignore
mediaUrl: message.media?.url,
// @ts-ignore
ack: message.ack,
ackName: WAMessageAck[message.ack] || ACK_UNKNOWN,
location: message.location,
vCards: message.vCards,
replyTo: replyTo,
_data: message.rawData,
};
}
protected extractReplyTo(message: Message): ReplyToMessage | null {
// @ts-ignore
const quotedMsg = message.rawData?.quotedMsg;
if (!quotedMsg) {
return;
}
return {
id: quotedMsg.id?.id,
participant: quotedMsg.author || quotedMsg.from,
body: quotedMsg.caption || quotedMsg.body,
_data: quotedMsg,
};
}
public async getEngineInfo() {
if (!this.whatsapp || !this.whatsapp.pupPage) {
return null;
}
return {
WWebVersion: await this.whatsapp.getWWebVersion(),
state: await this.whatsapp.getState(),
};
}
protected toWAContact(contact: Contact) {
// @ts-ignore
contact.id = contact.id._serialized;
return contact;
}
protected async downloadMediaSafe(message): Promise<WAMedia | null> {
try {
return await this.downloadMedia(message);
} catch (e) {
this.logger.error('Failed when tried to download media for a message');
this.logger.error(e, e.stack);
}
return null;
}
protected async downloadMedia(message: Message) {
const processor = new WEBJSEngineMediaProcessor();
const media = await this.mediaManager.processMedia(
processor,
message,
this.name,
);
return media;
}
protected getMessageOptions(request: any): any {
let mentions = request.mentions;
mentions = mentions ? mentions.map(this.ensureSuffix) : undefined;
const quotedMessageId = request.reply_to || request.replyTo;
return {
mentions: mentions,
quotedMessageId: quotedMessageId,
linkPreview: request.linkPreview,
};
}
}
export class WEBJSEngineMediaProcessor
implements IMediaEngineProcessor<Message>
{
hasMedia(message: Message): boolean {
if (!message.hasMedia) {
return false;
}
// Can't get media for revoked messages
return message.type !== 'revoked';
}
getChatId(message: Message): string {
return message.id.remote;
}
getMessageId(message: Message): string {
return message.id._serialized;
}
getMimetype(message: Message): string {
// @ts-ignore
return message.rawData.mimetype;
}
async getMediaBuffer(message: Message): Promise<Buffer | null> {
return message.downloadMedia().then((media: MessageMedia) => {
if (!media) {
return null;
}
return Buffer.from(media.data, 'base64');
});
}
getFilename(message: Message): string | null {
// @ts-ignore
return message.rawData?.filename || null;
}
}
|