@bhanulabs/wacli 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +221 -2
- package/bin/wacli.js +127 -0
- package/package.json +46 -4
- package/src/config.js +30 -0
- package/src/media.js +441 -0
- package/src/sixel.js +184 -0
- package/src/store.js +214 -0
- package/src/text.js +62 -0
- package/src/tui.js +1011 -0
- package/src/whatsapp.js +474 -0
package/src/whatsapp.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { EventEmitter } from 'node:events';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import makeWASocket, {
|
|
6
|
+
Browsers,
|
|
7
|
+
DisconnectReason,
|
|
8
|
+
downloadMediaMessage,
|
|
9
|
+
fetchLatestBaileysVersion,
|
|
10
|
+
proto,
|
|
11
|
+
getContentType,
|
|
12
|
+
isJidBroadcast,
|
|
13
|
+
isJidGroup,
|
|
14
|
+
isJidNewsletter,
|
|
15
|
+
isJidStatusBroadcast,
|
|
16
|
+
isLidUser,
|
|
17
|
+
isPnUser,
|
|
18
|
+
jidNormalizedUser,
|
|
19
|
+
normalizeMessageContent,
|
|
20
|
+
useMultiFileAuthState,
|
|
21
|
+
} from '@whiskeysockets/baileys';
|
|
22
|
+
import { AUTH_DIR, MEDIA_DIR, logger } from './config.js';
|
|
23
|
+
import { store } from './store.js';
|
|
24
|
+
import { buildContent } from './media.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* WhatsApp connection (Baileys, as a "linked device").
|
|
28
|
+
*
|
|
29
|
+
* Events:
|
|
30
|
+
* 'status' (status) connecting | qr | open | closed | logged_out
|
|
31
|
+
* 'qr' (qrString) show this to the user to scan
|
|
32
|
+
* 'pairing-code' (code) alternative to the QR (--pair)
|
|
33
|
+
* 'open' (me) logged in
|
|
34
|
+
* 'logged-out' session ended; a new QR will follow
|
|
35
|
+
* 'presence' (chat, state) typing… / online / offline for a subscribed chat
|
|
36
|
+
* 'sync' (percent|null) history sync progress after linking
|
|
37
|
+
*/
|
|
38
|
+
export const wa = new EventEmitter();
|
|
39
|
+
|
|
40
|
+
export const options = {
|
|
41
|
+
pairNumber: null, // digits; use a pairing code instead of the QR
|
|
42
|
+
readReceipts: true, // send blue ticks when you open a chat
|
|
43
|
+
online: true, // show as online while wacli runs (needed to see "typing…")
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const state = { status: 'starting', me: null, lastError: null };
|
|
47
|
+
|
|
48
|
+
let sock = null;
|
|
49
|
+
let generation = 0;
|
|
50
|
+
let reconnectTimer = null;
|
|
51
|
+
let pairingRequested = false;
|
|
52
|
+
|
|
53
|
+
function setStatus(status) {
|
|
54
|
+
state.status = status;
|
|
55
|
+
wa.emit('status', status);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function start() {
|
|
59
|
+
clearTimeout(reconnectTimer);
|
|
60
|
+
const myGen = ++generation;
|
|
61
|
+
setStatus('connecting');
|
|
62
|
+
|
|
63
|
+
const { state: auth, saveCreds } = await useMultiFileAuthState(AUTH_DIR);
|
|
64
|
+
let version;
|
|
65
|
+
try {
|
|
66
|
+
({ version } = await fetchLatestBaileysVersion());
|
|
67
|
+
} catch {
|
|
68
|
+
// fall back to the version bundled with Baileys
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
sock = makeWASocket({
|
|
72
|
+
auth,
|
|
73
|
+
version,
|
|
74
|
+
logger,
|
|
75
|
+
browser: Browsers.windows('wacli'),
|
|
76
|
+
markOnlineOnConnect: false,
|
|
77
|
+
syncFullHistory: false,
|
|
78
|
+
});
|
|
79
|
+
const current = sock;
|
|
80
|
+
const live = (fn) => (...args) => { if (myGen === generation) return fn(...args); };
|
|
81
|
+
|
|
82
|
+
current.ev.on('creds.update', saveCreds);
|
|
83
|
+
|
|
84
|
+
current.ev.on('connection.update', live(async ({ connection, lastDisconnect, qr }) => {
|
|
85
|
+
if (qr) {
|
|
86
|
+
if (options.pairNumber && !auth.creds.registered) {
|
|
87
|
+
if (!pairingRequested) {
|
|
88
|
+
pairingRequested = true;
|
|
89
|
+
try {
|
|
90
|
+
const code = await current.requestPairingCode(options.pairNumber);
|
|
91
|
+
setStatus('qr');
|
|
92
|
+
wa.emit('pairing-code', code.match(/.{1,4}/g).join('-'));
|
|
93
|
+
} catch (err) {
|
|
94
|
+
pairingRequested = false;
|
|
95
|
+
state.lastError = `Could not get a pairing code: ${err.message}`;
|
|
96
|
+
setStatus('qr');
|
|
97
|
+
wa.emit('qr', qr);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
setStatus('qr');
|
|
102
|
+
wa.emit('qr', qr);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (connection === 'open') {
|
|
107
|
+
state.lastError = null;
|
|
108
|
+
state.me = current.user ? { id: jidNormalizedUser(current.user.id), name: current.user.name || null } : null;
|
|
109
|
+
setStatus('open');
|
|
110
|
+
wa.emit('open', state.me);
|
|
111
|
+
if (options.online) current.sendPresenceUpdate('available').catch(() => {});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (connection === 'close') {
|
|
115
|
+
const code = lastDisconnect?.error?.output?.statusCode;
|
|
116
|
+
if (code === DisconnectReason.loggedOut) {
|
|
117
|
+
// Unlinked from the phone or with /logout: the saved session is dead.
|
|
118
|
+
clearAuth();
|
|
119
|
+
store.clear();
|
|
120
|
+
rmSync(MEDIA_DIR, { recursive: true, force: true }); // that account's photos
|
|
121
|
+
state.me = null;
|
|
122
|
+
pairingRequested = false;
|
|
123
|
+
setStatus('logged_out');
|
|
124
|
+
wa.emit('logged-out');
|
|
125
|
+
reconnectTimer = setTimeout(() => start().catch(onStartError), 1000);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
state.lastError = lastDisconnect?.error?.message || null;
|
|
129
|
+
setStatus('closed');
|
|
130
|
+
const delay = code === DisconnectReason.restartRequired ? 0 : 3000;
|
|
131
|
+
reconnectTimer = setTimeout(() => start().catch(onStartError), delay);
|
|
132
|
+
}
|
|
133
|
+
}));
|
|
134
|
+
|
|
135
|
+
current.ev.on('messaging-history.set', live(async ({ chats, contacts, messages, lidPnMappings, progress }) => {
|
|
136
|
+
for (const { lid, pn } of lidPnMappings || []) rememberLid(lid, pn);
|
|
137
|
+
for (const c of contacts || []) addContact(c);
|
|
138
|
+
for (const c of chats || []) {
|
|
139
|
+
const id = await chatIdFor(c.id, c.pnJid);
|
|
140
|
+
if (!id) continue;
|
|
141
|
+
const chat = store.ensureChat(id);
|
|
142
|
+
chat.name ||= c.name || null;
|
|
143
|
+
chat.unread = Math.max(chat.unread || 0, Number(c.unreadCount) || 0);
|
|
144
|
+
chat.lastTs = Math.max(chat.lastTs || 0, (Number(c.conversationTimestamp) || 0) * 1000);
|
|
145
|
+
}
|
|
146
|
+
for (const m of messages || []) await recordMessage(m, { live: false });
|
|
147
|
+
store.changed();
|
|
148
|
+
wa.emit('sync', typeof progress === 'number' && progress < 100 ? progress : null);
|
|
149
|
+
}));
|
|
150
|
+
|
|
151
|
+
current.ev.on('messages.upsert', live(async ({ messages, type }) => {
|
|
152
|
+
for (const m of messages) {
|
|
153
|
+
try {
|
|
154
|
+
await recordMessage(m, { live: type === 'notify' });
|
|
155
|
+
} catch (err) {
|
|
156
|
+
logger.warn({ err }, 'failed to process message');
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}));
|
|
160
|
+
|
|
161
|
+
// Ticks on our messages: 2 sent, 3 delivered, 4 read, 5 played.
|
|
162
|
+
current.ev.on('messages.update', live((updates) => {
|
|
163
|
+
for (const { key, update } of updates) {
|
|
164
|
+
if (key?.fromMe && typeof update?.status === 'number') setStatusLater(key.id, update.status);
|
|
165
|
+
}
|
|
166
|
+
}));
|
|
167
|
+
|
|
168
|
+
current.ev.on('contacts.upsert', live((list) => list.forEach(addContact)));
|
|
169
|
+
current.ev.on('contacts.update', live((list) => list.forEach(addContact)));
|
|
170
|
+
current.ev.on('lid-mapping.update', live(({ lid, pn }) => rememberLid(lid, pn)));
|
|
171
|
+
|
|
172
|
+
const onChats = live(async (list) => {
|
|
173
|
+
for (const c of list) {
|
|
174
|
+
const id = await chatIdFor(c.id, c.pnJid);
|
|
175
|
+
if (!id || !store.chats[id]) continue;
|
|
176
|
+
// unreadCount 0 means it was read somewhere else (e.g. on your phone).
|
|
177
|
+
if (c.unreadCount === 0 && store.chats[id].unread) { store.chats[id].unread = 0; store.changed(); }
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
current.ev.on('chats.update', onChats);
|
|
181
|
+
current.ev.on('chats.upsert', onChats);
|
|
182
|
+
|
|
183
|
+
current.ev.on('presence.update', live(({ id, presences }) => {
|
|
184
|
+
const chat = chatIdSync(id);
|
|
185
|
+
const p = Object.values(presences || {})[0]?.lastKnownPresence;
|
|
186
|
+
if (chat && p) wa.emit('presence', chat, p);
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function onStartError(err) {
|
|
191
|
+
logger.error({ err }, 'failed to start socket');
|
|
192
|
+
state.lastError = err.message;
|
|
193
|
+
setStatus('closed');
|
|
194
|
+
reconnectTimer = setTimeout(() => start().catch(onStartError), 5000);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function clearAuth() {
|
|
198
|
+
rmSync(AUTH_DIR, { recursive: true, force: true });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ---------------- chat ids (phone numbers vs hidden "lid" ids) ----------------
|
|
202
|
+
|
|
203
|
+
function rememberLid(lid, pn) {
|
|
204
|
+
if (!lid || !pn) return;
|
|
205
|
+
lid = jidNormalizedUser(lid);
|
|
206
|
+
pn = jidNormalizedUser(pn);
|
|
207
|
+
if (isLidUser(lid) && isPnUser(pn)) store.linkLid(lid, pn);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function isDirect(jid) {
|
|
211
|
+
return jid && !isJidGroup(jid) && !isJidBroadcast(jid) && !isJidNewsletter(jid) && !isJidStatusBroadcast(jid)
|
|
212
|
+
&& (isPnUser(jid) || isLidUser(jid));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Without network lookups: the phone JID if known, else the JID as given. */
|
|
216
|
+
function chatIdSync(jid) {
|
|
217
|
+
if (!jid) return null;
|
|
218
|
+
jid = jidNormalizedUser(jid);
|
|
219
|
+
return store.lidMap[jid] || jid;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Chat id for a direct chat (phone JID when we can find it), or null for groups etc. */
|
|
223
|
+
async function chatIdFor(jid, alt) {
|
|
224
|
+
if (!isDirect(jid)) return null;
|
|
225
|
+
jid = jidNormalizedUser(jid);
|
|
226
|
+
if (!isLidUser(jid)) return jid;
|
|
227
|
+
if (alt && isPnUser(alt)) { rememberLid(jid, alt); return jidNormalizedUser(alt); }
|
|
228
|
+
if (store.lidMap[jid]) return store.lidMap[jid];
|
|
229
|
+
try {
|
|
230
|
+
const pn = await sock?.signalRepository?.lidMapping?.getPNForLID(jid);
|
|
231
|
+
if (pn) { rememberLid(jid, pn); return jidNormalizedUser(pn); }
|
|
232
|
+
} catch {}
|
|
233
|
+
return jid;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function addContact(c) {
|
|
237
|
+
if (!c?.id) return;
|
|
238
|
+
let id = jidNormalizedUser(c.id);
|
|
239
|
+
if (isLidUser(id) && c.phoneNumber) { rememberLid(id, c.phoneNumber); id = jidNormalizedUser(c.phoneNumber); }
|
|
240
|
+
else if (isPnUser(id) && c.lid) rememberLid(c.lid, id);
|
|
241
|
+
if (!isDirect(id)) return;
|
|
242
|
+
store.upsertContact(chatIdSync(id), c);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ---------------- messages ----------------
|
|
246
|
+
|
|
247
|
+
const pendingStatus = new Map(); // ticks that arrived before the message was stored
|
|
248
|
+
|
|
249
|
+
function setStatusLater(id, status) {
|
|
250
|
+
if (store.setStatus(id, status)) return;
|
|
251
|
+
pendingStatus.set(id, Math.max(pendingStatus.get(id) ?? -1, status));
|
|
252
|
+
setTimeout(() => pendingStatus.delete(id), 60_000).unref?.();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const LABELS = {
|
|
256
|
+
imageMessage: '📷 Photo',
|
|
257
|
+
videoMessage: '🎥 Video',
|
|
258
|
+
ptvMessage: '🎥 Video note',
|
|
259
|
+
audioMessage: '🎤 Audio',
|
|
260
|
+
documentMessage: '📄 Document',
|
|
261
|
+
documentWithCaptionMessage: '📄 Document',
|
|
262
|
+
stickerMessage: '🏷️ Sticker',
|
|
263
|
+
contactMessage: '👤 Contact',
|
|
264
|
+
contactsArrayMessage: '👥 Contacts',
|
|
265
|
+
locationMessage: '📍 Location',
|
|
266
|
+
liveLocationMessage: '📍 Live location',
|
|
267
|
+
pollCreationMessage: '📊 Poll',
|
|
268
|
+
pollCreationMessageV2: '📊 Poll',
|
|
269
|
+
pollCreationMessageV3: '📊 Poll',
|
|
270
|
+
eventMessage: '📅 Event',
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const IGNORED = new Set([
|
|
274
|
+
'protocolMessage', 'senderKeyDistributionMessage', 'reactionMessage', 'pollUpdateMessage',
|
|
275
|
+
'messageContextInfo', 'keepInChatMessage', 'editedMessage', 'encReactionMessage', 'pinInChatMessage',
|
|
276
|
+
]);
|
|
277
|
+
|
|
278
|
+
function extractText(message) {
|
|
279
|
+
const content = normalizeMessageContent(message);
|
|
280
|
+
const kind = getContentType(content);
|
|
281
|
+
if (!kind || IGNORED.has(kind)) return null;
|
|
282
|
+
const body = content[kind];
|
|
283
|
+
if (kind === 'conversation') return { kind, text: body || '' };
|
|
284
|
+
if (kind === 'extendedTextMessage') return { kind, text: body?.text || '' };
|
|
285
|
+
let label = LABELS[kind] || `[${kind.replace(/Message$/, '')}]`;
|
|
286
|
+
if (kind === 'audioMessage' && body?.ptt) label = '🎤 Voice message';
|
|
287
|
+
if (kind === 'videoMessage' && body?.gifPlayback) label = '🎞️ GIF';
|
|
288
|
+
// View-once media is meant to be seen once on the phone, so it's never downloaded.
|
|
289
|
+
const viewOnce = Boolean(body?.viewOnce || message?.viewOnceMessage || message?.viewOnceMessageV2 || message?.viewOnceMessageV2Extension);
|
|
290
|
+
if (viewOnce) label = `👁️ View-once ${label.split(' ').pop().toLowerCase()}`;
|
|
291
|
+
const extra = body?.caption || body?.fileName || body?.displayName || body?.name || body?.title || '';
|
|
292
|
+
return { kind, text: extra ? `${label}: ${extra}` : label, media: true, viewOnce };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function recordMessage(msg, { live, localImage = null }) {
|
|
296
|
+
const { key } = msg;
|
|
297
|
+
if (!key?.remoteJid || !msg.message) return;
|
|
298
|
+
const chat = await chatIdFor(key.remoteJid, key.remoteJidAlt);
|
|
299
|
+
if (!chat) return; // groups, status updates, channels
|
|
300
|
+
|
|
301
|
+
const extracted = extractText(msg.message);
|
|
302
|
+
if (!extracted) return;
|
|
303
|
+
|
|
304
|
+
if (!key.fromMe && msg.pushName) store.upsertContact(chat, { notify: msg.pushName });
|
|
305
|
+
|
|
306
|
+
const entry = {
|
|
307
|
+
id: key.id,
|
|
308
|
+
ts: (Number(msg.messageTimestamp) || Math.floor(Date.now() / 1000)) * 1000,
|
|
309
|
+
fromMe: !!key.fromMe,
|
|
310
|
+
text: extracted.text,
|
|
311
|
+
key: { remoteJid: key.remoteJid, id: key.id, fromMe: !!key.fromMe, ...(key.participant && { participant: key.participant }) },
|
|
312
|
+
...(extracted.media && { media: true }),
|
|
313
|
+
};
|
|
314
|
+
if (entry.fromMe) {
|
|
315
|
+
entry.status = Math.max(typeof msg.status === 'number' ? msg.status : 2, pendingStatus.get(key.id) ?? 0);
|
|
316
|
+
pendingStatus.delete(key.id);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Photos: keep what's needed to download them (now, or later on /open).
|
|
320
|
+
const image = extracted.kind === 'imageMessage' && !extracted.viewOnce ? normalizeMessageContent(msg.message).imageMessage : null;
|
|
321
|
+
if (image?.mediaKey) {
|
|
322
|
+
entry.photo = {
|
|
323
|
+
status: 'remote',
|
|
324
|
+
mime: image.mimetype || 'image/jpeg',
|
|
325
|
+
w: Number(image.width) || 0, // used to make room for the inline preview
|
|
326
|
+
h: Number(image.height) || 0,
|
|
327
|
+
raw: Buffer.from(proto.Message.ImageMessage.encode({ ...image, jpegThumbnail: undefined }).finish()).toString('base64'),
|
|
328
|
+
};
|
|
329
|
+
if (localImage) savePhoto(entry, localImage); // one we just sent: we already have the bytes
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const added = store.addMessage(chat, entry, { live });
|
|
333
|
+
// Message arrived in the chat you're looking at: it's read.
|
|
334
|
+
if (added && live && !added.fromMe && store.activeChat === chat) markRead(chat, [added]);
|
|
335
|
+
// New photos download right away; ones from the history sync only when you open them.
|
|
336
|
+
if (added?.photo?.status === 'remote' && live) downloadPhoto(added).catch(() => {});
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---------------- photos ----------------
|
|
340
|
+
|
|
341
|
+
function savePhoto(entry, buffer) {
|
|
342
|
+
const ext = /png/.test(entry.photo.mime) ? 'png' : /webp/.test(entry.photo.mime) ? 'webp' : 'jpg';
|
|
343
|
+
const file = `${entry.id.replace(/[^\w-]/g, '')}.${ext}`;
|
|
344
|
+
mkdirSync(MEDIA_DIR, { recursive: true });
|
|
345
|
+
writeFileSync(path.join(MEDIA_DIR, file), buffer);
|
|
346
|
+
Object.assign(entry.photo, { status: 'ready', file, size: buffer.length });
|
|
347
|
+
delete entry.photo.raw; // no longer needed
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const downloads = new Map(); // message id -> promise
|
|
351
|
+
|
|
352
|
+
/** Downloads a photo into ~/.wacli/media. Safe to call twice; resolves to the file path. */
|
|
353
|
+
export function downloadPhoto(entry) {
|
|
354
|
+
const p = entry.photo;
|
|
355
|
+
if (!p) return Promise.reject(new UserError('That message has no photo'));
|
|
356
|
+
if (p.status === 'ready' && p.file && existsSync(path.join(MEDIA_DIR, p.file))) return Promise.resolve(path.join(MEDIA_DIR, p.file));
|
|
357
|
+
if (downloads.has(entry.id)) return downloads.get(entry.id);
|
|
358
|
+
if (!p.raw) return Promise.reject(new UserError('This photo can no longer be downloaded'));
|
|
359
|
+
|
|
360
|
+
const job = (async () => {
|
|
361
|
+
requireOpen();
|
|
362
|
+
p.status = 'downloading';
|
|
363
|
+
store.changed();
|
|
364
|
+
try {
|
|
365
|
+
const message = { key: entry.key, message: { imageMessage: proto.Message.ImageMessage.decode(Buffer.from(p.raw, 'base64')) } };
|
|
366
|
+
const buffer = await downloadMediaMessage(message, 'buffer', {}, {
|
|
367
|
+
logger,
|
|
368
|
+
reuploadRequest: (m) => sock.updateMediaMessage(m), // asks the sender's phone to re-upload expired photos
|
|
369
|
+
});
|
|
370
|
+
savePhoto(entry, buffer);
|
|
371
|
+
return path.join(MEDIA_DIR, entry.photo.file);
|
|
372
|
+
} catch (err) {
|
|
373
|
+
logger.warn({ err, id: entry.id }, 'photo download failed');
|
|
374
|
+
p.status = 'failed';
|
|
375
|
+
throw new UserError(`Couldn't download the photo: ${err.message}`);
|
|
376
|
+
} finally {
|
|
377
|
+
downloads.delete(entry.id);
|
|
378
|
+
store.changed();
|
|
379
|
+
}
|
|
380
|
+
})();
|
|
381
|
+
downloads.set(entry.id, job);
|
|
382
|
+
return job;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** For tests only: feed messages through the real handler with a stand-in socket. */
|
|
386
|
+
export const _test = { recordMessage, setSocket: (s) => { sock = s; }, setOpener: (fn) => { opener = fn; } };
|
|
387
|
+
|
|
388
|
+
let opener = null;
|
|
389
|
+
|
|
390
|
+
/** Opens a file in the system's default app (Photos on Windows). */
|
|
391
|
+
export function openFile(file) {
|
|
392
|
+
if (opener) return opener(file);
|
|
393
|
+
const [cmd, args] = process.platform === 'win32' ? ['explorer.exe', [file]]
|
|
394
|
+
: process.platform === 'darwin' ? ['open', [file]] : ['xdg-open', [file]];
|
|
395
|
+
spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ---------------- actions used by the UI ----------------
|
|
399
|
+
|
|
400
|
+
export class UserError extends Error {}
|
|
401
|
+
|
|
402
|
+
function requireOpen() {
|
|
403
|
+
if (state.status !== 'open' || !sock) throw new UserError('Not connected to WhatsApp right now.');
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export async function sendText(chat, text) {
|
|
407
|
+
requireOpen();
|
|
408
|
+
const sent = await sock.sendMessage(chat, { text });
|
|
409
|
+
if (sent) {
|
|
410
|
+
sent.status = 2;
|
|
411
|
+
await recordMessage(sent, { live: true });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Sends a file (from the attachment bar). Photos are converted to JPEG first.
|
|
417
|
+
* Voice/audio messages can't carry a caption, so it goes as a separate text.
|
|
418
|
+
*/
|
|
419
|
+
export async function sendFile(chat, attachment, caption = '') {
|
|
420
|
+
requireOpen();
|
|
421
|
+
const content = await buildContent(attachment, caption);
|
|
422
|
+
const sent = await sock.sendMessage(chat, content);
|
|
423
|
+
if (sent) {
|
|
424
|
+
sent.status = 2;
|
|
425
|
+
await recordMessage(sent, { live: true, localImage: Buffer.isBuffer(content.image) ? content.image : null });
|
|
426
|
+
}
|
|
427
|
+
if (caption && !('caption' in content)) await sendText(chat, caption);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Looks up a phone number. Returns its chat id, or throws if it isn't on WhatsApp. */
|
|
431
|
+
export async function findNumber(input) {
|
|
432
|
+
requireOpen();
|
|
433
|
+
const digits = String(input).replace(/\D/g, '');
|
|
434
|
+
if (digits.length < 8 || digits.length > 15) {
|
|
435
|
+
throw new UserError('Use the full number with country code, e.g. 919876543210');
|
|
436
|
+
}
|
|
437
|
+
const [result] = (await sock.onWhatsApp(digits)) || [];
|
|
438
|
+
if (!result?.exists) throw new UserError(`+${digits} is not on WhatsApp`);
|
|
439
|
+
return (await chatIdFor(result.jid)) || `${digits}@s.whatsapp.net`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Sends blue ticks for the unread messages in a chat. */
|
|
443
|
+
export function markRead(chat, entries) {
|
|
444
|
+
const c = store.chats[chat];
|
|
445
|
+
if (!entries) {
|
|
446
|
+
const unread = c?.unread || 0;
|
|
447
|
+
entries = unread ? store.history(chat).filter((m) => !m.fromMe).slice(-unread) : [];
|
|
448
|
+
}
|
|
449
|
+
if (c?.unread) { c.unread = 0; store.changed(); }
|
|
450
|
+
if (!options.readReceipts || !entries.length || !sock || state.status !== 'open') return;
|
|
451
|
+
sock.readMessages(entries.map((m) => m.key).filter(Boolean)).catch((err) => logger.warn({ err }, 'readMessages failed'));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export function subscribePresence(chat) {
|
|
455
|
+
if (sock && state.status === 'open' && options.online) sock.presenceSubscribe(chat).catch(() => {});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export function sendTyping(chat, typing) {
|
|
459
|
+
if (sock && state.status === 'open') sock.sendPresenceUpdate(typing ? 'composing' : 'paused', chat).catch(() => {});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export async function logout() {
|
|
463
|
+
requireOpen();
|
|
464
|
+
await sock.logout(); // the 'close' event clears the session and shows a new QR
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export async function stop() {
|
|
468
|
+
clearTimeout(reconnectTimer);
|
|
469
|
+
generation++;
|
|
470
|
+
if (sock && state.status === 'open' && options.online) {
|
|
471
|
+
await Promise.race([sock.sendPresenceUpdate('unavailable').catch(() => {}), new Promise((r) => setTimeout(r, 500))]);
|
|
472
|
+
}
|
|
473
|
+
try { sock?.end(undefined); } catch {}
|
|
474
|
+
}
|