Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sendPresence #237

Merged
merged 3 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"editor.smoothScrolling": true,
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.fixAll": true
"source.fixAll.eslint": "explicit",
"source.fixAll": "explicit"
},
"prisma-smart-formatter.typescript.defaultFormatter": "esbenp.prettier-vscode",
"prisma-smart-formatter.prisma.defaultFormatter": "Prisma.prisma"
Expand Down
10 changes: 10 additions & 0 deletions src/validate/validate.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@ export const textMessageSchema: JSONSchema7 = {
required: ['textMessage', 'number'],
};

export const presenceSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
number: { ...numberDefinition },
options: { ...optionsSchema, required: ['presence', 'delay'] },
},
required: ['options', 'number'],
};

export const pollMessageSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
Expand Down
6 changes: 6 additions & 0 deletions src/whatsapp/controllers/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ProfilePictureDto,
ProfileStatusDto,
ReadMessageDto,
SendPresenceDto,
WhatsAppNumberDto,
} from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto';
Expand Down Expand Up @@ -77,6 +78,11 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchChats();
}

public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {
logger.verbose('requested sendPresence from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].sendPresence(data);
}

public async fetchPrivacySettings({ instanceName }: InstanceDto) {
logger.verbose('requested fetchPrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings();
Expand Down
19 changes: 18 additions & 1 deletion src/whatsapp/dto/chat.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { proto, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';

export class OnWhatsAppDto {
constructor(public readonly jid: string, public readonly exists: boolean, public readonly name?: string) {}
Expand Down Expand Up @@ -83,3 +83,20 @@ export class DeleteMessage {
remoteJid: string;
participant?: string;
}
export class Options {
delay?: number;
presence?: WAPresence;
}
class OptionsMessage {
options: Options;
}
export class Metadata extends OptionsMessage {
number: string;
}

export class SendPresenceDto extends Metadata {
options: {
presence: WAPresence;
delay: number;
};
}
4 changes: 4 additions & 0 deletions src/whatsapp/dto/sendMessage.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,13 @@ class PollMessage {
values: string[];
messageSecret?: Uint8Array;
}

export class SendTextDto extends Metadata {
textMessage: TextMessage;
}
export class SendPresence extends Metadata {
textMessage: TextMessage;
}

export class SendStatusDto extends Metadata {
statusMessage: StatusMessage;
Expand Down
18 changes: 18 additions & 0 deletions src/whatsapp/routers/chat.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
deleteMessageSchema,
messageUpSchema,
messageValidateSchema,
presenceSchema,
privacySettingsSchema,
profileNameSchema,
profilePictureSchema,
Expand All @@ -26,6 +27,7 @@ import {
ProfilePictureDto,
ProfileStatusDto,
ReadMessageDto,
SendPresenceDto,
WhatsAppNumberDto,
} from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto';
Expand Down Expand Up @@ -228,6 +230,22 @@ export class ChatRouter extends RouterBroker {

return res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('sendPresence'), ...guards, async (req, res) => {
logger.verbose('request received in sendPresence');
logger.verbose('request body: ');
logger.verbose(req.body);

logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<null>({
request: req,
schema: presenceSchema,
ClassRef: SendPresenceDto,
execute: (instance, data) => chatController.sendPresence(instance, data),
});

return res.status(HttpStatus.CREATED).json(response);
})
// Profile routes
.get(this.routerPath('fetchPrivacySettings'), ...guards, async (req, res) => {
logger.verbose('request received in fetchPrivacySettings');
Expand Down
33 changes: 33 additions & 0 deletions src/whatsapp/services/whatsapp.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import {
OnWhatsAppDto,
PrivacySettingDto,
ReadMessageDto,
SendPresenceDto,
WhatsAppNumberDto,
} from '../dto/chat.dto';
import {
Expand Down Expand Up @@ -2387,6 +2388,38 @@ export class WAStartupService {
return this.stateConnection;
}

public async sendPresence(data: SendPresenceDto) {
try {
const { number } = data;

this.logger.verbose(`Check if number "${number}" is WhatsApp`);
const isWA = (await this.whatsappNumber({ numbers: [number] }))?.shift();

this.logger.verbose(`Exists: "${isWA.exists}" | jid: ${isWA.jid}`);
if (!isWA.exists && !isJidGroup(isWA.jid) && !isWA.jid.includes('@broadcast')) {
throw new BadRequestException(isWA);
}

const sender = isWA.jid;

this.logger.verbose('Sending presence');
await this.client.presenceSubscribe(sender);
this.logger.verbose('Subscribing to presence');

await this.client.sendPresenceUpdate(data.options?.presence ?? 'composing', sender);
this.logger.verbose('Sending presence update: ' + data.options?.presence ?? 'composing');

await delay(data.options.delay);
this.logger.verbose('Set delay: ' + data.options.delay);

await this.client.sendPresenceUpdate('paused', sender);
this.logger.verbose('Sending presence update: paused');
} catch (error) {
this.logger.error(error);
throw new BadRequestException(error.toString());
}
}

// Send Message Controller
public async textMessage(data: SendTextDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
Expand Down