Skip to content

Commit

Permalink
[core] Add dedicated POST /api/{session}/groups/refresh endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
devlikepro committed Dec 9, 2024
1 parent 767d1bb commit 56009e4
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 41 deletions.
12 changes: 9 additions & 3 deletions src/api/groups.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { WhatsappSession } from '../core/abc/session.abc';
import {
CreateGroupRequest,
DescriptionRequest,
GetGroupsParams,
GroupsPaginationParams,
ParticipantsRequest,
SettingsSecurityChangeInfo,
Expand Down Expand Up @@ -52,9 +51,16 @@ export class GroupsController {
getGroups(
@WorkingSessionParam session: WhatsappSession,
@Query() pagination: GroupsPaginationParams,
@Query() params: GetGroupsParams,
) {
return session.getGroups(pagination, params.refresh);
return session.getGroups(pagination);
}

@Post('refresh')
@SessionApiParam
@ApiOperation({ summary: 'Refresh groups from the server.' })
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
async refreshGroups(@WorkingSessionParam session: WhatsappSession) {
return { success: await session.refreshGroups() };
}

@Get(':id')
Expand Down
6 changes: 5 additions & 1 deletion src/core/abc/session.abc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,11 @@ export abstract class WhatsappSession {
throw new NotImplementedByEngineError();
}

public getGroups(pagination: PaginationParams, refresh: boolean) {
public getGroups(pagination: PaginationParams) {
throw new NotImplementedByEngineError();
}

public refreshGroups(): Promise<boolean> {
throw new NotImplementedByEngineError();
}

Expand Down
12 changes: 9 additions & 3 deletions src/core/engines/noweb/session.noweb.core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1084,14 +1084,20 @@ export class WhatsappSessionNoWebCore extends WhatsappSession {
return this.sock.groupCreate(request.name, participants);
}

public async getGroups(pagination: PaginationParams, refresh: boolean) {
const groups = await this.store.getGroups(pagination, refresh);
public async getGroups(pagination: PaginationParams) {
const groups = await this.store.getGroups(pagination);
// return {id: group} mapping for backward compatability
return lodash.keyBy(groups, 'id');
}

public async refreshGroups(): Promise<boolean> {
this.store.resetGroupsCache();
await this.store.getGroups({});
return true;
}

public async getGroup(id) {
const groups = await this.getGroups({}, false);
const groups = await this.getGroups({});
return groups[id];
}

Expand Down
7 changes: 3 additions & 4 deletions src/core/engines/noweb/store/INowebStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ export interface INowebStore {

getChatLabels(chatId: string): Promise<Label[]>;

getGroups(
pagination: PaginationParams,
refresh: boolean,
): Promise<GroupMetadata[]>;
getGroups(pagination: PaginationParams): Promise<GroupMetadata[]>;

resetGroupsCache(): void;
}
9 changes: 5 additions & 4 deletions src/core/engines/noweb/store/NowebInMemoryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,14 @@ export class NowebInMemoryStore implements INowebStore {
throw new BadRequestException(this.errorMessage);
}

async getGroups(
pagination: PaginationParams,
refresh: boolean,
): Promise<GroupMetadata[]> {
async getGroups(pagination: PaginationParams): Promise<GroupMetadata[]> {
const response = await this.socket?.groupFetchAllParticipating();
const groups = Object.values(response);
const paginator = new PaginatorInMemory(pagination);
return paginator.apply(groups);
}

resetGroupsCache() {
return;
}
}
23 changes: 10 additions & 13 deletions src/core/engines/noweb/store/NowebPersistentStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class NowebPersistentStore implements INowebStore {
});

private lastTimeGroupUpdate: Date = new Date(0);
private lastTimeGroupFetch: Date = new Date(0);
private GROUP_METADATA_CACHE_TIME = 24 * HOUR;

constructor(
Expand Down Expand Up @@ -453,15 +454,14 @@ export class NowebPersistentStore implements INowebStore {
return this.chatRepo.getAllWithMessages(pagination);
}

private shouldUpdateGroup(): boolean {
const timePassed =
new Date().getTime() - this.lastTimeGroupUpdate.getTime();
private shouldFetchGroup(): boolean {
const timePassed = new Date().getTime() - this.lastTimeGroupFetch.getTime();
return timePassed > this.GROUP_METADATA_CACHE_TIME;
}

private async fetchGroups() {
await this.groupsFetchLock.acquire('groups-fetch', async () => {
if (!this.shouldUpdateGroup()) {
if (!this.shouldFetchGroup()) {
// Update has been done by another request
return;
}
Expand All @@ -474,19 +474,16 @@ export class NowebPersistentStore implements INowebStore {
100,
5_000,
);
this.lastTimeGroupFetch = new Date();
});
}

async getGroups(
pagination: PaginationParams,
refresh: boolean,
): Promise<GroupMetadata[]> {
if (refresh) {
// Reset the last update time
this.lastTimeGroupUpdate = new Date(0);
}
resetGroupsCache() {
this.lastTimeGroupFetch = new Date(0);
}

if (this.shouldUpdateGroup()) {
async getGroups(pagination: PaginationParams): Promise<GroupMetadata[]> {
if (this.shouldFetchGroup()) {
await this.fetchGroups();
}
return this.groupRepo.getAll(pagination);
Expand Down
6 changes: 5 additions & 1 deletion src/core/engines/webjs/session.webjs.core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -790,13 +790,17 @@ export class WhatsappSessionWebJSCore extends WhatsappSession {
return groupChat.setMessagesAdminsOnly(value);
}

public async getGroups(pagination: PaginationParams, refresh: boolean) {
public async getGroups(pagination: PaginationParams) {
const chats = await this.whatsapp.getChats();
const groups = lodash.filter(chats, (chat) => chat.isGroup);
const paginator = new PaginatorInMemory(pagination);
return paginator.apply(groups);
}

public async refreshGroups(): Promise<boolean> {
return true;
}

public getGroup(id) {
return this.whatsapp.getChatById(id);
}
Expand Down
12 changes: 0 additions & 12 deletions src/structures/groups.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,3 @@ export class GroupsPaginationParams extends PaginationParams {
@IsEnum(GroupSortField)
sortBy?: string;
}

export class GetGroupsParams {
@ApiProperty({
description: 'Refresh the groups list and participants from the server',
example: false,
required: false,
})
@Transform(BooleanString)
@IsBoolean()
@IsOptional()
refresh: boolean = false;
}

0 comments on commit 56009e4

Please sign in to comment.