@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/store.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { MEDIA_DIR, STORE_FILE, logger } from './config.js';
|
|
5
|
+
|
|
6
|
+
const PER_CHAT_LIMIT = 500;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Local copy of chats, messages and contact names.
|
|
10
|
+
* Chat ids are WhatsApp JIDs: `<number>@s.whatsapp.net`, or `<id>@lid` when WhatsApp
|
|
11
|
+
* hides the phone number and we haven't learned it yet.
|
|
12
|
+
*
|
|
13
|
+
* Emits 'change' whenever something visible changed.
|
|
14
|
+
*/
|
|
15
|
+
class Store extends EventEmitter {
|
|
16
|
+
constructor() {
|
|
17
|
+
super();
|
|
18
|
+
this.reset();
|
|
19
|
+
this.activeChat = null; // set by the UI: messages arriving here don't count as unread
|
|
20
|
+
this.saveTimer = null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
reset() {
|
|
24
|
+
this.chats = {}; // id -> { id, name, unread, lastTs }
|
|
25
|
+
this.messages = {}; // id -> [entry] sorted by ts
|
|
26
|
+
this.contacts = {}; // id -> { name, notify, verifiedName }
|
|
27
|
+
this.aliases = {}; // id -> name you set with /name
|
|
28
|
+
this.lidMap = {}; // lid jid -> phone jid
|
|
29
|
+
this.index = new Map(); // message id -> chat id
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
load() {
|
|
33
|
+
let data;
|
|
34
|
+
try {
|
|
35
|
+
data = JSON.parse(readFileSync(STORE_FILE, 'utf8'));
|
|
36
|
+
} catch (err) {
|
|
37
|
+
if (err.code !== 'ENOENT') logger.warn({ err }, 'could not read store');
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
Object.assign(this, {
|
|
41
|
+
chats: data.chats || {},
|
|
42
|
+
messages: data.messages || {},
|
|
43
|
+
contacts: data.contacts || {},
|
|
44
|
+
aliases: data.aliases || {},
|
|
45
|
+
lidMap: data.lidMap || {},
|
|
46
|
+
});
|
|
47
|
+
for (const [chat, list] of Object.entries(this.messages)) {
|
|
48
|
+
for (const m of list) {
|
|
49
|
+
this.index.set(m.id, chat);
|
|
50
|
+
// A download cut off by quitting: allow it to be retried.
|
|
51
|
+
if (m.photo?.status === 'downloading') m.photo.status = m.photo.raw ? 'remote' : 'failed';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
save() {
|
|
57
|
+
clearTimeout(this.saveTimer);
|
|
58
|
+
this.saveTimer = setTimeout(() => this.flush(), 1000);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
flush() {
|
|
62
|
+
clearTimeout(this.saveTimer);
|
|
63
|
+
const { chats, messages, contacts, aliases, lidMap } = this;
|
|
64
|
+
try {
|
|
65
|
+
writeFileSync(STORE_FILE + '.tmp', JSON.stringify({ chats, messages, contacts, aliases, lidMap }));
|
|
66
|
+
renameSync(STORE_FILE + '.tmp', STORE_FILE);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
logger.warn({ err }, 'could not save store');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
changed() {
|
|
73
|
+
this.save();
|
|
74
|
+
this.emit('change');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
ensureChat(id) {
|
|
78
|
+
return (this.chats[id] ||= { id, name: null, unread: 0, lastTs: 0 });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Newest first. */
|
|
82
|
+
sortedChats() {
|
|
83
|
+
return Object.values(this.chats).sort((a, b) => (b.lastTs || 0) - (a.lastTs || 0));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
history(chat) {
|
|
87
|
+
return this.messages[chat] || [];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
lastMessage(chat) {
|
|
91
|
+
const list = this.messages[chat];
|
|
92
|
+
return list?.length ? list[list.length - 1] : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
totalUnread() {
|
|
96
|
+
return Object.values(this.chats).reduce((n, c) => n + (c.unread || 0), 0);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
displayName(id) {
|
|
100
|
+
const c = this.contacts[id] || {};
|
|
101
|
+
return this.aliases[id] || c.name || c.notify || c.verifiedName || this.chats[id]?.name || formatJid(id);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Adds a message. `live` = arrived just now (counts as unread unless the chat is open).
|
|
106
|
+
* Returns the stored entry, or null for a duplicate.
|
|
107
|
+
*/
|
|
108
|
+
addMessage(chat, entry, { live = false } = {}) {
|
|
109
|
+
if (this.index.has(entry.id)) return null;
|
|
110
|
+
const list = (this.messages[chat] ||= []);
|
|
111
|
+
// History sync can deliver out of order: insert in timestamp order.
|
|
112
|
+
let i = list.length;
|
|
113
|
+
while (i > 0 && list[i - 1].ts > entry.ts) i--;
|
|
114
|
+
list.splice(i, 0, entry);
|
|
115
|
+
this.index.set(entry.id, chat);
|
|
116
|
+
if (list.length > PER_CHAT_LIMIT) {
|
|
117
|
+
for (const old of list.splice(0, list.length - PER_CHAT_LIMIT)) {
|
|
118
|
+
this.index.delete(old.id);
|
|
119
|
+
if (old.photo?.file) rmSync(path.join(MEDIA_DIR, old.photo.file), { force: true });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const c = this.ensureChat(chat);
|
|
124
|
+
c.lastTs = Math.max(c.lastTs || 0, entry.ts);
|
|
125
|
+
if (live) {
|
|
126
|
+
if (entry.fromMe) c.unread = 0; // you replied (maybe from your phone), so it's read
|
|
127
|
+
else if (this.activeChat !== chat) c.unread = (c.unread || 0) + 1;
|
|
128
|
+
}
|
|
129
|
+
this.changed();
|
|
130
|
+
return entry;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Delivery ticks of our own messages. Only ever moves forward, except to mark a failure. */
|
|
134
|
+
setStatus(id, status) {
|
|
135
|
+
const chat = this.index.get(id);
|
|
136
|
+
const entry = chat && this.messages[chat].find((m) => m.id === id);
|
|
137
|
+
if (!entry) return false;
|
|
138
|
+
const cur = entry.status ?? 1;
|
|
139
|
+
const next = status === 0 ? (cur <= 1 ? 0 : cur) : Math.max(cur, status);
|
|
140
|
+
if (next !== entry.status) { entry.status = next; this.changed(); }
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
upsertContact(id, fields) {
|
|
145
|
+
const c = (this.contacts[id] ||= {});
|
|
146
|
+
let dirty = false;
|
|
147
|
+
for (const k of ['name', 'notify', 'verifiedName']) {
|
|
148
|
+
if (fields[k] && fields[k] !== c[k]) { c[k] = fields[k]; dirty = true; }
|
|
149
|
+
}
|
|
150
|
+
if (dirty) this.changed();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
setAlias(id, name) {
|
|
154
|
+
if (name) this.aliases[id] = name;
|
|
155
|
+
else delete this.aliases[id];
|
|
156
|
+
this.changed();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Records that a hidden-number chat (lid) belongs to a phone number, and merges the two. */
|
|
160
|
+
linkLid(lid, pn) {
|
|
161
|
+
if (this.lidMap[lid] === pn) return;
|
|
162
|
+
this.lidMap[lid] = pn;
|
|
163
|
+
if (this.chats[lid] || this.messages[lid] || this.contacts[lid] || this.aliases[lid]) {
|
|
164
|
+
this.mergeChat(lid, pn);
|
|
165
|
+
}
|
|
166
|
+
this.changed();
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
mergeChat(from, to) {
|
|
170
|
+
const src = this.chats[from];
|
|
171
|
+
if (src) {
|
|
172
|
+
const dst = this.ensureChat(to);
|
|
173
|
+
dst.unread = (dst.unread || 0) + (src.unread || 0);
|
|
174
|
+
dst.lastTs = Math.max(dst.lastTs || 0, src.lastTs || 0);
|
|
175
|
+
dst.name ||= src.name;
|
|
176
|
+
delete this.chats[from];
|
|
177
|
+
}
|
|
178
|
+
if (this.messages[from]) {
|
|
179
|
+
const ids = new Set((this.messages[to] || []).map((m) => m.id));
|
|
180
|
+
const merged = [...(this.messages[to] || []), ...this.messages[from].filter((m) => !ids.has(m.id))]
|
|
181
|
+
.sort((a, b) => a.ts - b.ts)
|
|
182
|
+
.slice(-PER_CHAT_LIMIT);
|
|
183
|
+
for (const m of this.messages[from]) this.index.delete(m.id);
|
|
184
|
+
for (const m of merged) this.index.set(m.id, to);
|
|
185
|
+
this.messages[to] = merged;
|
|
186
|
+
delete this.messages[from];
|
|
187
|
+
}
|
|
188
|
+
if (this.contacts[from]) {
|
|
189
|
+
this.contacts[to] = { ...this.contacts[from], ...this.contacts[to] };
|
|
190
|
+
delete this.contacts[from];
|
|
191
|
+
}
|
|
192
|
+
if (this.aliases[from] && !this.aliases[to]) this.aliases[to] = this.aliases[from];
|
|
193
|
+
delete this.aliases[from];
|
|
194
|
+
if (this.activeChat === from) this.activeChat = to;
|
|
195
|
+
this.emit('merged', from, to);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Forget everything (used on logout, so another account doesn't see these chats). */
|
|
199
|
+
clear() {
|
|
200
|
+
this.reset();
|
|
201
|
+
this.activeChat = null;
|
|
202
|
+
this.flush();
|
|
203
|
+
this.emit('change');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function formatJid(id) {
|
|
208
|
+
const [user, server] = String(id).split('@');
|
|
209
|
+
if (server === 's.whatsapp.net') return '+' + user.split(':')[0];
|
|
210
|
+
if (server === 'lid') return 'Unknown (hidden number)';
|
|
211
|
+
return id;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export const store = new Store();
|
package/src/text.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import stringWidth from 'string-width';
|
|
2
|
+
|
|
3
|
+
const segmenter = new Intl.Segmenter();
|
|
4
|
+
|
|
5
|
+
/** Splits text into user-perceived characters (so emoji and accents stay whole). */
|
|
6
|
+
export function graphemes(text) {
|
|
7
|
+
return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Columns the text takes in the terminal. */
|
|
11
|
+
export function width(text) {
|
|
12
|
+
return stringWidth(text);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Cuts plain text to at most `cols` columns and pads it with spaces to exactly `cols`. */
|
|
16
|
+
export function fit(text, cols, { ellipsis = true } = {}) {
|
|
17
|
+
if (cols <= 0) return '';
|
|
18
|
+
text = String(text ?? '').replace(/[\r\n\t]+/g, ' ');
|
|
19
|
+
const w = stringWidth(text);
|
|
20
|
+
if (w <= cols) return text + ' '.repeat(cols - w);
|
|
21
|
+
let out = '';
|
|
22
|
+
let used = 0;
|
|
23
|
+
const limit = ellipsis ? cols - 1 : cols;
|
|
24
|
+
for (const g of graphemes(text)) {
|
|
25
|
+
const gw = stringWidth(g);
|
|
26
|
+
if (used + gw > limit) break;
|
|
27
|
+
out += g;
|
|
28
|
+
used += gw;
|
|
29
|
+
}
|
|
30
|
+
if (ellipsis) { out += '…'; used += 1; }
|
|
31
|
+
return out + ' '.repeat(Math.max(0, cols - used));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Word-wraps plain text into lines of at most `cols` columns. Keeps explicit line breaks. */
|
|
35
|
+
export function wrap(text, cols) {
|
|
36
|
+
cols = Math.max(1, cols);
|
|
37
|
+
const lines = [];
|
|
38
|
+
for (const para of String(text ?? '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').split('\n')) {
|
|
39
|
+
if (!para) { lines.push(''); continue; }
|
|
40
|
+
let line = '';
|
|
41
|
+
let lineW = 0;
|
|
42
|
+
// Tokens are runs of spaces or runs of non-spaces.
|
|
43
|
+
for (const token of para.match(/\s+|\S+/g)) {
|
|
44
|
+
const tw = stringWidth(token);
|
|
45
|
+
if (lineW + tw <= cols) { line += token; lineW += tw; continue; }
|
|
46
|
+
if (/^\s+$/.test(token)) { lines.push(line); line = ''; lineW = 0; continue; }
|
|
47
|
+
if (tw <= cols) {
|
|
48
|
+
lines.push(line.trimEnd());
|
|
49
|
+
line = token; lineW = tw;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
// A word longer than the line: break it by characters.
|
|
53
|
+
for (const g of graphemes(token)) {
|
|
54
|
+
const gw = stringWidth(g);
|
|
55
|
+
if (lineW + gw > cols) { lines.push(line.trimEnd()); line = ''; lineW = 0; }
|
|
56
|
+
line += g; lineW += gw;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
lines.push(line.trimEnd());
|
|
60
|
+
}
|
|
61
|
+
return lines;
|
|
62
|
+
}
|