2023-03-13 15:53:21 +00:00
|
|
|
/* eslint-disable unicorn/no-abusive-eslint-disable */
|
|
|
|
|
/* eslint-disable */
|
2023-02-13 12:41:30 +00:00
|
|
|
import { Server } from "@hapi/hapi";
|
|
|
|
|
import { Service } from "@hapipal/schmervice";
|
2023-03-13 11:01:28 +00:00
|
|
|
import { SavedWhatsappBot as Bot } from "@digiresilience/metamigo-db";
|
2023-03-13 15:53:21 +00:00
|
|
|
import makeWASocket, { DisconnectReason, proto, downloadContentFromMessage, MediaType, fetchLatestBaileysVersion, isJidBroadcast, isJidStatusBroadcast, MessageRetryMap, useMultiFileAuthState } from "@adiwajshing/baileys";
|
|
|
|
|
import fs from "fs";
|
2023-02-13 12:41:30 +00:00
|
|
|
import workerUtils from "../../worker-utils";
|
|
|
|
|
|
|
|
|
|
export type AuthCompleteCallback = (error?: string) => void;
|
|
|
|
|
|
|
|
|
|
export default class WhatsappService extends Service {
|
2023-03-13 15:53:21 +00:00
|
|
|
connections: { [key: string]: any } = {};
|
|
|
|
|
loginConnections: { [key: string]: any } = {};
|
2023-02-13 12:41:30 +00:00
|
|
|
|
|
|
|
|
static browserDescription: [string, string, string] = [
|
|
|
|
|
"Metamigo",
|
|
|
|
|
"Chrome",
|
|
|
|
|
"2.0",
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
constructor(server: Server, options: never) {
|
|
|
|
|
super(server, options);
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
getAuthDirectory(bot: Bot): string {
|
|
|
|
|
return `/baileys/${bot.id}`;
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-13 12:41:30 +00:00
|
|
|
async initialize(): Promise<void> {
|
|
|
|
|
this.updateConnections();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async teardown(): Promise<void> {
|
|
|
|
|
this.resetConnections();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async sleep(ms: number): Promise<void> {
|
2023-03-13 15:53:21 +00:00
|
|
|
console.log(`pausing ${ms}`)
|
|
|
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async resetConnections() {
|
|
|
|
|
for (const connection of Object.values(this.connections)) {
|
|
|
|
|
try {
|
2023-03-13 15:53:21 +00:00
|
|
|
connection.end(null)
|
2023-02-13 12:41:30 +00:00
|
|
|
} catch (error) {
|
|
|
|
|
console.log(error);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
this.connections = {};
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
|
|
|
|
|
private async createConnection(bot: Bot, server: Server, options: any, authCompleteCallback?: any) {
|
|
|
|
|
const directory = this.getAuthDirectory(bot);
|
|
|
|
|
const { state, saveCreds } = await useMultiFileAuthState(directory);
|
|
|
|
|
const msgRetryCounterMap: MessageRetryMap = {}
|
|
|
|
|
const socket = makeWASocket({
|
|
|
|
|
...options,
|
|
|
|
|
auth: state,
|
|
|
|
|
msgRetryCounterMap,
|
|
|
|
|
shouldIgnoreJid: jid => isJidBroadcast(jid) || isJidStatusBroadcast(jid),
|
|
|
|
|
});
|
2023-02-13 12:41:30 +00:00
|
|
|
let pause = 5000;
|
2023-03-13 15:53:21 +00:00
|
|
|
|
|
|
|
|
socket.ev.process(
|
|
|
|
|
async (events) => {
|
|
|
|
|
if (events['connection.update']) {
|
|
|
|
|
const update = events['connection.update']
|
|
|
|
|
const { connection: connectionState, lastDisconnect, qr, isNewLogin } = update
|
|
|
|
|
if (qr) {
|
|
|
|
|
console.log('got qr code')
|
|
|
|
|
await this.server.db().whatsappBots.updateQR(bot, qr);
|
|
|
|
|
} else if (isNewLogin) {
|
|
|
|
|
console.log("got new login")
|
|
|
|
|
await this.server.db().whatsappBots.updateVerified(bot, true);
|
|
|
|
|
} else if (connectionState === 'open') {
|
|
|
|
|
console.log('opened connection')
|
|
|
|
|
} else if (connectionState === "close") {
|
|
|
|
|
console.log('connection closed due to ', lastDisconnect.error)
|
|
|
|
|
const disconnectStatusCode = (lastDisconnect?.error as any)?.output?.statusCode
|
|
|
|
|
|
|
|
|
|
if (disconnectStatusCode === DisconnectReason.restartRequired) {
|
|
|
|
|
console.log('reconnecting after got new login')
|
|
|
|
|
const updatedBot = await this.findById(bot.id);
|
|
|
|
|
await this.createConnection(updatedBot, server, options)
|
|
|
|
|
authCompleteCallback?.()
|
|
|
|
|
} else if (disconnectStatusCode !== DisconnectReason.loggedOut) {
|
|
|
|
|
console.log('reconnecting')
|
|
|
|
|
await this.sleep(pause)
|
|
|
|
|
pause *= 2
|
|
|
|
|
this.createConnection(bot, server, options)
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
2023-03-13 14:42:49 +00:00
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
if (events['creds.update']) {
|
|
|
|
|
console.log("creds update")
|
|
|
|
|
await saveCreds()
|
|
|
|
|
}
|
2023-02-13 12:41:30 +00:00
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
if (events['messages.upsert']) {
|
|
|
|
|
console.log("messages upsert")
|
|
|
|
|
const upsert = events['messages.upsert']
|
|
|
|
|
const { messages } = upsert
|
|
|
|
|
if (messages) {
|
|
|
|
|
await this.queueUnreadMessages(bot, messages);
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
2023-03-13 15:53:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
this.connections[bot.id] = { socket, msgRetryCounterMap };
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async updateConnections() {
|
|
|
|
|
this.resetConnections();
|
|
|
|
|
|
|
|
|
|
const bots = await this.server.db().whatsappBots.findAll();
|
|
|
|
|
for await (const bot of bots) {
|
|
|
|
|
if (bot.isVerified) {
|
2023-03-13 15:53:21 +00:00
|
|
|
const { version, isLatest } = await fetchLatestBaileysVersion()
|
|
|
|
|
console.log(`using WA v${version.join('.')}, isLatest: ${isLatest}`)
|
|
|
|
|
|
|
|
|
|
await this.createConnection(
|
|
|
|
|
bot,
|
|
|
|
|
this.server,
|
|
|
|
|
{
|
|
|
|
|
browser: WhatsappService.browserDescription,
|
|
|
|
|
printQRInTerminal: false,
|
|
|
|
|
version
|
|
|
|
|
})
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
private async queueMessage(bot: Bot, webMessageInfo: proto.WebMessageInfo) {
|
|
|
|
|
const { key: { id, fromMe }, message, messageTimestamp } = webMessageInfo;
|
2023-03-13 15:01:40 +00:00
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
if (!fromMe && message) {
|
2023-02-13 12:41:30 +00:00
|
|
|
const isMediaMessage =
|
2023-03-13 15:53:21 +00:00
|
|
|
message.audioMessage ||
|
|
|
|
|
message.documentMessage ||
|
|
|
|
|
message.imageMessage ||
|
|
|
|
|
message.videoMessage;
|
2023-02-13 12:41:30 +00:00
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
const messageContent = Object.values(message)[0]
|
2023-02-13 12:41:30 +00:00
|
|
|
let messageType: MediaType;
|
|
|
|
|
let attachment: string;
|
|
|
|
|
let filename: string;
|
|
|
|
|
let mimetype: string;
|
|
|
|
|
if (isMediaMessage) {
|
2023-03-13 15:53:21 +00:00
|
|
|
if (message.audioMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "audio";
|
2023-03-13 15:53:21 +00:00
|
|
|
filename =
|
|
|
|
|
id + "." + message.audioMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = message.audioMessage.mimetype;
|
|
|
|
|
} else if (message.documentMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "document";
|
2023-03-13 15:53:21 +00:00
|
|
|
filename = message.documentMessage.fileName;
|
|
|
|
|
mimetype = message.documentMessage.mimetype;
|
|
|
|
|
} else if (message.imageMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "image";
|
2023-03-13 15:53:21 +00:00
|
|
|
filename =
|
|
|
|
|
id + "." + message.imageMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = message.imageMessage.mimetype;
|
|
|
|
|
} else if (message.videoMessage) {
|
|
|
|
|
messageType = "video"
|
|
|
|
|
filename =
|
|
|
|
|
id + "." + message.videoMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = message.videoMessage.mimetype;
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
const stream = await downloadContentFromMessage(messageContent, messageType)
|
|
|
|
|
let buffer = Buffer.from([])
|
2023-02-13 12:41:30 +00:00
|
|
|
for await (const chunk of stream) {
|
2023-03-13 15:53:21 +00:00
|
|
|
buffer = Buffer.concat([buffer, chunk])
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
attachment = buffer.toString("base64");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (messageContent || attachment) {
|
|
|
|
|
const receivedMessage = {
|
2023-03-13 15:53:21 +00:00
|
|
|
waMessageId: id,
|
2023-02-13 12:41:30 +00:00
|
|
|
waMessage: JSON.stringify(webMessageInfo),
|
|
|
|
|
waTimestamp: new Date((messageTimestamp as number) * 1000),
|
|
|
|
|
attachment,
|
|
|
|
|
filename,
|
|
|
|
|
mimetype,
|
|
|
|
|
whatsappBotId: bot.id,
|
|
|
|
|
botPhoneNumber: bot.phoneNumber,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
workerUtils.addJob("whatsapp-message", receivedMessage, {
|
2023-03-13 15:53:21 +00:00
|
|
|
jobKey: id,
|
2023-02-13 12:41:30 +00:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
private async queueUnreadMessages(bot: Bot, messages: any[]) {
|
2023-02-13 12:41:30 +00:00
|
|
|
for await (const message of messages) {
|
|
|
|
|
await this.queueMessage(bot, message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async create(
|
|
|
|
|
phoneNumber: string,
|
|
|
|
|
description: string,
|
|
|
|
|
email: string
|
|
|
|
|
): Promise<Bot> {
|
|
|
|
|
const db = this.server.db();
|
|
|
|
|
const user = await db.users.findBy({ email });
|
|
|
|
|
const row = await db.whatsappBots.insert({
|
|
|
|
|
phoneNumber,
|
|
|
|
|
description,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
});
|
|
|
|
|
return row;
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
async unverify(bot: Bot): Promise<Bot> {
|
|
|
|
|
const directory = this.getAuthDirectory(bot);
|
|
|
|
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
|
|
|
return this.server.db().whatsappBots.updateVerified(bot, false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async remove(bot: Bot): Promise<number> {
|
|
|
|
|
const directory = this.getAuthDirectory(bot);
|
|
|
|
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
|
|
|
return this.server.db().whatsappBots.remove(bot);
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-13 12:41:30 +00:00
|
|
|
async findAll(): Promise<Bot[]> {
|
|
|
|
|
return this.server.db().whatsappBots.findAll();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async findById(id: string): Promise<Bot> {
|
|
|
|
|
return this.server.db().whatsappBots.findById({ id });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async findByToken(token: string): Promise<Bot> {
|
|
|
|
|
return this.server.db().whatsappBots.findBy({ token });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async register(bot: Bot, callback: AuthCompleteCallback): Promise<void> {
|
2023-03-13 15:53:21 +00:00
|
|
|
const { version } = await fetchLatestBaileysVersion()
|
|
|
|
|
await this.createConnection(bot, this.server, { version }, callback);
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async send(bot: Bot, phoneNumber: string, message: string): Promise<void> {
|
2023-03-13 15:53:21 +00:00
|
|
|
const connection = this.connections[bot.id]?.socket;
|
2023-02-13 12:41:30 +00:00
|
|
|
const recipient = `${phoneNumber.replace(/\D+/g, "")}@s.whatsapp.net`;
|
|
|
|
|
await connection.sendMessage(recipient, { text: message });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async receiveSince(bot: Bot, lastReceivedDate: Date): Promise<void> {
|
2023-03-13 15:53:21 +00:00
|
|
|
const connection = this.connections[bot.id]?.socket;
|
2023-02-13 12:41:30 +00:00
|
|
|
const messages = await connection.messagesReceivedAfter(
|
|
|
|
|
lastReceivedDate,
|
|
|
|
|
false
|
|
|
|
|
);
|
|
|
|
|
for (const message of messages) {
|
|
|
|
|
this.queueMessage(bot, message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:53:21 +00:00
|
|
|
async receive(bot: Bot, lastReceivedDate: Date): Promise<any> {
|
|
|
|
|
const connection = this.connections[bot.id]?.socket;
|
2023-02-13 12:41:30 +00:00
|
|
|
|
|
|
|
|
const messages = await connection.loadAllUnreadMessages();
|
|
|
|
|
return messages;
|
|
|
|
|
}
|
|
|
|
|
}
|