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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 * This file is part of WPPConnect.
 *
 * WPPConnect is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WPPConnect is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with WPPConnect.  If not, see <https://www.gnu.org/licenses/>.
 */

import { ChatListOptions } from '@wppconnect/wa-js/dist/chat';
import { GetMessagesFromRowIdOptions } from '@wppconnect/wa-js/dist/indexdb';
import { Page } from 'puppeteer';
import { CreateConfig } from '../../config/create-config';
import { SessionToken } from '../../token-store';
import { evaluateAndReturn } from '../helpers';
import {
  Chat,
  ContactStatus,
  ProfilePicThumbObj,
  WhatsappProfile,
  Wid,
} from '../model';
import { SenderLayer } from './sender.layer';

export class RetrieverLayer extends SenderLayer {
  constructor(public page: Page, session?: string, options?: CreateConfig) {
    super(page, session, options);
  }

  /**
   * Returns a list of mute and non-mute users
   * @category Chat
   * @param type return type: all, toMute and noMute.
   * @returns obj
   */
  public async getListMutes(type?: string): Promise<object> {
    return await evaluateAndReturn(
      this.page,
      (type: string) => WAPI.getListMute(type),
      type
    );
  }

  /**
   * Returns browser session token
   * @category Host
   * @returns obj [token]
   */
  public async getSessionTokenBrowser(
    removePath?: boolean
  ): Promise<SessionToken> {
    if (removePath === true) {
      await evaluateAndReturn(this.page, () => {
        window['pathSession'] = true;
      });
    }
    if (await this.isMultiDevice()) {
      return await this.page
        .evaluate(() => {
          if (window.localStorage) {
            return {
              WABrowserId:
                window.localStorage.getItem('WABrowserId') || 'MultiDevice',
              WASecretBundle: 'MultiDevice',
              WAToken1: 'MultiDevice',
              WAToken2: 'MultiDevice',
            };
          }
          return null;
        })
        .catch(() => null);
    }
    return await this.page
      .evaluate(() => {
        if (window.localStorage) {
          return {
            WABrowserId: window.localStorage.getItem('WABrowserId'),
            WASecretBundle: window.localStorage.getItem('WASecretBundle'),
            WAToken1: window.localStorage.getItem('WAToken1'),
            WAToken2: window.localStorage.getItem('WAToken2'),
          };
        }
        return null;
      })
      .catch(() => null);
  }

  /**
   * Receive all blocked contacts
   * @category Blocklist
   * @returns array of [0,1,2,3....]
   */
  public async getBlockList() {
    return await evaluateAndReturn(this.page, () =>
      WPP.blocklist.all().map((b) => b.toString())
    );
  }

  /**
   * Retrieves all chats
   * Deprecated in favor of {@link listChats}
   *
   * @category Chat
   * @returns array of [Chat]
   * @deprecated Deprecated in favor of listChats.
   */
  public async getAllChats(withNewMessageOnly = false) {
    this.logger.warn(
      'Deprecated: This function [getAllChats] is deprecated in favor of the listChats function. Please update your code accordingly.'
    );
    if (withNewMessageOnly) {
      return evaluateAndReturn(this.page, () => WAPI.getAllChatsWithNewMsg());
    } else {
      return evaluateAndReturn(this.page, () => WAPI.getAllChats());
    }
  }

  /**
   * Return list of chats
   *  * @example
   * ```javascript
   * // All chats
   * const chats = await client.listChats();
   *
   * // Some chats
   * const chats = client.listChats({count: 20});
   *
   * // 20 chats before specific chat
   * const chats = client.listChats({count: 20, direction: 'before', id: '[number]@c.us'});
   *
   * // Only users chats
   * const chats = await client.listChats({onlyUsers: true});
   *
   * // Only groups chats
   * const chats = await client.listChats({onlyGroups: true});
   *
   * // Only with label Text
   * const chats = await client.listChats({withLabels: ['Test']});
   *
   * // Only with label id
   * const chats = await client.listChats({withLabels: ['1']});
   *
   * // Only with label with one of text or id
   * const chats = await client.listChats({withLabels: ['Alfa','5']});
   * ```
   * @category Chat
   * @returns array of [Chat]
   */
  public async listChats(options?: ChatListOptions): Promise<Chat[]> {
    return await evaluateAndReturn(
      this.page,
      async ({ options }) => {
        const chats = await WPP.chat.list(options);

        const serialized = chats.map((c) => WAPI._serializeChatObj(c));
        return serialized;
      },
      { options }
    );
  }

  /**
   * Checks if a number is a valid WA number
   * @category Contact
   * @param contactId, you need to include the @c.us at the end.
   * @returns contact details as promise
   */
  public async checkNumberStatus(contactId: string): Promise<WhatsappProfile> {
    return await evaluateAndReturn(
      this.page,
      (contactId) => WAPI.checkNumberStatus(contactId),
      contactId
    );
  }

  /**
   * Retrieves all chats with messages
   * Deprecated in favor of {@link listChats}
   *
   * @category Chat
   * @returns array of [Chat]
   * @deprecated Deprecated in favor of listChats.
   */
  public async getAllChatsWithMessages(withNewMessageOnly = false) {
    this.logger.warn(
      'Deprecated: This function [getAllChatsWithMessages] is deprecated in favor of the listChats function. Please update your code accordingly.'
    );
    return evaluateAndReturn(
      this.page,
      (withNewMessageOnly: boolean) =>
        WAPI.getAllChatsWithMessages(withNewMessageOnly),
      withNewMessageOnly
    );
  }

  /**
   * Retrieve all groups
   * Deprecated in favor of {@link listChats}
   *
   * @category Group
   * @returns array of groups
   * @deprecated Deprecated in favor of listChats.
   */
  public async getAllGroups(withNewMessagesOnly = false): Promise<Chat[]> {
    this.logger.warn(
      'Deprecated: This function [getAllGroups] is deprecated in favor of the listChats function. Please update your code accordingly.'
    );
    return await evaluateAndReturn(
      this.page,
      async ({ withNewMessagesOnly }) => {
        const chats = await WPP.chat.list({
          onlyGroups: true,
          onlyWithUnreadMessage: withNewMessagesOnly,
        });

        const groups = await Promise.all(
          chats.map((c) => WPP.group.ensureGroup(c.id))
        );

        return groups.map((g) => WAPI._serializeChatObj(g));
      },
      { withNewMessagesOnly }
    );
  }

  /**
   * Retrieve all broadcast list
   * @category Group
   * @returns array of broadcast list
   */
  public async getAllBroadcastList() {
    const chats = await evaluateAndReturn(this.page, () => WAPI.getAllChats());
    return chats.filter(
      (chat) => chat.isBroadcast && chat.id._serialized !== 'status@broadcast'
    );
  }

  /**
   * Retrieves contact detail object of given contact id
   * @category Contact
   * @param contactId
   * @returns contact details as promise
   */
  public async getContact(contactId: string) {
    return evaluateAndReturn(
      this.page,
      (contactId) => WAPI.getContact(contactId),
      contactId
    );
  }

  /**
   * Retrieves all contacts
   * @category Contact
   * @returns array of [Contact]
   */
  public async getAllContacts() {
    return await evaluateAndReturn(this.page, () => WAPI.getAllContacts());
  }

  /**
   * Retrieves chat object of given contact id
   * @category Chat
   * @param contactId
   * @returns chat details as promise
   */
  public async getChatById(contactId: string | Wid): Promise<Chat> {
    return evaluateAndReturn(
      this.page,
      (contactId) => WAPI.getChatById(contactId),
      contactId
    );
  }

  /**
   * Retrieves chat object of given contact id
   * @category Chat
   * @param contactId
   * @returns chat details as promise
   * @deprecated
   */
  public async getChat(contactId: string | Wid) {
    return this.getChatById(contactId);
  }

  /**
   * Retorna dados da imagem do contato
   * @category Contact
   * @param chatId Chat id
   * @returns url of the chat picture or undefined if there is no picture for the chat.
   */
  public async getProfilePicFromServer(
    chatId: string
  ): Promise<ProfilePicThumbObj> {
    return evaluateAndReturn(
      this.page,
      (chatId) => WAPI._profilePicfunc(chatId),
      chatId
    );
  }

  /**
   * Load more messages in chat object from server. Use this in a while loop
   * Depreciado em favor de {@link getMessages}
   *
   * @deprecated Depreciado em favor de getMessages
   * @category Chat
   * @param contactId
   * @returns contact details as promise
   */
  public async loadEarlierMessages(contactId: string) {
    return evaluateAndReturn(
      this.page,
      (contactId) => WAPI.loadEarlierMessages(contactId),
      contactId
    );
  }

  /**
   * Retrieves status of given contact
   * @category Contact
   * @param contactId
   */
  public async getStatus(contactId: string): Promise<ContactStatus> {
    return await evaluateAndReturn(
      this.page,
      async (contactId) => {
        const status = await WPP.contact.getStatus(contactId);

        return {
          id: contactId,
          status: (status as any)?.status || status,
        };
      },
      contactId
    );
  }

  /**
   * Checks if a number is a valid whatsapp number
   *
   * Deprecated in favor of checkNumberStatus
   * @deprecated Deprecated in favor of checkNumberStatus
   * @category Contact
   * @param contactId, you need to include the @c.us at the end.
   * @returns contact details as promise
   */
  public async getNumberProfile(contactId: string) {
    this.log(
      'warn',
      'The getNumberProfile function is deprecated, please use checkNumberStatus'
    );
    return evaluateAndReturn(
      this.page,
      (contactId) => WAPI.getNumberProfile(contactId),
      contactId
    );
  }

  /**
   * Retrieves all undread Messages
   * @category Chat
   * @param includeMe
   * @param includeNotifications
   * @param useUnreadCount
   * @returns any
   * @deprecated
   */
  public async getUnreadMessages(
    includeMe: boolean,
    includeNotifications: boolean,
    useUnreadCount: boolean
  ) {
    return await evaluateAndReturn(
      this.page,
      ({ includeMe, includeNotifications, useUnreadCount }) =>
        WAPI.getUnreadMessages(includeMe, includeNotifications, useUnreadCount),
      { includeMe, includeNotifications, useUnreadCount }
    );
  }

  /**
   * Retrieves all unread messages (where ack is -1)
   * @category Chat
   * @returns list of messages
   */
  public async getAllUnreadMessages() {
    return evaluateAndReturn(this.page, () => WAPI.getAllUnreadMessages());
  }

  /**
   * Retrieves all new messages (where isNewMsg is true)
   * @category Chat
   * @returns List of messages
   * @deprecated Use getAllUnreadMessages
   */
  public async getAllNewMessages() {
    return await evaluateAndReturn(this.page, () => WAPI.getAllNewMessages());
  }

  /**
   * Retrieves all messages already loaded in a chat
   * For loading every message use loadAndGetAllMessagesInChat
   * Depreciado em favor de {@link getMessages}
   *
   * @deprecated Depreciado em favor de getMessages
   *
   * @category Chat
   * @param chatId, the chat to get the messages from
   * @param includeMe, include my own messages? boolean
   * @param includeNotifications
   * @returns any
   */
  public async getAllMessagesInChat(
    chatId: string,
    includeMe: boolean,
    includeNotifications: boolean
  ) {
    return await evaluateAndReturn(
      this.page,
      ({ chatId, includeMe, includeNotifications }) =>
        WAPI.getAllMessagesInChat(chatId, includeMe, includeNotifications),
      { chatId, includeMe, includeNotifications }
    );
  }

  /**
   * Loads and Retrieves all Messages in a chat
   * Depreciado em favor de {@link getMessages}
   *
   * @deprecated Depreciado em favor de getMessages
   * @category Chat
   * @param chatId, the chat to get the messages from
   * @param includeMe, include my own messages? boolean
   * @param includeNotifications
   * @returns any
   */
  public async loadAndGetAllMessagesInChat(
    chatId: string,
    includeMe = false,
    includeNotifications = false
  ) {
    return await evaluateAndReturn(
      this.page,
      ({ chatId, includeMe, includeNotifications }) =>
        WAPI.loadAndGetAllMessagesInChat(
          chatId,
          includeMe,
          includeNotifications
        ),
      { chatId, includeMe, includeNotifications }
    );
  }

  /**
   * Checks if a CHAT contact is online.
   * @category Chat
   * @param chatId chat id: xxxxx@c.us
   */
  public async getChatIsOnline(chatId: string): Promise<boolean> {
    return await evaluateAndReturn(
      this.page,
      (chatId: string) => WAPI.getChatIsOnline(chatId),
      chatId
    );
  }

  /**
   * Retrieves the last seen of a CHAT.
   * @category Chat
   * @param chatId chat id: xxxxx@c.us
   */
  public async getLastSeen(chatId: string): Promise<number | boolean> {
    return await evaluateAndReturn(
      this.page,
      (chatId: string) => WAPI.getLastSeen(chatId),
      chatId
    );
  }

  /**
   * Get the platform message from message ID
   *
   * The platform can be:
   * android
   * iphone
   * web
   * unknown
   * @category Chat
   * @param chatId chat id: xxxxx@c.us
   */
  public async getPlatformFromMessage(msgId: string): Promise<string> {
    return await evaluateAndReturn(
      this.page,
      (msgId: string) => WPP.chat.getPlatformFromMessage(msgId),
      msgId
    );
  }

  /**
   * Get the reactions of a message
   *
   * @category Chat
   */
  public async getReactions(msgId: string): Promise<{
    reactionByMe: {
      id: any;
      orphan: number;
      msgId: any;
      reactionText: string;
      read: boolean;
      senderUserJid: string;
      timestamp: number;
    };
    reactions: {
      aggregateEmoji: string;
      hasReactionByMe: boolean;
      senders: {
        id: any;
        orphan: number;
        msgId: any;
        reactionText: string;
        read: boolean;
        senderUserJid: string;
        timestamp: number;
      }[];
    }[];
  }> {
    return await evaluateAndReturn(
      this.page,
      (msgId: string) => WPP.chat.getReactions(msgId),
      msgId
    );
  }

  /**
   * Get the votes of a poll message
   *
   * @category Chat
   */
  public async getVotes(msgId: string): Promise<{
    msgId: any;
    chatId: Wid;
    votes: {
      selectedOptions: number[];
      timestamp: number;
      sender: Wid;
    }[];
  }> {
    return await evaluateAndReturn(
      this.page,
      (msgId: string) => WPP.chat.getVotes(msgId),
      msgId
    );
  }

  /**
   * Get the max number of participants for a group
   *
   * @category Group
   */
  public async getGroupSizeLimit(): Promise<number> {
    return await evaluateAndReturn(this.page, () =>
      WPP.group.getGroupSizeLimit()
    );
  }

  /**
   * Get info of your sended order
   *
   * @example
   * ```javascript
   * const orderInfo = await client.getOrder('<orderId>');
   * ```
   * @category Order
   * @return Your order
   */
  public async getOrder(msgId: string) {
    return evaluateAndReturn(this.page, (msgId) => WPP.order.get(msgId), msgId);
  }

  /**
   * Get all commons groups for the contact
   *
   * @example
   * ```javascript
   * const groups_ids = await client.getCommonGroups('[number]@c.us');
   * ```
   *
   * @category Group
   * @param groupId Group ID ('000000-000000@g.us')
   * @returns Promise
   */
  public async getCommonGroups(wid: string) {
    return await evaluateAndReturn(
      this.page,
      ({ wid }) => WPP.contact.getCommonGroups(wid),
      { wid }
    );
  }

  /**
   * Get LID/PhoneNumber mapping and Contact information
   *
   * @example
   * ```javascript
   * const info = await client.getPnLidEntry('[number]@c.us');
   * const info = await client.getPnLidEntry('[number]@lid');
   * ```
   *
   * @category Contact
   * @param phoneOrLid Contact ID (phone number or LID)
   * @returns Promise with lid, phoneNumber and contact information
   */
  public async getPnLidEntry(phoneOrLid: string) {
    return await evaluateAndReturn(
      this.page,
      (phoneOrLid) => WPP.contact.getPnLidEntry(phoneOrLid),
      phoneOrLid
    );
  }

  /**
   * Get messages from IndexedDB 'model-storage' database starting from a specific rowId
   *
   * This function queries the IndexedDB database directly using the rowId index,
   * retrieving messages with rowId greater than the specified value.
   * It's useful for pagination or fetching messages in chronological order.
   *
   * @example
   * ```javascript
   * // Get 1000 messages after rowId 999960610
   * const messages = await client.getMessagesFromRowId({ minRowId: 999960610 });
   *
   * // Get 500 messages after rowId 999960610
   * const messages = await client.getMessagesFromRowId({
   *   minRowId: 999960610,
   *   limit: 500
   * });
   *
   * // Get all available messages after rowId (use with caution)
   * const messages = await client.getMessagesFromRowId({
   *   minRowId: 999960610,
   *   limit: -1
   * });
   * ```
   * @category Chat
   * @param options Options for fetching messages
   * @returns Promise that resolves to an array of message objects from IndexedDB
   */
  public async getMessagesFromRowId(
    input: GetMessagesFromRowIdOptions
  ): Promise<any[]> {
    return await evaluateAndReturn(
      this.page,
      (options) => WPP.indexdb.getMessagesFromRowId(options),
      input
    );
  }
}