Skip to content

Commit

Permalink
feat: more options to chat listing (#1037)
Browse files Browse the repository at this point in the history
  • Loading branch information
Saifallak committed Apr 10, 2023
1 parent b5ff15a commit 48663da
Showing 1 changed file with 35 additions and 7 deletions.
42 changes: 35 additions & 7 deletions src/chat/functions/list.ts
@@ -1,5 +1,5 @@
/*!
* Copyright 2021 WPPConnect Team
* Copyright 2023 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -19,9 +19,14 @@ import {
ChatStore,
GroupMetadataStore,
LabelStore,
Wid,
} from '../../whatsapp';
import { get } from './get';

export interface ChatListOptions {
id?: Wid;
count?: number;
direction?: 'after' | 'before';
onlyGroups?: boolean;
onlyUsers?: boolean;
onlyWithUnreadMessage?: boolean;
Expand All @@ -36,6 +41,12 @@ export interface ChatListOptions {
* // All chats
* const chats = await WPP.chat.list();
*
* // Some chats
* const chats = WPP.chat.list({count: 20});
*
* // 20 chats before specific chat
* const chats = WPP.chat.list({count: 20, direction: 'before', id: '[number]@c.us'});
*
* // Only users chats
* const chats = await WPP.chat.list({onlyUsers: true});
*
Expand All @@ -57,8 +68,15 @@ export interface ChatListOptions {
export async function list(
options: ChatListOptions = {}
): Promise<ChatModel[]> {
// Setting the check to null, so it doesn't break existing codes.
const count = options.count == null ? Infinity : options.count;
const direction = options.direction === 'before' ? 'before' : 'after';

// Getting All Chats.
// IDK, why we use slice here. don't think its needed.
let models = ChatStore.getModelsArray().slice();

// Filtering Based on Options.
if (options.onlyUsers) {
models = models.filter((c) => c.isUser);
}
Expand All @@ -74,17 +92,27 @@ export async function list(
if (options.withLabels) {
const ids = options.withLabels.map((value) => {
const label = LabelStore.findFirst((l) => l.name === value);

if (label) {
return label.id;
}

return value;
return label ? label.id : value;
});

models = models.filter((c) => c.labels?.some((id) => ids.includes(id)));
}

// Getting The Chat to start from.
// Searching for chat (index) here, so it gets applied after all filtering.
const indexChat = options?.id ? get(options.id) : null;
const startIndex = indexChat ? models.indexOf(indexChat as any) : 0;

if (direction === 'before') {
const fixStartIndex = startIndex - count < 0 ? 0 : startIndex - count;
const fixEndIndex =
fixStartIndex + count >= startIndex ? startIndex : fixStartIndex + count;
models = models.slice(fixStartIndex, fixEndIndex);
} else {
models = models.slice(startIndex, startIndex + count);
}

// Attaching Group Metadata on Found Chats.
for (const chat of models) {
if (chat.isGroup) {
await GroupMetadataStore.find(chat.id);
Expand Down

0 comments on commit 48663da

Please sign in to comment.