-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
whatsapp.ts
200 lines (183 loc) · 6.6 KB
/
whatsapp.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import makeWASocket, {DisconnectReason, useMultiFileAuthState} from "@whiskeysockets/baileys";
import pino from "pino";
import path from "path";
import * as fs from "fs";
import {Boom} from "@hapi/boom";
import signale from "signale";
import * as os from "os";
import mime from 'mime';
export const globalOptions = {
logLevel: 'silent'
}
export const mudslideFooter = '\u2B50 Please star Mudslide on GitHub! https://github.com/robvanderleek/mudslide';
export function getAuthStateCacheFolderLocation() {
if (process.env.MUDSLIDE_CACHE_FOLDER) {
return process.env.MUDSLIDE_CACHE_FOLDER;
} else {
const homedir = os.homedir();
if (process.platform === 'win32') {
return path.join(homedir, 'AppData', 'Local', 'mudslide', 'Data');
} else {
return path.join(homedir, '.local', 'share', 'mudslide');
}
}
}
function clearCacheFolder() {
const folder = initAuthStateCacheFolder();
fs.readdirSync(folder).forEach(f => f.endsWith(".json") && fs.rmSync(`${folder}/${f}`));
}
function initAuthStateCacheFolder() {
const folderLocation = getAuthStateCacheFolderLocation();
if (!fs.existsSync(folderLocation)) {
fs.mkdirSync(folderLocation, {recursive: true});
signale.log(`Created mudslide cache folder: ${folderLocation}`);
}
return folderLocation;
}
export async function initWASocket(printQR = true, message: string | undefined = undefined) {
const {state, saveCreds} = await useMultiFileAuthState(initAuthStateCacheFolder());
const os = process.platform === 'darwin' ? 'macOS' : process.platform === 'win32' ? 'Windows' : 'Linux';
const socket = makeWASocket({
logger: pino({level: globalOptions.logLevel}),
auth: state,
printQRInTerminal: printQR,
browser: [os, 'Chrome', '10.15.0'],
getMessage: async _ => {
return {
conversation: message
}
},
markOnlineOnConnect: false
});
socket.ev.on('creds.update', async () => await saveCreds());
return socket;
}
export function terminate(socket: any, waitSeconds = 0) {
if (waitSeconds > 0) {
signale.await(`Waiting ${waitSeconds} second(s) for successful delivery...`);
}
setTimeout(() => {
socket.end(undefined);
socket.ws.close();
process.exit();
}, waitSeconds * 1000);
console.info(mudslideFooter);
}
export function checkLoggedIn() {
if (!fs.existsSync(path.join(initAuthStateCacheFolder(), 'creds.json'))) {
signale.error('Not logged in');
process.exit(1);
}
}
export function checkValidFile(path: string) {
if (!(fs.existsSync(path) && fs.lstatSync(path).isFile())) {
signale.error(`Could not read image file: ${path}`);
process.exit(1);
}
}
export function parseGeoLocation(latitude: string, longitude: string): Array<number> {
const latitudeFloat = parseFloat(latitude);
const longitudeFloat = parseFloat(longitude);
if (isNaN(latitudeFloat) || isNaN(longitudeFloat)) {
signale.error(`Invalid geo location: ${latitude}, ${longitude}`);
process.exit(1);
}
return [parseFloat(latitudeFloat.toFixed(7)), parseFloat(longitudeFloat.toFixed(7))];
}
export async function waitForKey(message: string) {
signale.pause(message);
process.stdin.setRawMode(true);
return new Promise(resolve => process.stdin.once('data', () => {
process.stdin.setRawMode(false);
resolve(undefined);
}));
}
export async function login(waitForWA = false) {
const socket = await initWASocket();
socket.ev.on('connection.update', async (update) => {
const {connection, lastDisconnect} = update
if (connection === 'close') {
if ((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
await login(true);
} else {
return;
}
} else if (connection === 'open') {
signale.success('Logged in');
if (waitForWA) {
await waitForKey("Wait until WhatsApp finishes connecting, then press any key to exit");
terminate(socket);
} else {
terminate(socket);
}
}
});
}
export async function logout() {
checkLoggedIn();
const socket = await initWASocket(false);
socket.ev.on('connection.update', async (update) => {
const {connection} = update
if (update.connection === undefined && update.qr) {
clearCacheFolder();
signale.success(`Logged out`);
terminate(socket);
}
if (connection === 'open') {
await socket.logout();
clearCacheFolder();
signale.success(`Logged out`);
terminate(socket);
}
});
process.on('exit', clearCacheFolder);
}
export async function getWhatsAppId(socket: any, recipient: string) {
if (recipient.startsWith('+')) {
recipient = recipient.substring(1);
}
if (recipient.endsWith('@s.whatsapp.net') || recipient.endsWith('@g.us')) {
return recipient;
} else if (recipient === 'me') {
const user = await socket.user;
if (user) {
const phoneNumber = user.id.substring(0, user.id.indexOf(':'));
return `${phoneNumber}@s.whatsapp.net`;
}
}
return `${recipient}@s.whatsapp.net`;
}
export async function sendImageHelper(socket: any, whatsappId: string, filePath: string, options: {
caption: string | undefined
}) {
const payload = {image: fs.readFileSync(filePath), caption: handleNewlines(options.caption)}
await socket.sendMessage(whatsappId, payload);
signale.success('Done');
terminate(socket, 3);
}
export async function sendFileHelper(socket: any, whatsappId: string, filePath: string,
options: { caption: string | undefined, type: 'audio' | 'video' | 'document' }) {
const payload: any = {
mimetype: mime.getType(filePath),
caption: handleNewlines(options.caption)
};
switch (options.type) {
case "audio":
payload['audio'] = fs.readFileSync(filePath);
break;
case "video":
payload['video'] = fs.readFileSync(filePath);
break;
default:
payload['document'] = fs.readFileSync(filePath);
payload['fileName'] = path.basename(filePath)
}
await socket.sendMessage(whatsappId, payload);
signale.success('Done');
terminate(socket, 3);
}
export function handleNewlines(s?: string): string | undefined {
if (s) {
return s.replace(/\\n/g, '\n');
}
}