trompot 1.5.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +195 -20
  2. package/lib/bot/BotEvents.d.ts +2 -0
  3. package/lib/bot/BotEvents.js.map +1 -1
  4. package/lib/client/Client.js +93 -28
  5. package/lib/client/Client.js.map +1 -1
  6. package/lib/client/ClientFunctionHandler.js +39 -3
  7. package/lib/client/ClientFunctionHandler.js.map +1 -1
  8. package/lib/telegram/TelegramAuth.js +36 -1
  9. package/lib/telegram/TelegramAuth.js.map +1 -1
  10. package/lib/telegram/TelegramBot.d.ts +11 -0
  11. package/lib/telegram/TelegramBot.js +101 -15
  12. package/lib/telegram/TelegramBot.js.map +1 -1
  13. package/lib/telegram/TelegramEvents.d.ts +8 -1
  14. package/lib/telegram/TelegramEvents.js +67 -30
  15. package/lib/telegram/TelegramEvents.js.map +1 -1
  16. package/lib/telegram/TelegramSendingController.js +59 -17
  17. package/lib/telegram/TelegramSendingController.js.map +1 -1
  18. package/lib/telegram/TelegramToRompotConverter.js +44 -14
  19. package/lib/telegram/TelegramToRompotConverter.js.map +1 -1
  20. package/lib/wa/Auth.js +17 -5
  21. package/lib/wa/Auth.js.map +1 -1
  22. package/lib/wa/ConfigWAEvents.d.ts +6 -10
  23. package/lib/wa/ConfigWAEvents.js +220 -426
  24. package/lib/wa/ConfigWAEvents.js.map +1 -1
  25. package/lib/wa/ConvertWAMessage.js +28 -19
  26. package/lib/wa/ConvertWAMessage.js.map +1 -1
  27. package/lib/wa/ID.d.ts +10 -1
  28. package/lib/wa/ID.js +22 -2
  29. package/lib/wa/ID.js.map +1 -1
  30. package/lib/wa/WhatsAppBot.d.ts +58 -11
  31. package/lib/wa/WhatsAppBot.js +365 -648
  32. package/lib/wa/WhatsAppBot.js.map +1 -1
  33. package/lib/wa/constants/ConfigDefaults.d.ts +23 -0
  34. package/lib/wa/constants/ConfigDefaults.js +27 -0
  35. package/lib/wa/constants/ConfigDefaults.js.map +1 -0
  36. package/lib/wa/constants/DisconnectReasons.d.ts +24 -0
  37. package/lib/wa/constants/DisconnectReasons.js +36 -0
  38. package/lib/wa/constants/DisconnectReasons.js.map +1 -0
  39. package/lib/wa/constants/ErrorCodes.d.ts +28 -0
  40. package/lib/wa/constants/ErrorCodes.js +32 -0
  41. package/lib/wa/constants/ErrorCodes.js.map +1 -0
  42. package/lib/wa/constants/JIDPatterns.d.ts +23 -0
  43. package/lib/wa/constants/JIDPatterns.js +38 -0
  44. package/lib/wa/constants/JIDPatterns.js.map +1 -0
  45. package/lib/wa/constants/Timeouts.d.ts +11 -0
  46. package/lib/wa/constants/Timeouts.js +15 -0
  47. package/lib/wa/constants/Timeouts.js.map +1 -0
  48. package/lib/wa/core/ConnectionManager.d.ts +84 -0
  49. package/lib/wa/core/ConnectionManager.js +256 -0
  50. package/lib/wa/core/ConnectionManager.js.map +1 -0
  51. package/lib/wa/core/SessionManager.d.ts +29 -0
  52. package/lib/wa/core/SessionManager.js +155 -0
  53. package/lib/wa/core/SessionManager.js.map +1 -0
  54. package/lib/wa/core/StateManager.d.ts +49 -0
  55. package/lib/wa/core/StateManager.js +135 -0
  56. package/lib/wa/core/StateManager.js.map +1 -0
  57. package/lib/wa/events/CallEventHandler.d.ts +17 -0
  58. package/lib/wa/events/CallEventHandler.js +155 -0
  59. package/lib/wa/events/CallEventHandler.js.map +1 -0
  60. package/lib/wa/events/ChatEventHandler.d.ts +12 -0
  61. package/lib/wa/events/ChatEventHandler.js +74 -0
  62. package/lib/wa/events/ChatEventHandler.js.map +1 -0
  63. package/lib/wa/events/ConnectionEventHandler.d.ts +43 -0
  64. package/lib/wa/events/ConnectionEventHandler.js +305 -0
  65. package/lib/wa/events/ConnectionEventHandler.js.map +1 -0
  66. package/lib/wa/events/ContactEventHandler.d.ts +12 -0
  67. package/lib/wa/events/ContactEventHandler.js +55 -0
  68. package/lib/wa/events/ContactEventHandler.js.map +1 -0
  69. package/lib/wa/events/EventManager.d.ts +43 -0
  70. package/lib/wa/events/EventManager.js +198 -0
  71. package/lib/wa/events/EventManager.js.map +1 -0
  72. package/lib/wa/events/GroupEventHandler.d.ts +12 -0
  73. package/lib/wa/events/GroupEventHandler.js +74 -0
  74. package/lib/wa/events/GroupEventHandler.js.map +1 -0
  75. package/lib/wa/events/HistoryEventHandler.d.ts +16 -0
  76. package/lib/wa/events/HistoryEventHandler.js +101 -0
  77. package/lib/wa/events/HistoryEventHandler.js.map +1 -0
  78. package/lib/wa/events/LIDMappingEventHandler.d.ts +20 -0
  79. package/lib/wa/events/LIDMappingEventHandler.js +39 -0
  80. package/lib/wa/events/LIDMappingEventHandler.js.map +1 -0
  81. package/lib/wa/events/MessageEventHandler.d.ts +16 -0
  82. package/lib/wa/events/MessageEventHandler.js +218 -0
  83. package/lib/wa/events/MessageEventHandler.js.map +1 -0
  84. package/lib/wa/interfaces/ICacheService.d.ts +12 -0
  85. package/lib/wa/interfaces/ICacheService.js +3 -0
  86. package/lib/wa/interfaces/ICacheService.js.map +1 -0
  87. package/lib/wa/interfaces/IConnectionManager.d.ts +15 -0
  88. package/lib/wa/interfaces/IConnectionManager.js +3 -0
  89. package/lib/wa/interfaces/IConnectionManager.js.map +1 -0
  90. package/lib/wa/interfaces/IErrorHandler.d.ts +9 -0
  91. package/lib/wa/interfaces/IErrorHandler.js +3 -0
  92. package/lib/wa/interfaces/IErrorHandler.js.map +1 -0
  93. package/lib/wa/interfaces/ILoggerService.d.ts +13 -0
  94. package/lib/wa/interfaces/ILoggerService.js +3 -0
  95. package/lib/wa/interfaces/ILoggerService.js.map +1 -0
  96. package/lib/wa/interfaces/ISessionManager.d.ts +16 -0
  97. package/lib/wa/interfaces/ISessionManager.js +3 -0
  98. package/lib/wa/interfaces/ISessionManager.js.map +1 -0
  99. package/lib/wa/interfaces/IStateManager.d.ts +41 -0
  100. package/lib/wa/interfaces/IStateManager.js +3 -0
  101. package/lib/wa/interfaces/IStateManager.js.map +1 -0
  102. package/lib/wa/operations/ChatOperations.d.ts +117 -0
  103. package/lib/wa/operations/ChatOperations.js +349 -0
  104. package/lib/wa/operations/ChatOperations.js.map +1 -0
  105. package/lib/wa/operations/GroupOperations.d.ts +31 -0
  106. package/lib/wa/operations/GroupOperations.js +128 -0
  107. package/lib/wa/operations/GroupOperations.js.map +1 -0
  108. package/lib/wa/operations/MessageOperations.d.ts +69 -0
  109. package/lib/wa/operations/MessageOperations.js +335 -0
  110. package/lib/wa/operations/MessageOperations.js.map +1 -0
  111. package/lib/wa/operations/UserOperations.d.ts +100 -0
  112. package/lib/wa/operations/UserOperations.js +216 -0
  113. package/lib/wa/operations/UserOperations.js.map +1 -0
  114. package/lib/wa/services/CacheService.d.ts +45 -0
  115. package/lib/wa/services/CacheService.js +93 -0
  116. package/lib/wa/services/CacheService.js.map +1 -0
  117. package/lib/wa/services/ErrorHandler.d.ts +26 -0
  118. package/lib/wa/services/ErrorHandler.js +73 -0
  119. package/lib/wa/services/ErrorHandler.js.map +1 -0
  120. package/lib/wa/services/LIDMappingService.d.ts +42 -0
  121. package/lib/wa/services/LIDMappingService.js +132 -0
  122. package/lib/wa/services/LIDMappingService.js.map +1 -0
  123. package/lib/wa/services/LIDNormalizationService.d.ts +30 -0
  124. package/lib/wa/services/LIDNormalizationService.js +136 -0
  125. package/lib/wa/services/LIDNormalizationService.js.map +1 -0
  126. package/lib/wa/services/LoggerService.d.ts +44 -0
  127. package/lib/wa/services/LoggerService.js +85 -0
  128. package/lib/wa/services/LoggerService.js.map +1 -0
  129. package/lib/wa/services/PendingMessageQueue.d.ts +46 -0
  130. package/lib/wa/services/PendingMessageQueue.js +119 -0
  131. package/lib/wa/services/PendingMessageQueue.js.map +1 -0
  132. package/lib/wa/services/RetryService.d.ts +25 -0
  133. package/lib/wa/services/RetryService.js +59 -0
  134. package/lib/wa/services/RetryService.js.map +1 -0
  135. package/lib/wa/utils/ConfigValidator.d.ts +15 -0
  136. package/lib/wa/utils/ConfigValidator.js +66 -0
  137. package/lib/wa/utils/ConfigValidator.js.map +1 -0
  138. package/lib/wa/utils/ErrorUtils.d.ts +29 -0
  139. package/lib/wa/utils/ErrorUtils.js +66 -0
  140. package/lib/wa/utils/ErrorUtils.js.map +1 -0
  141. package/lib/wa/utils/Validation.d.ts +18 -0
  142. package/lib/wa/utils/Validation.js +40 -0
  143. package/lib/wa/utils/Validation.js.map +1 -0
  144. package/package.json +4 -3
@@ -1,64 +1,52 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
3
  const baileys_1 = require("@whiskeysockets/baileys");
40
- const boom_1 = require("@hapi/boom");
41
- const long_1 = __importDefault(require("long"));
42
4
  const BotStatus_1 = require("../bot/BotStatus");
43
5
  const ID_1 = require("./ID");
44
- const Call_1 = __importStar(require("../models/Call"));
45
- const Chat_1 = __importDefault(require("../modules/chat/Chat"));
46
- const ConvertWAMessage_1 = __importDefault(require("./ConvertWAMessage"));
47
- const ErrorMessage_1 = __importDefault(require("../messages/ErrorMessage"));
6
+ const ErrorCodes_1 = require("./constants/ErrorCodes");
48
7
  class ConfigWAEvents {
49
8
  constructor(wa) {
9
+ var _a, _b;
10
+ this.cleanupFunctions = [];
11
+ this.stateManager = null;
50
12
  this.wa = wa;
13
+ // Obtém stateManager de forma type-safe
14
+ this.stateManager = ((_b = (_a = this.wa).getStateManager) === null || _b === void 0 ? void 0 : _b.call(_a)) || null;
15
+ }
16
+ /**
17
+ * Limpa todos os listeners configurados
18
+ */
19
+ cleanup() {
20
+ var _a;
21
+ // Remove todos os listeners do socket
22
+ if ((_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.ev) {
23
+ // Remove listeners específicos que foram registrados
24
+ this.cleanupFunctions.forEach(cleanup => {
25
+ try {
26
+ cleanup();
27
+ }
28
+ catch (error) {
29
+ // Ignora erros ao limpar
30
+ }
31
+ });
32
+ this.cleanupFunctions = [];
33
+ }
51
34
  }
52
35
  configureAll() {
36
+ // CRÍTICO: connection.update deve ser configurado PRIMEIRO
37
+ // O Baileys pode emitir o QR code no primeiro connection.update
53
38
  this.configConnectionUpdate();
54
- this.configHistorySet();
55
- this.configContactsUpsert();
56
- this.configContactsUpdate();
57
- this.configChatsDelete();
58
- this.configGroupsUpdate();
59
- this.configMessagesUpsert();
60
- this.configMessagesUpdate();
61
- this.configCall();
39
+ // REMOVIDO: messages.upsert e messages.update
40
+ // Agora são gerenciados exclusivamente pelo MessageEventHandler
41
+ // para evitar processamento duplicado
42
+ // REMOVIDO: history, contacts, groups, chats, call
43
+ // Agora são gerenciados pelos handlers especializados:
44
+ // - HistoryEventHandler
45
+ // - ContactEventHandler
46
+ // - GroupEventHandler
47
+ // - ChatEventHandler
48
+ // - CallEventHandler
49
+ // Mantém apenas eventos específicos que não têm handlers especializados
62
50
  this.configCBNotifications();
63
51
  }
64
52
  configCBNotifications() {
@@ -68,7 +56,7 @@ class ConfigWAEvents {
68
56
  this.configCBNotificationDemote();
69
57
  }
70
58
  configCBNotificationRemove() {
71
- this.wa.sock.ws.on('CB:notification,,remove', async (data) => {
59
+ const handler = async (data) => {
72
60
  var _a;
73
61
  for (const content of ((_a = data.content[0]) === null || _a === void 0 ? void 0 : _a.content) || []) {
74
62
  try {
@@ -78,10 +66,15 @@ class ConfigWAEvents {
78
66
  this.wa.emit('error', err);
79
67
  }
80
68
  }
69
+ };
70
+ this.wa.sock.ws.on('CB:notification,,remove', handler);
71
+ this.cleanupFunctions.push(() => {
72
+ var _a;
73
+ (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.ws.off('CB:notification,,remove', handler);
81
74
  });
82
75
  }
83
76
  configCBNotificationAdd() {
84
- this.wa.sock.ws.on('CB:notification,,add', async (data) => {
77
+ const handler = async (data) => {
85
78
  var _a;
86
79
  for (const content of ((_a = data.content[0]) === null || _a === void 0 ? void 0 : _a.content) || []) {
87
80
  try {
@@ -93,10 +86,15 @@ class ConfigWAEvents {
93
86
  this.wa.emit('error', err);
94
87
  }
95
88
  }
89
+ };
90
+ this.wa.sock.ws.on('CB:notification,,add', handler);
91
+ this.cleanupFunctions.push(() => {
92
+ var _a;
93
+ (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.ws.off('CB:notification,,add', handler);
96
94
  });
97
95
  }
98
96
  configCBNotificationPromote() {
99
- this.wa.sock.ws.on('CB:notification,,promote', async (data) => {
97
+ const handler = async (data) => {
100
98
  var _a;
101
99
  for (const content of ((_a = data.content[0]) === null || _a === void 0 ? void 0 : _a.content) || []) {
102
100
  try {
@@ -106,10 +104,15 @@ class ConfigWAEvents {
106
104
  this.wa.emit('error', err);
107
105
  }
108
106
  }
107
+ };
108
+ this.wa.sock.ws.on('CB:notification,,promote', handler);
109
+ this.cleanupFunctions.push(() => {
110
+ var _a;
111
+ (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.ws.off('CB:notification,,promote', handler);
109
112
  });
110
113
  }
111
114
  configCBNotificationDemote() {
112
- this.wa.sock.ws.on('CB:notification,,demote', async (data) => {
115
+ const handler = async (data) => {
113
116
  var _a;
114
117
  for (const content of ((_a = data.content[0]) === null || _a === void 0 ? void 0 : _a.content) || []) {
115
118
  try {
@@ -119,231 +122,199 @@ class ConfigWAEvents {
119
122
  this.wa.emit('error', err);
120
123
  }
121
124
  }
125
+ };
126
+ this.wa.sock.ws.on('CB:notification,,demote', handler);
127
+ this.cleanupFunctions.push(() => {
128
+ var _a;
129
+ (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.ws.off('CB:notification,,demote', handler);
122
130
  });
123
131
  }
124
- async readMessages(messages, type = 'notify') {
125
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
126
- try {
127
- for (const message of messages || []) {
128
- try {
129
- if (!message)
130
- continue;
131
- // v7: key pode ser null/undefined no tipo, garantir antes de usar
132
- const key = message.key;
133
- if (!key)
134
- continue;
135
- if (key.remoteJid == 'status@broadcast')
136
- continue;
137
- if (!message.message) {
138
- if (!(message.messageStubType ==
139
- baileys_1.proto.WebMessageInfo.StubType.CIPHERTEXT)) {
140
- return; // Not read other null messages
141
- }
142
- const msgRetryCount = (_a = this.wa.config.msgRetryCounterCache) === null || _a === void 0 ? void 0 : _a.get(key.id);
143
- if (msgRetryCount != this.wa.config.maxMsgRetryCount) {
144
- const time = this.wa.config.retryRequestDelayMs || 1000;
145
- await new Promise((res) => setTimeout(res, time * 3));
146
- const newMsgRetryCount = (_b = this.wa.config.msgRetryCounterCache) === null || _b === void 0 ? void 0 : _b.get(key.id);
147
- if (!this.wa.config.readAllFailedMessages) {
148
- if (msgRetryCount &&
149
- newMsgRetryCount &&
150
- msgRetryCount != newMsgRetryCount) {
151
- return; // Not read duplicated failed message
152
- }
153
- }
154
- }
155
- }
156
- if (((_d = (_c = message.message) === null || _c === void 0 ? void 0 : _c.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) ==
157
- baileys_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SYNC_RESPONSE ||
158
- ((_f = (_e = message.message) === null || _e === void 0 ? void 0 : _e.protocolMessage) === null || _f === void 0 ? void 0 : _f.type) ==
159
- baileys_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE ||
160
- ((_h = (_g = message.message) === null || _g === void 0 ? void 0 : _g.protocolMessage) === null || _h === void 0 ? void 0 : _h.type) ==
161
- baileys_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_REQUEST ||
162
- ((_k = (_j = message.message) === null || _j === void 0 ? void 0 : _j.protocolMessage) === null || _k === void 0 ? void 0 : _k.type) ==
163
- baileys_1.proto.Message.ProtocolMessage.Type
164
- .APP_STATE_FATAL_EXCEPTION_NOTIFICATION ||
165
- ((_m = (_l = message.message) === null || _l === void 0 ? void 0 : _l.protocolMessage) === null || _m === void 0 ? void 0 : _m.type) ==
166
- baileys_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING ||
167
- ((_p = (_o = message.message) === null || _o === void 0 ? void 0 : _o.protocolMessage) === null || _p === void 0 ? void 0 : _p.type) ==
168
- baileys_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION ||
169
- ((_r = (_q = message.message) === null || _q === void 0 ? void 0 : _q.protocolMessage) === null || _r === void 0 ? void 0 : _r.type) ==
170
- baileys_1.proto.Message.ProtocolMessage.Type
171
- .INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC) {
172
- return; // Not read empty messages
173
- }
174
- if (this.wa.messagesCached.includes(key.id))
175
- return;
176
- this.wa.addMessageCache(key.id);
177
- const chatId = (0, ID_1.fixID)(key.remoteJid || this.wa.id);
178
- const chat = await this.wa.getChat(new Chat_1.default(chatId));
179
- let timestamp;
180
- if (message.messageTimestamp) {
181
- if (long_1.default.isLong(message.messageTimestamp)) {
182
- timestamp = message.messageTimestamp.toNumber() * 1000;
183
- }
184
- else {
185
- timestamp = message.messageTimestamp * 1000;
186
- }
187
- }
188
- await this.wa.updateChat({
189
- id: chatId,
190
- unreadCount: ((chat === null || chat === void 0 ? void 0 : chat.unreadCount) || 0) + 1,
191
- timestamp,
192
- name: ((_s = key.id) === null || _s === void 0 ? void 0 : _s.includes('@s')) && !key.fromMe
193
- ? message.pushName || message.verifiedBizName || undefined
194
- : undefined,
195
- });
196
- const userId = (0, ID_1.fixID)(key.fromMe
197
- ? this.wa.id
198
- : key.participant ||
199
- message.participant ||
200
- key.remoteJid ||
201
- '');
202
- await this.wa.updateUser({
203
- id: userId,
204
- name: message.pushName || message.verifiedBizName || undefined,
205
- });
206
- // v7: tipagem de WAMessageKey exige key não nula; após o guard podemos fazer cast
207
- const msg = await new ConvertWAMessage_1.default(this.wa, message, type).get();
208
- if (msg.fromMe && msg.isUnofficial) {
209
- await this.wa.updateChat({ id: msg.chat.id, unreadCount: 0 });
210
- }
211
- this.wa.emit('message', msg);
212
- }
213
- catch (err) {
214
- this.wa.emit('message', new ErrorMessage_1.default((0, ID_1.fixID)(((_t = message === null || message === void 0 ? void 0 : message.key) === null || _t === void 0 ? void 0 : _t.remoteJid) || ''), err && err instanceof Error
215
- ? err
216
- : new Error(JSON.stringify(err))));
217
- }
218
- }
219
- }
220
- catch (err) {
221
- this.wa.emit('error', err);
222
- }
223
- }
224
- configMessagesUpsert() {
225
- this.wa.sock.ev.on('messages.upsert', async (m) => {
226
- try {
227
- await this.readMessages((m === null || m === void 0 ? void 0 : m.messages) || [], m.type);
228
- }
229
- catch (err) {
230
- this.wa.emit('error', err);
231
- }
232
- });
233
- }
234
- configMessagesUpdate() {
235
- this.wa.sock.ev.on('messages.update', async (messages) => {
236
- var _a, _b;
237
- try {
238
- for (const message of messages || []) {
239
- try {
240
- if (!message.key || message.key.remoteJid == 'status@broadcast')
241
- return;
242
- await this.readMessages([{ key: message.key, ...message.update }]);
243
- if (!((_a = message === null || message === void 0 ? void 0 : message.update) === null || _a === void 0 ? void 0 : _a.status))
244
- return;
245
- const msg = await new ConvertWAMessage_1.default(this.wa, message).get();
246
- msg.isUpdate = true;
247
- this.wa.emit('message', msg);
248
- }
249
- catch (err) {
250
- this.wa.emit('message', new ErrorMessage_1.default((0, ID_1.fixID)(((_b = message === null || message === void 0 ? void 0 : message.key) === null || _b === void 0 ? void 0 : _b.remoteJid) || ''), err && err instanceof Error
251
- ? err
252
- : new Error(JSON.stringify(err))));
253
- }
254
- }
255
- }
256
- catch (err) {
257
- this.wa.emit('error', err);
258
- }
259
- });
260
- }
132
+ // REMOVIDO: readMessages, configMessagesUpsert, configMessagesUpdate
133
+ // Agora são gerenciados exclusivamente pelo MessageEventHandler
134
+ // para evitar processamento duplicado
261
135
  configConnectionUpdate() {
136
+ // CRÍTICO: Configurar o listener ANTES de qualquer outra coisa
137
+ // O Baileys pode emitir o QR code no primeiro connection.update
262
138
  this.wa.sock.ev.on('connection.update', async (update) => {
263
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
139
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
264
140
  try {
265
141
  this.wa.connectionListeners = this.wa.connectionListeners.filter((listener) => !listener(update));
266
142
  if (update.connection == 'connecting') {
267
- this.wa.lastConnectionUpdateDate = Date.now();
268
- this.wa.status = BotStatus_1.BotStatus.Offline;
143
+ // Usa StateManager através dos setters (type-safe)
144
+ if (this.stateManager) {
145
+ this.stateManager.setLastConnectionUpdateDate(Date.now());
146
+ this.stateManager.setStatus(BotStatus_1.BotStatus.Offline);
147
+ }
269
148
  this.wa.emit('connecting', { action: 'connecting' });
270
149
  }
150
+ // IMPORTANTE: O Baileys envia o QR code como string no campo 'qr' do connection.update
151
+ // O QR code será emitido como texto através do evento 'qr'
271
152
  if (update.qr) {
153
+ // Emite o QR code (string) para o cliente
154
+ // O QR code pode ser atualizado várias vezes, então emitimos sempre que houver
272
155
  this.wa.emit('qr', update.qr);
273
156
  }
274
157
  if (update.connection == 'open') {
275
158
  const uptime = Date.now();
276
- this.wa.lastConnectionUpdateDate = uptime;
277
- this.wa.status = BotStatus_1.BotStatus.Online;
278
- this.wa.id = (0, ID_1.fixID)(((_b = (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.id) || '');
279
- this.wa.phoneNumber = (0, ID_1.getPhoneNumber)(this.wa.id);
280
- this.wa.name =
281
- ((_d = (_c = this.wa.sock) === null || _c === void 0 ? void 0 : _c.user) === null || _d === void 0 ? void 0 : _d.name) ||
282
- ((_f = (_e = this.wa.sock) === null || _e === void 0 ? void 0 : _e.user) === null || _f === void 0 ? void 0 : _f.notify) ||
283
- ((_h = (_g = this.wa.sock) === null || _g === void 0 ? void 0 : _g.user) === null || _h === void 0 ? void 0 : _h.verifiedName) ||
284
- '';
285
- this.wa.profileUrl = ((_k = (_j = this.wa.sock) === null || _j === void 0 ? void 0 : _j.user) === null || _k === void 0 ? void 0 : _k.imgUrl) || '';
286
- this.wa.readUser({ id: this.wa.id }, {
287
- notify: this.wa.name || undefined,
288
- imgUrl: this.wa.profileUrl || undefined,
289
- });
290
- this.wa.readChat({ id: this.wa.id }, { subject: this.wa.name || undefined });
291
- this.wa.emit('open', { isNewLogin: update.isNewLogin || false });
292
- setTimeout(async () => {
293
- try {
294
- if (this.wa.lastConnectionUpdateDate != uptime)
295
- return;
296
- await this.wa.reconnect(true, false);
159
+ // Usa StateManager através dos setters (type-safe)
160
+ if (this.stateManager) {
161
+ this.stateManager.setLastConnectionUpdateDate(uptime);
162
+ this.stateManager.setStatus(BotStatus_1.BotStatus.Online);
163
+ this.stateManager.setLastDisconnectError(undefined);
164
+ // Tenta obter ID de múltiplas fontes (sock.user.id pode não estar disponível imediatamente)
165
+ // 1. Tenta sock.user.id
166
+ // 2. Tenta creds.me.id (das credenciais, mais confiável)
167
+ let rawId = ((_b = (_a = this.wa.sock) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.id) || '';
168
+ // Se não encontrou, tenta das credenciais
169
+ if (!rawId && ((_f = (_e = (_d = (_c = this.wa.sock) === null || _c === void 0 ? void 0 : _c.authState) === null || _d === void 0 ? void 0 : _d.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.id)) {
170
+ rawId = this.wa.sock.authState.creds.me.id;
297
171
  }
298
- catch (error) {
299
- this.wa.emit('error', error);
300
- }
301
- }, this.wa.config.autoRestartInterval);
172
+ const id = (0, ID_1.fixID)(rawId);
173
+ this.stateManager.setId(id);
174
+ // Obtém o número de telefone do ID original (antes do fixID) ou do ID fixado
175
+ // Tenta primeiro do ID original, depois do fixado
176
+ const phoneNumber = (0, ID_1.getPhoneNumber)(rawId) || (0, ID_1.getPhoneNumber)(id);
177
+ this.stateManager.setPhoneNumber(phoneNumber);
178
+ this.stateManager.setName(((_h = (_g = this.wa.sock) === null || _g === void 0 ? void 0 : _g.user) === null || _h === void 0 ? void 0 : _h.name) ||
179
+ ((_k = (_j = this.wa.sock) === null || _j === void 0 ? void 0 : _j.user) === null || _k === void 0 ? void 0 : _k.notify) ||
180
+ ((_m = (_l = this.wa.sock) === null || _l === void 0 ? void 0 : _l.user) === null || _m === void 0 ? void 0 : _m.verifiedName) ||
181
+ ((_r = (_q = (_p = (_o = this.wa.sock) === null || _o === void 0 ? void 0 : _o.authState) === null || _p === void 0 ? void 0 : _p.creds) === null || _q === void 0 ? void 0 : _q.me) === null || _r === void 0 ? void 0 : _r.name) ||
182
+ '');
183
+ this.stateManager.setProfileUrl(((_t = (_s = this.wa.sock) === null || _s === void 0 ? void 0 : _s.user) === null || _t === void 0 ? void 0 : _t.imgUrl) || '');
184
+ this.wa.readUser({ id: this.stateManager.id }, {
185
+ notify: this.stateManager.name || undefined,
186
+ imgUrl: this.stateManager.profileUrl || undefined,
187
+ });
188
+ this.wa.readChat({ id: this.stateManager.id }, { subject: this.stateManager.name || undefined });
189
+ }
190
+ this.wa.emit('open', { isNewLogin: update.isNewLogin || false });
191
+ // REMOVIDO: Auto-restart que estava causando reconexões desnecessárias
192
+ // O Baileys já gerencia a conexão automaticamente
193
+ // setTimeout(async () => {
194
+ // try {
195
+ // if (this.wa.lastConnectionUpdateDate != uptime) return;
196
+ // await this.wa.reconnect(true, false);
197
+ // } catch (error) {
198
+ // this.wa.emit('error', error);
199
+ // }
200
+ // }, this.wa.config.autoRestartInterval);
201
+ // Limpa interval anterior se existir
302
202
  if (this.wa.checkConnectionInterval !== null) {
303
203
  clearInterval(this.wa.checkConnectionInterval);
204
+ this.wa.checkConnectionInterval = null;
304
205
  }
305
- this.wa.checkConnectionInterval = setInterval(() => {
306
- if (!this.wa.sock) {
307
- if (this.wa.checkConnectionInterval) {
308
- clearInterval(this.wa.checkConnectionInterval);
309
- this.wa.checkConnectionInterval = null;
310
- }
311
- return;
312
- }
313
- if (this.wa.sock.ws.isOpen)
314
- return;
315
- this.wa.sock.ev.emit('connection.update', {
316
- connection: 'close',
317
- lastDisconnect: {
318
- date: new Date(),
319
- error: new boom_1.Boom('Socket closed', {
320
- statusCode: baileys_1.DisconnectReason.connectionClosed,
321
- }),
322
- },
323
- });
324
- }, 10000);
206
+ // REMOVIDO: Interval que estava forçando desconexão após 10 segundos
207
+ // Isso estava causando o erro 402 após escanear o QR code
208
+ // O Baileys já gerencia a conexão e emite eventos de desconexão quando necessário
209
+ // this.wa.checkConnectionInterval = setInterval(() => {
210
+ // if (!this.wa.sock) {
211
+ // if (this.wa.checkConnectionInterval) {
212
+ // clearInterval(this.wa.checkConnectionInterval);
213
+ // this.wa.checkConnectionInterval = null;
214
+ // }
215
+ // return;
216
+ // }
217
+ // if (this.wa.sock.ws.isOpen) return;
218
+ // this.wa.sock.ev.emit('connection.update', {
219
+ // connection: 'close',
220
+ // lastDisconnect: {
221
+ // date: new Date(),
222
+ // error: new Boom('Socket closed', {
223
+ // statusCode: DisconnectReason.connectionClosed,
224
+ // }),
225
+ // },
226
+ // });
227
+ // }, 10000);
325
228
  this.wa.eventsIsStoped = false;
326
229
  await this.wa.sock.groupFetchAllParticipating();
327
230
  }
328
231
  if (update.connection == 'close') {
329
- this.wa.lastConnectionUpdateDate = Date.now();
330
- this.wa.status = BotStatus_1.BotStatus.Offline;
331
- const status = ((_o = (_m = (_l = update.lastDisconnect) === null || _l === void 0 ? void 0 : _l.error) === null || _m === void 0 ? void 0 : _m.output) === null || _o === void 0 ? void 0 : _o.statusCode) ||
332
- ((_p = update.lastDisconnect) === null || _p === void 0 ? void 0 : _p.error) ||
333
- 500;
232
+ // Delegamos o tratamento completo de 'close' para o ConnectionEventHandler
233
+ // para garantir limpeza de sessão (401/421) e restartRequired (515).
234
+ if ((_u = this.wa.connectionEventHandler) === null || _u === void 0 ? void 0 : _u.onConnectionClose) {
235
+ try {
236
+ if (!update.connection) {
237
+ return; // Sem estado de conexão, nada a fazer
238
+ }
239
+ // Asserção para ConnectionState completo (connection é obrigatório aqui)
240
+ await this.wa.connectionEventHandler.onConnectionClose(update);
241
+ return; // Evita duplicar emissões de eventos/estado
242
+ }
243
+ catch (err) {
244
+ this.wa.emit('error', err);
245
+ return;
246
+ }
247
+ }
248
+ const status = ((_x = (_w = (_v = update.lastDisconnect) === null || _v === void 0 ? void 0 : _v.error) === null || _w === void 0 ? void 0 : _w.output) === null || _x === void 0 ? void 0 : _x.statusCode) ||
249
+ (typeof ((_y = update.lastDisconnect) === null || _y === void 0 ? void 0 : _y.error) === 'number'
250
+ ? update.lastDisconnect.error
251
+ : undefined) ||
252
+ ErrorCodes_1.ErrorCodes.INTERNAL_SERVER_ERROR;
253
+ // Usa StateManager através dos setters (type-safe)
254
+ if (this.stateManager) {
255
+ this.stateManager.setLastConnectionUpdateDate(Date.now());
256
+ this.stateManager.setStatus(BotStatus_1.BotStatus.Offline);
257
+ this.stateManager.setLastDisconnectError(typeof status === 'number' ? status : undefined);
258
+ }
334
259
  if (this.wa.checkConnectionInterval !== null) {
335
260
  clearInterval(this.wa.checkConnectionInterval);
336
261
  this.wa.checkConnectionInterval = null;
337
262
  }
338
- if (status === baileys_1.DisconnectReason.loggedOut) {
263
+ if (status === baileys_1.DisconnectReason.loggedOut || status === ErrorCodes_1.ErrorCodes.LOGGED_OUT || status === ErrorCodes_1.ErrorCodes.LOGGED_OUT_ALT) {
264
+ // Erro 401/421: Logged Out - Sessão foi morta do WhatsApp
265
+ // A limpeza da sessão é feita pelo ConnectionEventHandler
266
+ // Aqui apenas emite eventos para o cliente ser notificado
267
+ this.wa.emit('close', {
268
+ reason: status,
269
+ message: ErrorCodes_1.ErrorMessages.LOGGED_OUT(status)
270
+ });
339
271
  this.wa.emit('stop', { isLogout: true });
340
272
  }
341
- else if (status === 402) {
342
- this.wa.emit('stop', { isLogout: false });
273
+ else if (status === ErrorCodes_1.ErrorCodes.CONNECTION_CLOSED) {
274
+ // 402 = connectionClosed - geralmente é temporário
275
+ // NÃO emite 'stop' para permitir que o Baileys gerencie a reconexão
276
+ // Apenas emite 'close' para notificar o cliente
277
+ this.wa.emit('close', {
278
+ reason: status,
279
+ message: ErrorCodes_1.ErrorMessages.CONNECTION_CLOSED
280
+ });
281
+ }
282
+ else if (status === ErrorCodes_1.ErrorCodes.REQUEST_TIMEOUT) {
283
+ // 408 = Request Timeout - requisição expirou, geralmente temporário
284
+ // Similar ao 402 - não limpa sessão, permite reconexão automática
285
+ this.wa.emit('close', {
286
+ reason: status,
287
+ message: ErrorCodes_1.ErrorMessages.REQUEST_TIMEOUT
288
+ });
289
+ // Não emite 'stop' - permite que o Baileys tente reconectar automaticamente
290
+ }
291
+ else if (status === ErrorCodes_1.ErrorCodes.CONNECTION_TERMINATED) {
292
+ // Erro 428: Connection Terminated - Erro temporário de conexão
293
+ // NÃO é sessão inválida (isso seria 401/421)
294
+ // Permite reconexão automática - o Baileys tentará reconectar
295
+ this.wa.emit('close', {
296
+ reason: status,
297
+ message: ErrorCodes_1.ErrorMessages.CONNECTION_TERMINATED
298
+ });
299
+ // Não emite 'stop' - permite que o Baileys tente reconectar automaticamente
300
+ }
301
+ else if (status === ErrorCodes_1.ErrorCodes.INTERNAL_SERVER_ERROR) {
302
+ // 500 = Internal Server Error - erro temporário do servidor
303
+ // Permite reconexão automática
304
+ this.wa.emit('close', {
305
+ reason: status,
306
+ message: ErrorCodes_1.ErrorMessages.INTERNAL_SERVER_ERROR_MSG
307
+ });
308
+ // Não emite 'stop' - permite que o ConnectionManager tente reconectar
309
+ // ConnectionManager será chamado pelo ConnectionEventHandler
343
310
  }
344
311
  else if (status == baileys_1.DisconnectReason.restartRequired) {
345
- await this.wa.saveCreds(this.wa.sock.authState.creds);
346
- await this.wa.reconnect(true, true);
312
+ // restartRequired é tratado pelo ConnectionEventHandler
313
+ // Apenas emite close para notificar (não trata aqui para evitar duplicação)
314
+ this.wa.emit('close', {
315
+ reason: status,
316
+ message: 'Reinício necessário após autenticação'
317
+ });
347
318
  }
348
319
  else {
349
320
  this.wa.emit('close', { reason: status });
@@ -355,183 +326,6 @@ class ConfigWAEvents {
355
326
  }
356
327
  });
357
328
  }
358
- configHistorySet() {
359
- const ignoreChats = [];
360
- this.wa.sock.ev.on('messaging-history.set', async (update) => {
361
- var _a, _b, _c, _d;
362
- if (!this.wa.config.autoSyncHistory)
363
- return;
364
- for (const chat of update.chats || []) {
365
- try {
366
- // v7: id pode ser null/undefined no tipo, ignorar chats sem id
367
- if (!chat.id)
368
- continue;
369
- if (!('unreadCount' in chat) || chat.isDefaultSubgroup === true) {
370
- ignoreChats.push(chat.id);
371
- continue;
372
- }
373
- const isGroup = (0, baileys_1.isJidGroup)(chat.id);
374
- if (!('pinned' in chat) || isGroup) {
375
- if (!isGroup) {
376
- ignoreChats.push(chat.id);
377
- continue;
378
- }
379
- if (!('endOfHistoryTransferType' in chat) &&
380
- !('isDefaultSubgroup' in chat)) {
381
- ignoreChats.push(chat.id);
382
- continue;
383
- }
384
- }
385
- if ((((_a = chat.participant) === null || _a === void 0 ? void 0 : _a.length) || 0) > 0) {
386
- if (!((_b = chat.participant) === null || _b === void 0 ? void 0 : _b.some((p) => p.userJid == this.wa.id))) {
387
- ignoreChats.push(chat.id);
388
- continue;
389
- }
390
- }
391
- const autoLoad = isGroup
392
- ? this.wa.config.autoLoadGroupInfo
393
- : this.wa.config.autoLoadContactInfo;
394
- if (autoLoad) {
395
- // v7: tipo de chat.id permite null, mas já garantimos acima que existe
396
- await this.wa.readChat({ id: chat.id }, chat);
397
- }
398
- }
399
- catch (err) {
400
- this.wa.emit('error', err);
401
- }
402
- }
403
- for (const message of (update === null || update === void 0 ? void 0 : update.messages) || []) {
404
- try {
405
- if (!(message === null || message === void 0 ? void 0 : message.message) ||
406
- !((_c = message.key) === null || _c === void 0 ? void 0 : _c.remoteJid) ||
407
- message.key.remoteJid == 'status@broadcast')
408
- continue;
409
- if (ignoreChats.includes((0, ID_1.fixID)(message.key.remoteJid || '')))
410
- continue;
411
- const msg = await new ConvertWAMessage_1.default(this.wa, message).get();
412
- msg.isOld = true;
413
- this.wa.emit('message', msg);
414
- }
415
- catch (err) {
416
- const msg = new ErrorMessage_1.default((0, ID_1.fixID)(((_d = message === null || message === void 0 ? void 0 : message.key) === null || _d === void 0 ? void 0 : _d.remoteJid) || ''), err && err instanceof Error ? err : new Error(JSON.stringify(err)));
417
- msg.isOld = true;
418
- this.wa.emit('message', msg);
419
- }
420
- }
421
- });
422
- }
423
- configContactsUpdate() {
424
- this.wa.sock.ev.on('contacts.update', async (updates) => {
425
- if (!this.wa.config.autoLoadContactInfo)
426
- return;
427
- for (const update of updates) {
428
- try {
429
- if ((0, baileys_1.isJidGroup)(update.id)) {
430
- await this.wa.readChat({ id: update.id }, update);
431
- }
432
- else {
433
- await this.wa.readUser({ id: update.id }, update);
434
- }
435
- }
436
- catch (err) {
437
- this.wa.emit('error', err);
438
- }
439
- }
440
- });
441
- }
442
- configContactsUpsert() {
443
- this.wa.sock.ev.on('contacts.upsert', async (updates) => {
444
- if (!this.wa.config.autoLoadContactInfo)
445
- return;
446
- for (const update of updates) {
447
- try {
448
- if ((0, baileys_1.isJidGroup)(update.id)) {
449
- await this.wa.readChat({ id: update.id }, update);
450
- }
451
- else {
452
- await this.wa.readUser({ id: update.id }, update);
453
- }
454
- }
455
- catch (err) {
456
- this.wa.emit('error', err);
457
- }
458
- }
459
- });
460
- }
461
- configGroupsUpdate() {
462
- this.wa.sock.ev.on('groups.update', async (updates) => {
463
- if (!this.wa.config.autoLoadGroupInfo)
464
- return;
465
- for (const update of updates) {
466
- try {
467
- if (!(update === null || update === void 0 ? void 0 : update.id))
468
- continue;
469
- const chat = await this.wa.getChat(new Chat_1.default(update.id));
470
- if (chat == null) {
471
- await this.wa.readChat({ id: update.id }, update, true);
472
- }
473
- else {
474
- await this.wa.readChat({ id: update.id }, update, false);
475
- }
476
- }
477
- catch (err) {
478
- this.wa.emit('error', err);
479
- }
480
- }
481
- });
482
- }
483
- configChatsDelete() {
484
- this.wa.sock.ev.on('chats.delete', async (deletions) => {
485
- for (const id of deletions) {
486
- try {
487
- await this.wa.removeChat(new Chat_1.default(id));
488
- }
489
- catch (err) {
490
- this.wa.emit('error', err);
491
- }
492
- }
493
- });
494
- }
495
- configCall() {
496
- this.wa.sock.ev.on('call', async (events) => {
497
- for (const event of events || []) {
498
- try {
499
- const chat = event.chatId || event.groupJid || event.from || '';
500
- let status;
501
- switch (event.status) {
502
- case 'offer':
503
- status = Call_1.CallStatus.Offer;
504
- break;
505
- case 'ringing':
506
- status = Call_1.CallStatus.Ringing;
507
- break;
508
- case 'reject':
509
- status = Call_1.CallStatus.Reject;
510
- break;
511
- case 'accept':
512
- status = Call_1.CallStatus.Accept;
513
- break;
514
- case 'timeout':
515
- status = Call_1.CallStatus.Timeout;
516
- break;
517
- default:
518
- status = Call_1.CallStatus.Ringing;
519
- break;
520
- }
521
- const call = new Call_1.default(event.id, chat, event.from, status, {
522
- date: event.date || new Date(),
523
- isVideo: !!event.isVideo,
524
- offline: !!event.offline,
525
- latencyMs: event.latencyMs || 1,
526
- });
527
- this.wa.emit('call', call);
528
- }
529
- catch (err) {
530
- this.wa.emit('error', err);
531
- }
532
- }
533
- });
534
- }
535
329
  }
536
330
  exports.default = ConfigWAEvents;
537
331
  //# sourceMappingURL=ConfigWAEvents.js.map