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 14:42:49 +00:00
|
|
|
import makeWASocket, {
|
|
|
|
|
DisconnectReason,
|
|
|
|
|
proto,
|
|
|
|
|
downloadContentFromMessage,
|
|
|
|
|
MediaType,
|
|
|
|
|
AnyMessageContent,
|
|
|
|
|
WAProto,
|
2023-03-13 15:01:40 +00:00
|
|
|
UserFacingSocketConfig,
|
2023-03-13 14:42:49 +00:00
|
|
|
MiscMessageGenerationOptions,
|
|
|
|
|
} from "@adiwajshing/baileys";
|
2023-02-13 12:41:30 +00:00
|
|
|
import workerUtils from "../../worker-utils";
|
|
|
|
|
import { useDatabaseAuthState } from "../lib/whatsapp-key-store";
|
|
|
|
|
|
|
|
|
|
export type AuthCompleteCallback = (error?: string) => void;
|
|
|
|
|
|
2023-03-13 14:42:49 +00:00
|
|
|
export type Connection = {
|
|
|
|
|
end: (error: Error | undefined) => void;
|
|
|
|
|
sendMessage: (
|
|
|
|
|
jid: string,
|
|
|
|
|
content: AnyMessageContent,
|
|
|
|
|
options?: MiscMessageGenerationOptions
|
|
|
|
|
) => Promise<WAProto.WebMessageInfo | undefined>;
|
|
|
|
|
};
|
|
|
|
|
|
2023-02-13 12:41:30 +00:00
|
|
|
export default class WhatsappService extends Service {
|
2023-03-13 14:42:49 +00:00
|
|
|
connections: { [key: string]: Connection } = {};
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async initialize(): Promise<void> {
|
|
|
|
|
this.updateConnections();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async teardown(): Promise<void> {
|
|
|
|
|
this.resetConnections();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async sleep(ms: number): Promise<void> {
|
2023-03-13 14:42:49 +00:00
|
|
|
console.log(`pausing ${ms}`);
|
2023-03-13 15:01:40 +00:00
|
|
|
// eslint-disable-next-line no-new
|
|
|
|
|
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:01:40 +00:00
|
|
|
connection.end(undefined);
|
2023-02-13 12:41:30 +00:00
|
|
|
} catch (error) {
|
|
|
|
|
console.log(error);
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-03-13 14:42:49 +00:00
|
|
|
|
2023-02-13 12:41:30 +00:00
|
|
|
this.connections = {};
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 14:42:49 +00:00
|
|
|
private createConnection(
|
|
|
|
|
bot: Bot,
|
|
|
|
|
server: Server,
|
2023-03-13 15:01:40 +00:00
|
|
|
options: Omit<UserFacingSocketConfig, "auth">,
|
|
|
|
|
authCompleteCallback?: () => void
|
2023-03-13 14:42:49 +00:00
|
|
|
) {
|
|
|
|
|
const { state, saveState } = useDatabaseAuthState(bot, server);
|
2023-02-13 12:41:30 +00:00
|
|
|
const connection = makeWASocket({ ...options, auth: state });
|
|
|
|
|
let pause = 5000;
|
2023-03-13 14:42:49 +00:00
|
|
|
connection.ev.on("connection.update", async (update) => {
|
2023-03-13 15:01:40 +00:00
|
|
|
console.log(`Connection updated ${JSON.stringify(update, undefined, 2)}`);
|
2023-03-13 14:42:49 +00:00
|
|
|
const {
|
|
|
|
|
connection: connectionState,
|
|
|
|
|
lastDisconnect,
|
|
|
|
|
qr,
|
|
|
|
|
isNewLogin,
|
|
|
|
|
} = update;
|
2023-02-13 12:41:30 +00:00
|
|
|
if (qr) {
|
2023-03-13 14:42:49 +00:00
|
|
|
console.log("got qr code");
|
2023-02-13 12:41:30 +00:00
|
|
|
await this.server.db().whatsappBots.updateQR(bot, qr);
|
|
|
|
|
} else if (isNewLogin) {
|
2023-03-13 14:42:49 +00:00
|
|
|
console.log("got new login");
|
|
|
|
|
} else if (connectionState === "open") {
|
|
|
|
|
console.log("opened connection");
|
2023-02-13 12:41:30 +00:00
|
|
|
} else if (connectionState === "close") {
|
2023-03-13 14:42:49 +00:00
|
|
|
console.log("connection closed due to", lastDisconnect.error);
|
2023-03-13 15:01:40 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2023-03-13 14:42:49 +00:00
|
|
|
const disconnectStatusCode = (lastDisconnect?.error as any)?.output
|
|
|
|
|
?.statusCode;
|
2023-02-13 12:41:30 +00:00
|
|
|
if (disconnectStatusCode === DisconnectReason.restartRequired) {
|
2023-03-13 14:42:49 +00:00
|
|
|
console.log("reconnecting after got new login");
|
2023-02-13 12:41:30 +00:00
|
|
|
const updatedBot = await this.findById(bot.id);
|
2023-03-13 14:42:49 +00:00
|
|
|
this.createConnection(updatedBot, server, options);
|
|
|
|
|
authCompleteCallback();
|
2023-02-13 12:41:30 +00:00
|
|
|
} else if (disconnectStatusCode !== DisconnectReason.loggedOut) {
|
2023-03-13 14:42:49 +00:00
|
|
|
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
|
|
|
});
|
|
|
|
|
|
|
|
|
|
connection.ev.process(async (events) => {
|
|
|
|
|
if (events["messaging-history.set"]) {
|
|
|
|
|
const { chats, contacts, messages, isLatest } =
|
|
|
|
|
events["messaging-history.set"];
|
|
|
|
|
console.log(
|
|
|
|
|
`recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest})`
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
});
|
2023-02-13 12:41:30 +00:00
|
|
|
|
2023-03-13 14:42:49 +00:00
|
|
|
connection.ev.on("messages.upsert", async (m) => {
|
|
|
|
|
console.log("messages upsert");
|
2023-02-13 12:41:30 +00:00
|
|
|
const { messages } = m;
|
|
|
|
|
if (messages) {
|
|
|
|
|
await this.queueUnreadMessages(bot, messages);
|
|
|
|
|
}
|
2023-03-13 14:42:49 +00:00
|
|
|
});
|
|
|
|
|
connection.ev.on("messages.update", (m) => console.log(m));
|
|
|
|
|
connection.ev.on("message-receipt.update", (m) => console.log(m));
|
|
|
|
|
connection.ev.on("presence.update", (m) => console.log(m));
|
|
|
|
|
connection.ev.on("chats.update", (m) => console.log(m));
|
|
|
|
|
connection.ev.on("contacts.upsert", (m) => console.log(m));
|
|
|
|
|
connection.ev.on("creds.update", saveState);
|
2023-02-13 12:41:30 +00:00
|
|
|
|
|
|
|
|
this.connections[bot.id] = connection;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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 14:42:49 +00:00
|
|
|
this.createConnection(bot, this.server, {
|
|
|
|
|
browser: WhatsappService.browserDescription,
|
|
|
|
|
printQRInTerminal: false,
|
|
|
|
|
version: [2, 2204, 13],
|
|
|
|
|
});
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:01:40 +00:00
|
|
|
private async queueMessage(bot: Bot, webMessageInfo: proto.IWebMessageInfo) {
|
2023-02-13 12:41:30 +00:00
|
|
|
const { key, message, messageTimestamp } = webMessageInfo;
|
|
|
|
|
const { remoteJid } = key;
|
|
|
|
|
|
2023-03-13 15:01:40 +00:00
|
|
|
const {fromMe, id: keyId} = key;
|
|
|
|
|
|
|
|
|
|
if (!fromMe && message && remoteJid !== "status@broadcast") {
|
|
|
|
|
const { audioMessage, documentMessage, imageMessage, videoMessage } =
|
|
|
|
|
message;
|
2023-02-13 12:41:30 +00:00
|
|
|
const isMediaMessage =
|
2023-03-13 15:01:40 +00:00
|
|
|
audioMessage || documentMessage || imageMessage || videoMessage;
|
2023-02-13 12:41:30 +00:00
|
|
|
|
2023-03-13 14:42:49 +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:01:40 +00:00
|
|
|
if (audioMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "audio";
|
2023-03-13 15:01:40 +00:00
|
|
|
filename = keyId + "." + audioMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = audioMessage.mimetype;
|
|
|
|
|
} else if (documentMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "document";
|
2023-03-13 15:01:40 +00:00
|
|
|
filename = documentMessage.fileName;
|
|
|
|
|
mimetype = documentMessage.mimetype;
|
|
|
|
|
} else if (imageMessage) {
|
2023-02-13 12:41:30 +00:00
|
|
|
messageType = "image";
|
2023-03-13 15:01:40 +00:00
|
|
|
filename = keyId + "." + imageMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = imageMessage.mimetype;
|
|
|
|
|
} else if (videoMessage) {
|
2023-03-13 14:42:49 +00:00
|
|
|
messageType = "video";
|
2023-03-13 15:01:40 +00:00
|
|
|
filename = keyId + "." + videoMessage.mimetype.split("/").pop();
|
|
|
|
|
mimetype = videoMessage.mimetype;
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
2023-03-13 14:42:49 +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 14:42:49 +00:00
|
|
|
buffer = Buffer.concat([buffer, chunk]);
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
2023-03-13 14:42:49 +00:00
|
|
|
|
2023-02-13 12:41:30 +00:00
|
|
|
attachment = buffer.toString("base64");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (messageContent || attachment) {
|
|
|
|
|
const receivedMessage = {
|
2023-03-13 15:01:40 +00:00
|
|
|
waMessageId: keyId,
|
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:01:40 +00:00
|
|
|
jobKey: keyId,
|
2023-02-13 12:41:30 +00:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:01:40 +00:00
|
|
|
private async queueUnreadMessages(bot: Bot, messages: proto.IWebMessageInfo[]) {
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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 14:42:49 +00:00
|
|
|
await this.createConnection(
|
|
|
|
|
bot,
|
|
|
|
|
this.server,
|
|
|
|
|
{ version: [2, 2204, 13] },
|
|
|
|
|
callback
|
|
|
|
|
);
|
2023-02-13 12:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async send(bot: Bot, phoneNumber: string, message: string): Promise<void> {
|
|
|
|
|
const connection = this.connections[bot.id];
|
|
|
|
|
const recipient = `${phoneNumber.replace(/\D+/g, "")}@s.whatsapp.net`;
|
|
|
|
|
await connection.sendMessage(recipient, { text: message });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async receiveSince(bot: Bot, lastReceivedDate: Date): Promise<void> {
|
|
|
|
|
const connection = this.connections[bot.id];
|
|
|
|
|
const messages = await connection.messagesReceivedAfter(
|
|
|
|
|
lastReceivedDate,
|
|
|
|
|
false
|
|
|
|
|
);
|
|
|
|
|
for (const message of messages) {
|
|
|
|
|
this.queueMessage(bot, message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-13 15:01:40 +00:00
|
|
|
async receive(bot: Bot, _lastReceivedDate: Date): Promise<proto.IWebMessageInfo[]> {
|
2023-02-13 12:41:30 +00:00
|
|
|
const connection = this.connections[bot.id];
|
|
|
|
|
// const messages = await connection.messagesReceivedAfter(
|
|
|
|
|
// lastReceivedDate,
|
|
|
|
|
// false
|
|
|
|
|
// );
|
|
|
|
|
|
|
|
|
|
const messages = await connection.loadAllUnreadMessages();
|
|
|
|
|
return messages;
|
|
|
|
|
}
|
|
|
|
|
}
|