@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/tui.js
ADDED
|
@@ -0,0 +1,1011 @@
|
|
|
1
|
+
import readline from 'node:readline';
|
|
2
|
+
import { store, formatJid } from './store.js';
|
|
3
|
+
import * as wa from './whatsapp.js';
|
|
4
|
+
import { fit, graphemes, width, wrap } from './text.js';
|
|
5
|
+
import { logger, MEDIA_DIR } from './config.js';
|
|
6
|
+
import { encodeSixel, graphics, makePreview, previewCells } from './sixel.js';
|
|
7
|
+
import { rmSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { describe, filesFromClipboard, formatSize, KIND_ICON, looksLikePath, parseDroppedFiles, TMP_DIR } from './media.js';
|
|
10
|
+
|
|
11
|
+
// ---------------- styling ----------------
|
|
12
|
+
const S = {
|
|
13
|
+
reset: '\x1b[0m',
|
|
14
|
+
bold: '\x1b[1m',
|
|
15
|
+
dim: '\x1b[2m',
|
|
16
|
+
inverse: '\x1b[7m',
|
|
17
|
+
red: '\x1b[31m',
|
|
18
|
+
green: '\x1b[32m',
|
|
19
|
+
yellow: '\x1b[33m',
|
|
20
|
+
cyan: '\x1b[36m',
|
|
21
|
+
blue: '\x1b[94m',
|
|
22
|
+
gray: '\x1b[90m',
|
|
23
|
+
selected: '\x1b[100m', // gray background
|
|
24
|
+
bar: '\x1b[42m\x1b[30m', // green bar with black text
|
|
25
|
+
};
|
|
26
|
+
const paint = (style, text) => (style ? style + text + S.reset : text);
|
|
27
|
+
|
|
28
|
+
const TICKS = { 0: ['β', S.red], 1: ['π', S.gray], 2: ['β', S.gray], 3: ['ββ', S.gray], 4: ['ββ', S.blue], 5: ['ββ', S.blue] };
|
|
29
|
+
|
|
30
|
+
// Windows Terminal keeps Ctrl+V for its own text paste, so wacli uses Alt+V there (like Claude Code).
|
|
31
|
+
// Mac and Linux terminals paste with Cmd+V / Ctrl+Shift+V and pass Ctrl+V through, and Option+V on a Mac types "β".
|
|
32
|
+
const PASTE_KEY = process.platform === 'win32' ? 'Alt+V' : 'Ctrl+V';
|
|
33
|
+
|
|
34
|
+
const HELP = [
|
|
35
|
+
['Keys', ''],
|
|
36
|
+
['Tab', 'switch between chat list and message box'],
|
|
37
|
+
['β / β', 'move in the chat list, or scroll messages'],
|
|
38
|
+
['Enter', 'open the selected chat / send the message'],
|
|
39
|
+
['Ctrl+J', 'new line in the message'],
|
|
40
|
+
['drop a file', 'drag files onto the window to attach (or paste a path)'],
|
|
41
|
+
[PASTE_KEY, process.platform === 'win32' ? 'paste an image/screenshot, a GIF (Win + .) or copied files' : 'paste an image/screenshot or copied files'],
|
|
42
|
+
['Ctrl+O', 'open the latest photo in this chat'],
|
|
43
|
+
['Backspace', 'on an empty message box: remove the last attached file'],
|
|
44
|
+
['PgUp / PgDn', 'scroll messages a page'],
|
|
45
|
+
['Ctrl+N / Ctrl+P', 'next / previous chat'],
|
|
46
|
+
['Esc', 'back to the chat list / clear the search'],
|
|
47
|
+
['Ctrl+C', 'quit'],
|
|
48
|
+
['', ''],
|
|
49
|
+
['Chat list', ''],
|
|
50
|
+
['type', 'search by name or number'],
|
|
51
|
+
['number + Enter', 'start a chat with a new number (with country code)'],
|
|
52
|
+
['', ''],
|
|
53
|
+
['Commands', '(type in the message box)'],
|
|
54
|
+
['/new <number>', 'start a chat, e.g. /new 919876543210'],
|
|
55
|
+
['/open <n>', 'open photo #n of this chat (downloads it if needed)'],
|
|
56
|
+
['/name <name>', 'give this chat a name (only in wacli); /name alone removes it'],
|
|
57
|
+
['/logout', 'unlink this device from your phone'],
|
|
58
|
+
['/quit', 'exit wacli'],
|
|
59
|
+
['//text', 'send a message that starts with /'],
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
// ---------------- dates ----------------
|
|
63
|
+
const dayKey = (ts) => new Date(ts).toDateString();
|
|
64
|
+
const timeOf = (ts) => new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
65
|
+
|
|
66
|
+
function dayLabel(ts) {
|
|
67
|
+
const d = new Date(ts);
|
|
68
|
+
const today = new Date();
|
|
69
|
+
const yesterday = new Date(Date.now() - 86400000);
|
|
70
|
+
if (d.toDateString() === today.toDateString()) return 'Today';
|
|
71
|
+
if (d.toDateString() === yesterday.toDateString()) return 'Yesterday';
|
|
72
|
+
return d.toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short', year: d.getFullYear() === today.getFullYear() ? undefined : 'numeric' });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function shortWhen(ts) {
|
|
76
|
+
if (!ts) return '';
|
|
77
|
+
const d = new Date(ts);
|
|
78
|
+
const now = new Date();
|
|
79
|
+
if (d.toDateString() === now.toDateString()) return timeOf(ts);
|
|
80
|
+
if (d.toDateString() === new Date(Date.now() - 86400000).toDateString()) return 'Yesterday';
|
|
81
|
+
if (now - d < 6 * 86400000) return d.toLocaleDateString([], { weekday: 'short' });
|
|
82
|
+
return d.toLocaleDateString([], { day: 'numeric', month: 'numeric', year: '2-digit' });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Full-screen terminal UI. Each frame is a list of rows; a row is a list of
|
|
87
|
+
* [column, styledText] parts placed with absolute cursor moves, so a wide emoji that the
|
|
88
|
+
* terminal measures differently can't push the rest of the screen out of line.
|
|
89
|
+
*/
|
|
90
|
+
export class App {
|
|
91
|
+
constructor({ onQuit }) {
|
|
92
|
+
this.out = process.stdout;
|
|
93
|
+
this.in = process.stdin;
|
|
94
|
+
this.onQuit = onQuit;
|
|
95
|
+
this.active = false;
|
|
96
|
+
|
|
97
|
+
this.focus = 'list'; // list | input
|
|
98
|
+
this.filter = '';
|
|
99
|
+
this.selected = 0;
|
|
100
|
+
this.listScroll = 0;
|
|
101
|
+
this.chat = null; // open chat id
|
|
102
|
+
this.scroll = 0; // message lines scrolled up from the bottom
|
|
103
|
+
this.input = []; // graphemes
|
|
104
|
+
this.cursor = 0;
|
|
105
|
+
this.inputScroll = 0;
|
|
106
|
+
this.help = false;
|
|
107
|
+
this.flashMsg = null;
|
|
108
|
+
this.presence = {}; // chat -> 'composing' | 'available' | ...
|
|
109
|
+
this.sync = null;
|
|
110
|
+
this.busy = false;
|
|
111
|
+
this.prevRows = [];
|
|
112
|
+
this.lineCache = new Map();
|
|
113
|
+
this.typing = { chat: null, at: 0, timer: null };
|
|
114
|
+
this.pasting = false;
|
|
115
|
+
this.pasteBuf = '';
|
|
116
|
+
this.pendingFiles = {}; // chat -> files waiting to be sent
|
|
117
|
+
this.sending = false;
|
|
118
|
+
this.lastKeyReturn = false;
|
|
119
|
+
this.previews = new Map(); // photo previews: "id|maxCols|maxRows" -> { state, img }
|
|
120
|
+
this.sixelCache = new Map(); // encoded (and cropped) previews
|
|
121
|
+
this.drawnImages = new Set();
|
|
122
|
+
this.frameImages = [];
|
|
123
|
+
|
|
124
|
+
this.onKey = this.onKey.bind(this);
|
|
125
|
+
this.render = this.render.bind(this);
|
|
126
|
+
this.scheduleRender = this.scheduleRender.bind(this);
|
|
127
|
+
|
|
128
|
+
store.on('change', this.scheduleRender);
|
|
129
|
+
store.on('merged', (from, to) => {
|
|
130
|
+
if (this.chat === from) this.chat = to;
|
|
131
|
+
if (this.presence[from]) this.presence[to] = this.presence[from];
|
|
132
|
+
});
|
|
133
|
+
wa.wa.on('status', this.scheduleRender);
|
|
134
|
+
wa.wa.on('sync', (p) => { this.sync = p; this.scheduleRender(); });
|
|
135
|
+
wa.wa.on('presence', (chat, p) => {
|
|
136
|
+
this.presence[chat] = p;
|
|
137
|
+
clearTimeout(this.presenceTimer?.[chat]);
|
|
138
|
+
// "typingβ¦" without a follow-up update shouldn't stick forever.
|
|
139
|
+
if (p === 'composing' || p === 'recording') {
|
|
140
|
+
(this.presenceTimer ||= {})[chat] = setTimeout(() => {
|
|
141
|
+
if (this.presence[chat] === p) { this.presence[chat] = 'available'; this.scheduleRender(); }
|
|
142
|
+
}, 25000);
|
|
143
|
+
}
|
|
144
|
+
this.scheduleRender();
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---------------- lifecycle ----------------
|
|
149
|
+
start() {
|
|
150
|
+
if (this.active) return;
|
|
151
|
+
this.active = true;
|
|
152
|
+
this.prevRows = [];
|
|
153
|
+
this.drawnImages = new Set();
|
|
154
|
+
// alternate screen, hide cursor, no auto-wrap, bracketed paste
|
|
155
|
+
this.out.write('\x1b[?1049h\x1b[?25l\x1b[?7l\x1b[?2004h\x1b[2J');
|
|
156
|
+
readline.emitKeypressEvents(this.in);
|
|
157
|
+
if (this.in.isTTY) this.in.setRawMode(true);
|
|
158
|
+
this.in.on('keypress', this.onKey);
|
|
159
|
+
this.in.resume();
|
|
160
|
+
this.out.on('resize', this.onResize = () => { this.prevRows = []; this.out.write('\x1b[2J'); this.render(); });
|
|
161
|
+
if (this.chat) this.openChat(this.chat, { focus: this.focus });
|
|
162
|
+
this.render();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
stop() {
|
|
166
|
+
if (!this.active) return;
|
|
167
|
+
this.active = false;
|
|
168
|
+
this.in.off('keypress', this.onKey);
|
|
169
|
+
this.out.off('resize', this.onResize);
|
|
170
|
+
if (this.in.isTTY) this.in.setRawMode(false);
|
|
171
|
+
this.in.pause();
|
|
172
|
+
this.out.write('\x1b[0m\x1b[?2004l\x1b[?7h\x1b[?25h\x1b[?1049l\x1b]0;\x07');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Called after logout: forget the open chat etc. */
|
|
176
|
+
resetView() {
|
|
177
|
+
Object.assign(this, { focus: 'list', filter: '', selected: 0, listScroll: 0, chat: null, scroll: 0, input: [], cursor: 0, presence: {}, pendingFiles: {} });
|
|
178
|
+
store.activeChat = null;
|
|
179
|
+
this.lineCache.clear();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
scheduleRender() {
|
|
183
|
+
if (!this.active || this.renderQueued) return;
|
|
184
|
+
this.renderQueued = true;
|
|
185
|
+
setTimeout(() => { this.renderQueued = false; this.render(); }, 16);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
flash(text, style = S.yellow) {
|
|
189
|
+
this.flashMsg = { text, style };
|
|
190
|
+
clearTimeout(this.flashTimer);
|
|
191
|
+
this.flashTimer = setTimeout(() => { this.flashMsg = null; this.scheduleRender(); }, 4000);
|
|
192
|
+
this.scheduleRender();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---------------- data helpers ----------------
|
|
196
|
+
listItems() {
|
|
197
|
+
const q = this.filter.trim().toLowerCase();
|
|
198
|
+
const digits = q.replace(/[\s+\-()]/g, '');
|
|
199
|
+
let chats = store.sortedChats();
|
|
200
|
+
if (q) {
|
|
201
|
+
chats = chats.filter((c) => {
|
|
202
|
+
const name = store.displayName(c.id).toLowerCase();
|
|
203
|
+
const num = c.id.split('@')[0];
|
|
204
|
+
return name.includes(q) || (/^\d+$/.test(digits) && num.includes(digits));
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
const items = chats.map((c) => ({ type: 'chat', id: c.id }));
|
|
208
|
+
if (/^\d{8,15}$/.test(digits) && !chats.some((c) => c.id === `${digits}@s.whatsapp.net`)) {
|
|
209
|
+
items.push({ type: 'new', number: digits });
|
|
210
|
+
}
|
|
211
|
+
return items;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
openChat(id, { focus = 'input' } = {}) {
|
|
215
|
+
if (this.chat && this.chat !== id) this.stopTyping();
|
|
216
|
+
this.chat = id;
|
|
217
|
+
store.activeChat = id;
|
|
218
|
+
this.scroll = 0;
|
|
219
|
+
this.focus = focus;
|
|
220
|
+
this.help = false;
|
|
221
|
+
wa.markRead(id);
|
|
222
|
+
wa.subscribePresence(id);
|
|
223
|
+
const idx = this.listItems().findIndex((it) => it.id === id);
|
|
224
|
+
if (idx >= 0) this.selected = idx;
|
|
225
|
+
this.scheduleRender();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async startNewChat(number) {
|
|
229
|
+
this.flash(`Looking up +${number}β¦`, S.gray);
|
|
230
|
+
try {
|
|
231
|
+
const id = await wa.findNumber(number);
|
|
232
|
+
store.ensureChat(id);
|
|
233
|
+
if (!store.chats[id].lastTs) store.chats[id].lastTs = Date.now(); // show it at the top
|
|
234
|
+
store.changed();
|
|
235
|
+
this.filter = '';
|
|
236
|
+
this.openChat(id);
|
|
237
|
+
this.flash(`Chat with ${store.displayName(id)} opened`, S.green);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
this.flash(err instanceof wa.UserError ? err.message : `Lookup failed: ${err.message}`, S.red);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---------------- input ----------------
|
|
244
|
+
onKey(str, key = {}) {
|
|
245
|
+
try {
|
|
246
|
+
this.handleKey(str, key);
|
|
247
|
+
} catch (err) {
|
|
248
|
+
logger.error({ err }, 'key handler failed');
|
|
249
|
+
this.flash(err.message, S.red);
|
|
250
|
+
}
|
|
251
|
+
this.scheduleRender();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
handleKey(str, key) {
|
|
255
|
+
const name = key.name;
|
|
256
|
+
if (name === 'paste-start') { this.pasting = true; this.pasteBuf = ''; return; }
|
|
257
|
+
if (name === 'paste-end') { this.pasting = false; return this.handlePaste(this.pasteBuf); }
|
|
258
|
+
|
|
259
|
+
if (this.pasting) {
|
|
260
|
+
// Collect the whole paste first: dropped files arrive as a pasted path.
|
|
261
|
+
// Pasted line breaks become new lines in the message instead of sending it.
|
|
262
|
+
if (name === 'return' || name === 'enter') {
|
|
263
|
+
if (!(name === 'enter' && this.lastKeyReturn)) this.pasteBuf += '\n';
|
|
264
|
+
this.lastKeyReturn = name === 'return';
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
this.lastKeyReturn = false;
|
|
268
|
+
if (str && !key.ctrl && !key.meta) this.pasteBuf += str.replace(/\r\n?/g, '\n');
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (key.ctrl && name === 'c') return this.onQuit();
|
|
273
|
+
if (this.help) { this.help = false; return; }
|
|
274
|
+
if (name === 'f1') { this.help = true; return; }
|
|
275
|
+
|
|
276
|
+
// Paste an image, a GIF or copied files from the clipboard. Both keys work everywhere;
|
|
277
|
+
// PASTE_KEY is the one that reaches wacli on this platform.
|
|
278
|
+
if ((key.meta || key.ctrl) && name === 'v') return void this.pasteFromClipboard();
|
|
279
|
+
if (key.ctrl && name === 'o') return void this.openPhoto(); // the latest photo in this chat
|
|
280
|
+
if (key.ctrl && (name === 'n' || name === 'p')) return this.cycleChat(name === 'n' ? 1 : -1);
|
|
281
|
+
if (name === 'pageup') return this.scrollBy(this.msgHeight() - 1);
|
|
282
|
+
if (name === 'pagedown') return this.scrollBy(-(this.msgHeight() - 1));
|
|
283
|
+
if (name === 'tab') {
|
|
284
|
+
if (this.focus === 'list' && this.chat) this.focus = 'input';
|
|
285
|
+
else this.focus = 'list';
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (this.focus === 'list') return this.listKey(str, key);
|
|
290
|
+
return this.inputKey(str, key);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
listKey(str, key) {
|
|
294
|
+
const items = this.listItems();
|
|
295
|
+
const name = key.name;
|
|
296
|
+
if (name === 'up') this.selected = Math.max(0, this.selected - 1);
|
|
297
|
+
else if (name === 'down') this.selected = Math.min(items.length - 1, this.selected + 1);
|
|
298
|
+
else if (name === 'home') this.selected = 0;
|
|
299
|
+
else if (name === 'end') this.selected = items.length - 1;
|
|
300
|
+
else if (name === 'return') {
|
|
301
|
+
const it = items[this.selected];
|
|
302
|
+
if (!it) return;
|
|
303
|
+
if (it.type === 'new') return void this.startNewChat(it.number);
|
|
304
|
+
this.filter = '';
|
|
305
|
+
this.openChat(it.id);
|
|
306
|
+
} else if (name === 'escape') {
|
|
307
|
+
if (this.filter) { this.filter = ''; this.selected = 0; }
|
|
308
|
+
else if (this.chat) this.focus = 'input';
|
|
309
|
+
} else if (name === 'backspace') {
|
|
310
|
+
this.filter = graphemes(this.filter).slice(0, -1).join('');
|
|
311
|
+
this.selected = 0;
|
|
312
|
+
} else if (isPrintable(str, key)) {
|
|
313
|
+
this.filter += str;
|
|
314
|
+
this.selected = 0;
|
|
315
|
+
this.checkTypedPath();
|
|
316
|
+
}
|
|
317
|
+
this.selected = Math.max(0, Math.min(this.selected, this.listItems().length - 1));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
inputKey(str, key) {
|
|
321
|
+
const name = key.name;
|
|
322
|
+
if (name === 'return' && !key.meta) return this.submit();
|
|
323
|
+
if (name === 'enter' || (name === 'return' && key.meta)) return this.insertText('\n');
|
|
324
|
+
if (name === 'escape') { this.focus = 'list'; return; }
|
|
325
|
+
if (name === 'up') return this.scrollBy(3);
|
|
326
|
+
if (name === 'down') return this.scrollBy(-3);
|
|
327
|
+
if (name === 'left') this.cursor = Math.max(0, this.cursor - 1);
|
|
328
|
+
else if (name === 'right') this.cursor = Math.min(this.input.length, this.cursor + 1);
|
|
329
|
+
else if (name === 'home' || (key.ctrl && name === 'a')) this.cursor = 0;
|
|
330
|
+
else if (name === 'end' || (key.ctrl && name === 'e')) this.cursor = this.input.length;
|
|
331
|
+
else if (name === 'backspace') {
|
|
332
|
+
if (!this.input.length && this.attachments.length) {
|
|
333
|
+
const removed = this.attachments.pop();
|
|
334
|
+
discardTemp(removed);
|
|
335
|
+
this.flash(`Removed ${removed.name}`, S.gray);
|
|
336
|
+
} else if (key.ctrl || key.meta) this.deleteWord();
|
|
337
|
+
else if (this.cursor > 0) { this.input.splice(this.cursor - 1, 1); this.cursor--; }
|
|
338
|
+
} else if (name === 'delete') this.input.splice(this.cursor, 1);
|
|
339
|
+
else if (key.ctrl && name === 'w') this.deleteWord();
|
|
340
|
+
else if (key.ctrl && name === 'u') { this.input.splice(0, this.cursor); this.cursor = 0; }
|
|
341
|
+
else if (key.ctrl && name === 'k') this.input.splice(this.cursor);
|
|
342
|
+
else if (isPrintable(str, key)) { this.insertText(str); this.checkTypedPath(); }
|
|
343
|
+
else return;
|
|
344
|
+
this.onTyped();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ---------------- attachments (drag and drop) ----------------
|
|
348
|
+
|
|
349
|
+
/** Files waiting to be sent in the open chat. Kept per chat, so switching chats doesn't lose them. */
|
|
350
|
+
get attachments() {
|
|
351
|
+
if (!this.chat) return [];
|
|
352
|
+
return (this.pendingFiles[this.chat] ||= []);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
handlePaste(text) {
|
|
356
|
+
// Some terminals send an empty paste when the clipboard holds only an image: read it ourselves.
|
|
357
|
+
if (!text) return void this.pasteFromClipboard();
|
|
358
|
+
const files = parseDroppedFiles(text);
|
|
359
|
+
if (files) return this.attach(files);
|
|
360
|
+
this.insertText(text);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Terminals without bracketed paste "type" a dropped path one character at a time.
|
|
365
|
+
* Shortly after typing stops, check whether the box holds nothing but file paths.
|
|
366
|
+
*/
|
|
367
|
+
checkTypedPath() {
|
|
368
|
+
clearTimeout(this.pathTimer);
|
|
369
|
+
this.pathTimer = setTimeout(() => {
|
|
370
|
+
const inList = this.focus === 'list';
|
|
371
|
+
const text = inList ? this.filter : this.input.join('');
|
|
372
|
+
if (!looksLikePath(text)) return;
|
|
373
|
+
const files = parseDroppedFiles(text);
|
|
374
|
+
if (!files) return;
|
|
375
|
+
if (inList) this.filter = '';
|
|
376
|
+
else { this.input = []; this.cursor = 0; }
|
|
377
|
+
this.attach(files);
|
|
378
|
+
this.scheduleRender();
|
|
379
|
+
}, 30);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async pasteFromClipboard() {
|
|
383
|
+
if (!this.chat) return this.flash('Open a chat first, then paste', S.red);
|
|
384
|
+
if (this.clipBusy) return;
|
|
385
|
+
this.clipBusy = true;
|
|
386
|
+
this.flash('Reading the clipboardβ¦', S.gray);
|
|
387
|
+
try {
|
|
388
|
+
this.attach(await filesFromClipboard());
|
|
389
|
+
} catch (err) {
|
|
390
|
+
logger.warn({ err }, 'clipboard paste failed');
|
|
391
|
+
this.flash(err.message, S.red);
|
|
392
|
+
} finally {
|
|
393
|
+
this.clipBusy = false;
|
|
394
|
+
this.scheduleRender();
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
attach(files) {
|
|
399
|
+
if (!this.chat) return this.flash('Open a chat first, then drop the file into it', S.red);
|
|
400
|
+
let added = 0;
|
|
401
|
+
for (const f of files) {
|
|
402
|
+
if (this.attachments.some((a) => a.path === f.path)) continue;
|
|
403
|
+
try {
|
|
404
|
+
this.attachments.push(describe(f));
|
|
405
|
+
added++;
|
|
406
|
+
} catch (err) {
|
|
407
|
+
this.flash(err.message, S.red);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
this.focus = 'input';
|
|
411
|
+
if (added) this.flash(`Attached ${added === 1 ? this.attachments.at(-1).name : `${added} files`}. Add a caption if you like, then Enter to send`, S.green);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
insertText(text) {
|
|
415
|
+
if (this.focus === 'list') {
|
|
416
|
+
// Pasting into the list searches.
|
|
417
|
+
this.filter += text.replace(/\n/g, ' ');
|
|
418
|
+
this.selected = 0;
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const gs = graphemes(text);
|
|
422
|
+
this.input.splice(this.cursor, 0, ...gs);
|
|
423
|
+
this.cursor += gs.length;
|
|
424
|
+
this.onTyped();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
deleteWord() {
|
|
428
|
+
let i = this.cursor;
|
|
429
|
+
while (i > 0 && /\s/.test(this.input[i - 1])) i--;
|
|
430
|
+
while (i > 0 && !/\s/.test(this.input[i - 1])) i--;
|
|
431
|
+
this.input.splice(i, this.cursor - i);
|
|
432
|
+
this.cursor = i;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Shows "typingβ¦" to the other person while you write, like the phone app does. */
|
|
436
|
+
onTyped() {
|
|
437
|
+
if (!this.chat) return;
|
|
438
|
+
const t = this.typing;
|
|
439
|
+
if (!this.input.length || this.input[0] === '/') return this.stopTyping();
|
|
440
|
+
if (t.chat !== this.chat || Date.now() - t.at > 10000) {
|
|
441
|
+
wa.sendTyping(this.chat, true);
|
|
442
|
+
Object.assign(t, { chat: this.chat, at: Date.now() });
|
|
443
|
+
}
|
|
444
|
+
clearTimeout(t.timer);
|
|
445
|
+
t.timer = setTimeout(() => this.stopTyping(), 5000);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
stopTyping() {
|
|
449
|
+
const t = this.typing;
|
|
450
|
+
clearTimeout(t.timer);
|
|
451
|
+
if (t.chat) wa.sendTyping(t.chat, false);
|
|
452
|
+
t.chat = null;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async submit() {
|
|
456
|
+
const raw = this.input.join('');
|
|
457
|
+
const text = raw.trim();
|
|
458
|
+
if (this.sending) return this.flash('Still sending, one momentβ¦', S.gray);
|
|
459
|
+
if (text.startsWith('/') && !text.startsWith('//')) return this.command(text);
|
|
460
|
+
if (this.attachments.length) return this.sendAttachments(text.startsWith('//') ? text.slice(1) : text);
|
|
461
|
+
if (!text) return;
|
|
462
|
+
// Safety net: never send a dropped file's path as a message if the drop wasn't caught earlier.
|
|
463
|
+
const dropped = looksLikePath(text) && parseDroppedFiles(text);
|
|
464
|
+
if (dropped && this.chat) {
|
|
465
|
+
this.input = [];
|
|
466
|
+
this.cursor = 0;
|
|
467
|
+
return this.attach(dropped);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
if (!this.chat) return this.flash('Open a chat first (Tab to the list)', S.red);
|
|
471
|
+
const message = text.startsWith('//') ? text.slice(1) : text;
|
|
472
|
+
const chat = this.chat;
|
|
473
|
+
this.input = [];
|
|
474
|
+
this.cursor = 0;
|
|
475
|
+
this.scroll = 0;
|
|
476
|
+
this.stopTyping();
|
|
477
|
+
try {
|
|
478
|
+
await wa.sendText(chat, message);
|
|
479
|
+
} catch (err) {
|
|
480
|
+
logger.warn({ err }, 'send failed');
|
|
481
|
+
this.flash(err instanceof wa.UserError ? err.message : `Not sent: ${err.message}`, S.red);
|
|
482
|
+
if (!this.input.length) { this.input = graphemes(raw); this.cursor = this.input.length; }
|
|
483
|
+
}
|
|
484
|
+
this.scheduleRender();
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Sends the attached files one by one; the caption goes with the first. */
|
|
488
|
+
async sendAttachments(caption) {
|
|
489
|
+
const chat = this.chat;
|
|
490
|
+
const queue = this.attachments;
|
|
491
|
+
const total = queue.length;
|
|
492
|
+
this.sending = true;
|
|
493
|
+
this.stopTyping();
|
|
494
|
+
this.scroll = 0;
|
|
495
|
+
let n = 0;
|
|
496
|
+
try {
|
|
497
|
+
while (queue.length) {
|
|
498
|
+
const att = queue[0];
|
|
499
|
+
n++;
|
|
500
|
+
this.flash(`Sending ${total > 1 ? `${n}/${total} ` : ''}${att.name}β¦`, S.gray);
|
|
501
|
+
await wa.sendFile(chat, att, n === 1 ? caption : '');
|
|
502
|
+
discardTemp(queue.shift());
|
|
503
|
+
if (n === 1 && this.chat === chat) { this.input = []; this.cursor = 0; } // caption went out
|
|
504
|
+
}
|
|
505
|
+
this.flash(total > 1 ? `Sent ${total} files` : 'Sent', S.green);
|
|
506
|
+
} catch (err) {
|
|
507
|
+
logger.warn({ err }, 'file send failed');
|
|
508
|
+
this.flash(`Couldn't send ${queue[0]?.name ?? 'the file'}: ${err.message}`, S.red);
|
|
509
|
+
} finally {
|
|
510
|
+
this.sending = false;
|
|
511
|
+
this.scheduleRender();
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async command(text) {
|
|
516
|
+
const [cmd, ...rest] = text.split(/\s+/);
|
|
517
|
+
const arg = text.slice(cmd.length).trim();
|
|
518
|
+
const clear = () => { this.input = []; this.cursor = 0; };
|
|
519
|
+
switch (cmd.toLowerCase()) {
|
|
520
|
+
case '/help': case '/?':
|
|
521
|
+
clear(); this.help = true; break;
|
|
522
|
+
case '/quit': case '/exit': case '/q':
|
|
523
|
+
clear(); this.onQuit(); break;
|
|
524
|
+
case '/new': case '/chat':
|
|
525
|
+
if (!rest.length) return this.flash('Usage: /new 919876543210', S.red);
|
|
526
|
+
clear(); await this.startNewChat(arg); break;
|
|
527
|
+
case '/open':
|
|
528
|
+
clear();
|
|
529
|
+
await this.openPhoto(arg ? Number(arg.replace('#', '')) : undefined);
|
|
530
|
+
break;
|
|
531
|
+
case '/name':
|
|
532
|
+
if (!this.chat) return this.flash('Open a chat first', S.red);
|
|
533
|
+
store.setAlias(this.chat, arg || null);
|
|
534
|
+
clear();
|
|
535
|
+
this.flash(arg ? `Named ${formatJid(this.chat)} "${arg}"` : 'Name removed', S.green);
|
|
536
|
+
break;
|
|
537
|
+
case '/logout':
|
|
538
|
+
clear();
|
|
539
|
+
try {
|
|
540
|
+
this.flash('Logging outβ¦', S.gray);
|
|
541
|
+
await wa.logout();
|
|
542
|
+
} catch (err) {
|
|
543
|
+
this.flash(err.message, S.red);
|
|
544
|
+
}
|
|
545
|
+
break;
|
|
546
|
+
default:
|
|
547
|
+
this.flash(`Unknown command ${cmd}. Type /help (or //text to send it as a message)`, S.red);
|
|
548
|
+
}
|
|
549
|
+
this.scheduleRender();
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Opens photo #n of this chat (default: the latest) in the system image viewer, downloading it first if needed. */
|
|
553
|
+
async openPhoto(n) {
|
|
554
|
+
if (!this.chat) return this.flash('Open a chat first', S.red);
|
|
555
|
+
const photos = store.history(this.chat).filter((m) => m.photo);
|
|
556
|
+
if (!photos.length) return this.flash('No photos in this chat', S.red);
|
|
557
|
+
if (n !== undefined && !(Number.isInteger(n) && n >= 1 && n <= photos.length)) {
|
|
558
|
+
return this.flash(`Use /open 1 to /open ${photos.length}`, S.red);
|
|
559
|
+
}
|
|
560
|
+
const no = n ?? photos.length;
|
|
561
|
+
const entry = photos[no - 1];
|
|
562
|
+
try {
|
|
563
|
+
if (entry.photo.status !== 'ready') this.flash(`Downloading photo #${no}β¦`, S.gray);
|
|
564
|
+
const file = await wa.downloadPhoto(entry);
|
|
565
|
+
wa.openFile(file);
|
|
566
|
+
this.flash(`Opened photo #${no}`, S.green);
|
|
567
|
+
} catch (err) {
|
|
568
|
+
this.flash(err.message, S.red);
|
|
569
|
+
}
|
|
570
|
+
this.scheduleRender();
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
cycleChat(dir) {
|
|
574
|
+
const items = this.listItems().filter((it) => it.type === 'chat');
|
|
575
|
+
if (!items.length) return;
|
|
576
|
+
const cur = items.findIndex((it) => it.id === this.chat);
|
|
577
|
+
const next = items[(cur + dir + items.length) % items.length];
|
|
578
|
+
this.openChat(next.id, { focus: this.focus });
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
scrollBy(n) {
|
|
582
|
+
this.scroll = Math.max(0, this.scroll + n); // upper bound is applied while rendering
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// ---------------- layout ----------------
|
|
586
|
+
layout() {
|
|
587
|
+
const cols = Math.max(20, this.out.columns || 80);
|
|
588
|
+
const rows = Math.max(8, this.out.rows || 24);
|
|
589
|
+
const top = 2; // row 1 = title bar
|
|
590
|
+
const bottom = rows - 2; // rows-1 = rule, rows = input
|
|
591
|
+
const height = bottom - top + 1;
|
|
592
|
+
if (cols < 70) {
|
|
593
|
+
// Narrow terminal: one pane at a time.
|
|
594
|
+
const showList = this.focus === 'list' || !this.chat;
|
|
595
|
+
return { cols, rows, top, height, list: showList ? { x: 1, w: cols } : null, msgs: showList ? null : { x: 1, w: cols } };
|
|
596
|
+
}
|
|
597
|
+
const lw = Math.min(38, Math.max(24, Math.floor(cols * 0.3)));
|
|
598
|
+
return { cols, rows, top, height, list: { x: 1, w: lw }, sep: lw + 1, msgs: { x: lw + 2, w: cols - lw - 1 } };
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
msgHeight() {
|
|
602
|
+
return Math.max(1, this.layout().height - 2);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// ---------------- rendering ----------------
|
|
606
|
+
render() {
|
|
607
|
+
if (!this.active) return;
|
|
608
|
+
const L = this.layout();
|
|
609
|
+
const rows = Array.from({ length: L.rows }, () => []);
|
|
610
|
+
const put = (r, x, text) => { if (r >= 1 && r <= L.rows) rows[r - 1].push([x, text]); };
|
|
611
|
+
this.frameImages = []; // photo previews placed by renderMessages
|
|
612
|
+
|
|
613
|
+
this.renderTitle(put, L);
|
|
614
|
+
// Side by side, the chat list runs to the bottom and the input sits under the conversation.
|
|
615
|
+
L.input = L.msgs && L.list ? L.msgs : { x: 1, w: L.cols };
|
|
616
|
+
if (L.list) this.renderList(put, L.list.x, L.list.w, L.top, L.height + (L.sep ? 2 : 0));
|
|
617
|
+
if (L.sep) for (let r = L.top; r <= L.rows; r++) put(r, L.sep, paint(S.gray, 'β'));
|
|
618
|
+
if (L.msgs) {
|
|
619
|
+
if (this.help) this.renderHelp(put, L.msgs.x, L.msgs.w, L.top, L.height);
|
|
620
|
+
else this.renderMessages(put, L.msgs.x, L.msgs.w, L.top, L.height);
|
|
621
|
+
} else if (this.help) {
|
|
622
|
+
this.renderHelp(put, 1, L.cols, L.top, L.height);
|
|
623
|
+
}
|
|
624
|
+
this.renderAttachments(put, L.rows - 1, L.input.x, L.input.w);
|
|
625
|
+
const cursor = this.renderInput(put, L);
|
|
626
|
+
|
|
627
|
+
// Rows a photo covers carry its id in their key, so they get cleared when it moves away.
|
|
628
|
+
const rowTags = new Array(L.rows).fill('');
|
|
629
|
+
for (const im of this.frameImages) {
|
|
630
|
+
for (let k = 0; k < im.count; k++) rowTags[im.r - 1 + k] += `${im.pkey}@${im.c}/${im.from};`;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Write only the rows that changed.
|
|
634
|
+
let buf = '\x1b[?2026h\x1b[?25l';
|
|
635
|
+
const rewritten = new Set();
|
|
636
|
+
rows.forEach((parts, i) => {
|
|
637
|
+
const line = parts.map(([x, t]) => `\x1b[${i + 1};${x}H${t}`).join('');
|
|
638
|
+
const key = rowTags[i] ? `${line}\0${rowTags[i]}` : line;
|
|
639
|
+
if (this.prevRows[i] !== key) {
|
|
640
|
+
buf += `\x1b[${i + 1};1H\x1b[2K${line}${S.reset}`;
|
|
641
|
+
this.prevRows[i] = key;
|
|
642
|
+
rewritten.add(i + 1);
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
|
|
646
|
+
// Draw photos that are new here, or whose rows were just cleared by a rewrite.
|
|
647
|
+
const drawn = new Set();
|
|
648
|
+
for (const im of this.frameImages) {
|
|
649
|
+
const sig = `${im.pkey}@${im.r},${im.c}/${im.from}+${im.count}`;
|
|
650
|
+
let needed = !this.drawnImages?.has(sig);
|
|
651
|
+
for (let k = 0; k < im.count && !needed; k++) if (rewritten.has(im.r + k)) needed = true;
|
|
652
|
+
if (needed) {
|
|
653
|
+
const six = this.sixelFor(im);
|
|
654
|
+
if (!six) continue; // not ready yet: try again next frame
|
|
655
|
+
buf += `\x1b[${im.r};${im.c}H${six}`;
|
|
656
|
+
}
|
|
657
|
+
drawn.add(sig);
|
|
658
|
+
}
|
|
659
|
+
this.drawnImages = drawn;
|
|
660
|
+
|
|
661
|
+
if (cursor) buf += `\x1b[${cursor.r};${cursor.c}H\x1b[?25h`;
|
|
662
|
+
buf += '\x1b[?2026l';
|
|
663
|
+
const unread = store.totalUnread();
|
|
664
|
+
const title = unread ? `(${unread}) wacli` : 'wacli';
|
|
665
|
+
if (title !== this.lastTitle) { buf += `\x1b]0;${title}\x07`; this.lastTitle = title; }
|
|
666
|
+
this.out.write(buf);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
renderTitle(put, L) {
|
|
670
|
+
const st = wa.state;
|
|
671
|
+
let status;
|
|
672
|
+
if (st.status === 'open') {
|
|
673
|
+
const me = st.me ? `${st.me.name ? st.me.name + ' ' : ''}${formatJid(st.me.id)}` : '';
|
|
674
|
+
status = `β ${me}`;
|
|
675
|
+
if (this.sync != null) status += ` Β· syncing history ${Math.round(this.sync)}%`;
|
|
676
|
+
} else if (st.status === 'qr' || st.status === 'logged_out') status = 'β Logged out';
|
|
677
|
+
else status = 'β Reconnectingβ¦';
|
|
678
|
+
const left = ` wacli ${status}`;
|
|
679
|
+
const right = this.flashMsg ? '' : L.cols < 80 ? 'F1 help Β· Esc back ' : 'F1 help Β· Tab switch Β· Ctrl+C quit ';
|
|
680
|
+
const rightW = width(right);
|
|
681
|
+
put(1, 1, paint(S.bar, fit(left, L.cols - rightW, { ellipsis: true }) + right));
|
|
682
|
+
if (this.flashMsg) {
|
|
683
|
+
const msg = ` ${this.flashMsg.text} `;
|
|
684
|
+
const w = Math.min(width(msg), Math.max(10, L.cols - width(left) - 2));
|
|
685
|
+
put(1, L.cols - w + 1, paint(S.inverse + this.flashMsg.style, fit(msg, w)));
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
renderList(put, x, w, top, height) {
|
|
690
|
+
const focused = this.focus === 'list';
|
|
691
|
+
// Search row
|
|
692
|
+
let search;
|
|
693
|
+
if (this.filter) search = paint(S.bold, fit(` Search: ${this.filter}`, w));
|
|
694
|
+
else search = paint(S.gray, fit(focused ? ' Type to search or enter a number' : ` Chats (${Object.keys(store.chats).length})`, w));
|
|
695
|
+
put(top, x, search);
|
|
696
|
+
put(top + 1, x, paint(S.gray, 'β'.repeat(w)));
|
|
697
|
+
|
|
698
|
+
const items = this.listItems();
|
|
699
|
+
const per = 2;
|
|
700
|
+
const visible = Math.max(1, Math.floor((height - 2) / per));
|
|
701
|
+
if (this.selected < this.listScroll) this.listScroll = this.selected;
|
|
702
|
+
if (this.selected >= this.listScroll + visible) this.listScroll = this.selected - visible + 1;
|
|
703
|
+
this.listScroll = Math.max(0, Math.min(this.listScroll, Math.max(0, items.length - visible)));
|
|
704
|
+
|
|
705
|
+
if (!items.length) {
|
|
706
|
+
const msg = this.filter ? ' No matches' : wa.state.status === 'open' ? ' No chats yet. Waiting for historyβ¦' : ' Connectingβ¦';
|
|
707
|
+
put(top + 2, x, paint(S.gray, fit(msg, w)));
|
|
708
|
+
if (!this.filter) put(top + 3, x, paint(S.gray, fit(' Type a number to start a chat', w)));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
for (let i = 0; i < visible; i++) {
|
|
712
|
+
const it = items[this.listScroll + i];
|
|
713
|
+
if (!it) break;
|
|
714
|
+
const r = top + 2 + i * per;
|
|
715
|
+
const isSel = this.listScroll + i === this.selected;
|
|
716
|
+
const bg = isSel ? (focused ? S.selected : '') : '';
|
|
717
|
+
const marker = isSel ? paint(S.green + S.bold, 'β') : ' ';
|
|
718
|
+
|
|
719
|
+
if (it.type === 'new') {
|
|
720
|
+
put(r, x, marker + paint(bg + S.green, fit(` + New chat with +${it.number}`, w - 1)));
|
|
721
|
+
put(r + 1, x, ' ' + paint(bg + S.gray, fit(' press Enter', w - 1)));
|
|
722
|
+
continue;
|
|
723
|
+
}
|
|
724
|
+
const chat = store.chats[it.id];
|
|
725
|
+
const last = store.lastMessage(it.id);
|
|
726
|
+
const unread = chat.unread || 0;
|
|
727
|
+
const when = shortWhen(chat.lastTs || last?.ts);
|
|
728
|
+
const isOpen = it.id === this.chat;
|
|
729
|
+
|
|
730
|
+
const nameW = Math.max(1, w - 2 - width(when) - 1);
|
|
731
|
+
const nameStyle = unread ? S.bold : isOpen ? S.green : '';
|
|
732
|
+
put(r, x, marker + paint(bg + nameStyle, ' ' + fit(store.displayName(it.id), nameW)) + paint(bg + (unread ? S.green : S.gray), when + ' '));
|
|
733
|
+
|
|
734
|
+
const badge = unread ? ` ${unread > 99 ? '99+' : unread} ` : '';
|
|
735
|
+
let preview = '';
|
|
736
|
+
if (last) {
|
|
737
|
+
const tick = last.fromMe ? (TICKS[last.status ?? 2]?.[0] || '') + ' ' : '';
|
|
738
|
+
preview = tick + last.text.replace(/\s+/g, ' ');
|
|
739
|
+
}
|
|
740
|
+
const prevW = Math.max(1, w - 2 - width(badge) - (badge ? 1 : 0));
|
|
741
|
+
put(r + 1, x, ' ' + paint(bg + S.gray, ' ' + fit(preview, prevW)) + (badge ? paint(S.bar + S.bold, badge) + paint(bg, ' ') : ''));
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (items.length > visible) {
|
|
745
|
+
const more = this.listScroll + visible < items.length ? 'βΌ' : ' ';
|
|
746
|
+
put(top + height - 1, x + w - 1, paint(S.gray, more));
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// ---------------- inline photo previews (sixel) ----------------
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Size (in cells) of a photo's inline preview, starting its generation if needed.
|
|
754
|
+
* Returns null when there's no preview to show (not supported, not downloaded, failed).
|
|
755
|
+
*/
|
|
756
|
+
previewFor(entry, w) {
|
|
757
|
+
if (!graphics.sixel || entry.photo?.status !== 'ready' || !entry.photo.file) return null;
|
|
758
|
+
const maxCols = Math.max(8, Math.min(48, Math.floor(w * 0.6)));
|
|
759
|
+
const maxRows = Math.max(3, Math.min(12, Math.floor(this.msgHeight() * 0.6)));
|
|
760
|
+
const pkey = `${entry.id}|${maxCols}|${maxRows}`;
|
|
761
|
+
let p = this.previews.get(pkey);
|
|
762
|
+
if (!p) {
|
|
763
|
+
p = { state: 'loading' };
|
|
764
|
+
this.previews.set(pkey, p);
|
|
765
|
+
if (this.previews.size > 300) this.previews.delete(this.previews.keys().next().value);
|
|
766
|
+
makePreview(path.join(MEDIA_DIR, entry.photo.file), maxCols, maxRows)
|
|
767
|
+
.then((img) => { p.state = 'ready'; p.img = img; })
|
|
768
|
+
.catch((err) => { p.state = 'failed'; logger.warn({ err, id: entry.id }, 'preview failed'); })
|
|
769
|
+
.finally(() => this.scheduleRender());
|
|
770
|
+
}
|
|
771
|
+
if (p.state === 'failed') return null;
|
|
772
|
+
if (p.state === 'ready') return { pkey, cols: p.img.cols, rows: p.img.rows };
|
|
773
|
+
// Not ready yet: make room using the size WhatsApp told us, so the chat doesn't jump.
|
|
774
|
+
const est = previewCells(entry.photo.w, entry.photo.h, maxCols, maxRows);
|
|
775
|
+
return est && { pkey, ...est };
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** Sixel data for a placed preview (cropped if partly scrolled out), or null if not ready. */
|
|
779
|
+
sixelFor(im) {
|
|
780
|
+
const p = this.previews.get(im.pkey);
|
|
781
|
+
if (p?.state !== 'ready') return null;
|
|
782
|
+
const key = `${im.pkey}|${im.from}|${im.count}`;
|
|
783
|
+
let six = this.sixelCache.get(key);
|
|
784
|
+
if (six === undefined) {
|
|
785
|
+
six = encodeSixel(p.img, im.from, im.count);
|
|
786
|
+
this.sixelCache.set(key, six);
|
|
787
|
+
if (this.sixelCache.size > 60) this.sixelCache.delete(this.sixelCache.keys().next().value);
|
|
788
|
+
}
|
|
789
|
+
return six;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Display lines for one message: [{ indent, parts: [[style, text]] }]. Cached. */
|
|
793
|
+
messageLines(m, w, photoNo = 0) {
|
|
794
|
+
const pv = m.photo ? this.previewFor(m, w) : null;
|
|
795
|
+
const keyStr = `${m.id}|${w}|${m.status}|${m.text.length}|${photoNo}|${m.photo?.status}|${pv ? `${pv.pkey}:${pv.cols}x${pv.rows}` : ''}`;
|
|
796
|
+
const cached = this.lineCache.get(keyStr);
|
|
797
|
+
if (cached) return cached;
|
|
798
|
+
|
|
799
|
+
const maxW = Math.max(16, Math.floor(w * 0.75));
|
|
800
|
+
const meta = timeOf(m.ts);
|
|
801
|
+
const tick = m.fromMe ? TICKS[m.status ?? 2] : null;
|
|
802
|
+
const metaW = width(meta) + (tick ? 1 + width(tick[0]) : 0);
|
|
803
|
+
const textStyle = m.fromMe ? S.green : m.media ? S.cyan : '';
|
|
804
|
+
|
|
805
|
+
// Photos get a number to open them by, and a line saying where the download is at.
|
|
806
|
+
let text = m.text;
|
|
807
|
+
let tag = null;
|
|
808
|
+
if (m.photo && photoNo) {
|
|
809
|
+
text = text.replace(/^π· Photo/, `π· Photo #${photoNo}`);
|
|
810
|
+
tag = {
|
|
811
|
+
ready: pv ? `/open ${photoNo} for full size` : `/open ${photoNo} to view`,
|
|
812
|
+
downloading: 'downloadingβ¦',
|
|
813
|
+
remote: `/open ${photoNo} to download and view`,
|
|
814
|
+
failed: `download failed Β· /open ${photoNo} to retry`,
|
|
815
|
+
}[m.photo.status] || null;
|
|
816
|
+
}
|
|
817
|
+
const styled = wrap(text, maxW).map((t) => [textStyle, t]);
|
|
818
|
+
if (tag) styled.push(...wrap(tag, maxW).map((t) => [S.gray, t]));
|
|
819
|
+
const textLines = styled.map(([, t]) => t);
|
|
820
|
+
const lastW = width(textLines[textLines.length - 1]);
|
|
821
|
+
const metaInline = lastW + 2 + metaW <= maxW;
|
|
822
|
+
const blockW = Math.max(...textLines.map(width), metaInline ? lastW + 2 + metaW : metaW, pv ? pv.cols : 0);
|
|
823
|
+
const indent = m.fromMe ? Math.max(0, w - 1 - blockW) : 1;
|
|
824
|
+
|
|
825
|
+
const metaParts = [[S.gray, meta], ...(tick ? [[S.gray, ' '], [tick[1], tick[0]]] : [])];
|
|
826
|
+
const lines = styled.map(([style, t]) => ({ indent, parts: [[style, t]] }));
|
|
827
|
+
// The photo itself goes above its caption: blank rows that the preview is drawn over.
|
|
828
|
+
if (pv) {
|
|
829
|
+
const imgIndent = m.fromMe ? indent + blockW - pv.cols : indent; // your photos hug the right edge
|
|
830
|
+
const imageRows = Array.from({ length: pv.rows }, (_, row) => ({ indent: imgIndent, parts: [], image: { pkey: pv.pkey, row, rows: pv.rows } }));
|
|
831
|
+
lines.unshift(...imageRows);
|
|
832
|
+
}
|
|
833
|
+
const last = lines[lines.length - 1];
|
|
834
|
+
if (metaInline) {
|
|
835
|
+
// Right-align the time inside the bubble, like the phone does.
|
|
836
|
+
last.parts.push(['', ' '.repeat(blockW - lastW - metaW)], ...metaParts);
|
|
837
|
+
} else {
|
|
838
|
+
lines.push({ indent: indent + blockW - metaW, parts: metaParts });
|
|
839
|
+
}
|
|
840
|
+
if (this.lineCache.size > 5000) this.lineCache.clear();
|
|
841
|
+
this.lineCache.set(keyStr, lines);
|
|
842
|
+
return lines;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
renderMessages(put, x, w, top, height) {
|
|
846
|
+
if (!this.chat) {
|
|
847
|
+
const lines = [
|
|
848
|
+
'',
|
|
849
|
+
paint(S.bold, 'Welcome to wacli'),
|
|
850
|
+
'',
|
|
851
|
+
'Pick a chat on the left with β/β and Enter,',
|
|
852
|
+
'or type a phone number with country code to start one.',
|
|
853
|
+
'',
|
|
854
|
+
paint(S.gray, 'F1 or /help shows all keys and commands.'),
|
|
855
|
+
];
|
|
856
|
+
lines.forEach((l, i) => put(top + 1 + i, x + 2, l));
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// Header
|
|
861
|
+
const name = store.displayName(this.chat);
|
|
862
|
+
const num = formatJid(this.chat);
|
|
863
|
+
const p = this.presence[this.chat];
|
|
864
|
+
const pres = p === 'composing' ? 'typingβ¦' : p === 'recording' ? 'recording audioβ¦' : p === 'available' ? 'online' : '';
|
|
865
|
+
let header = ' ' + paint(S.bold, name);
|
|
866
|
+
let hw = 1 + width(name);
|
|
867
|
+
if (num !== name) { header += paint(S.gray, ' ' + num); hw += 2 + width(num); }
|
|
868
|
+
if (pres) { header += paint(S.green, ' ' + pres); hw += 2 + width(pres); }
|
|
869
|
+
put(top, x, hw > w ? paint(S.bold, ' ' + fit(name, w - 1)) : header);
|
|
870
|
+
put(top + 1, x, paint(S.gray, 'β'.repeat(w)));
|
|
871
|
+
|
|
872
|
+
// Messages, bottom-aligned
|
|
873
|
+
const msgH = height - 2;
|
|
874
|
+
const lines = [];
|
|
875
|
+
let lastDay = null;
|
|
876
|
+
let photoNo = 0;
|
|
877
|
+
for (const m of store.history(this.chat)) {
|
|
878
|
+
if (m.photo) photoNo++;
|
|
879
|
+
const d = dayKey(m.ts);
|
|
880
|
+
if (d !== lastDay) {
|
|
881
|
+
if (lines.length) lines.push(null);
|
|
882
|
+
const label = ` ${dayLabel(m.ts)} `;
|
|
883
|
+
const side = Math.max(0, Math.floor((w - width(label)) / 2));
|
|
884
|
+
lines.push({ indent: side, parts: [[S.gray, label]] });
|
|
885
|
+
lastDay = d;
|
|
886
|
+
}
|
|
887
|
+
lines.push(null); // blank line between messages
|
|
888
|
+
lines.push(...this.messageLines(m, w, m.photo ? photoNo : 0));
|
|
889
|
+
}
|
|
890
|
+
if (!store.history(this.chat).length) {
|
|
891
|
+
lines.push(null, { indent: 2, parts: [[S.gray, 'No messages here yet. Say hi π']] });
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const maxScroll = Math.max(0, lines.length - msgH);
|
|
895
|
+
this.scroll = Math.min(this.scroll, maxScroll);
|
|
896
|
+
const end = lines.length - this.scroll;
|
|
897
|
+
const start = Math.max(0, end - msgH);
|
|
898
|
+
const view = lines.slice(start, end);
|
|
899
|
+
const offset = msgH - view.length;
|
|
900
|
+
// Where each visible photo lands, and which of its rows are on screen (it may be cut off at the top or bottom).
|
|
901
|
+
const placed = new Map();
|
|
902
|
+
view.forEach((line, i) => {
|
|
903
|
+
if (!line?.image) return;
|
|
904
|
+
const r = top + 2 + offset + i;
|
|
905
|
+
const im = placed.get(line.image.pkey);
|
|
906
|
+
if (im) im.count++;
|
|
907
|
+
else placed.set(line.image.pkey, { pkey: line.image.pkey, r, c: x + line.indent, from: line.image.row, count: 1 });
|
|
908
|
+
});
|
|
909
|
+
this.frameImages.push(...placed.values());
|
|
910
|
+
view.forEach((line, i) => {
|
|
911
|
+
if (!line || line.image) return;
|
|
912
|
+
put(top + 2 + offset + i, x + line.indent, line.parts.map(([s, t]) => paint(s, t)).join(''));
|
|
913
|
+
});
|
|
914
|
+
if (this.scroll > 0) {
|
|
915
|
+
const hint = ` β ${this.scroll} more lines (PgDn) `;
|
|
916
|
+
put(top + height - 1, x + Math.max(0, w - width(hint) - 1), paint(S.inverse, hint));
|
|
917
|
+
}
|
|
918
|
+
if (start > 0 && this.scroll === maxScroll && maxScroll > 0) {
|
|
919
|
+
put(top + 2, x + Math.max(0, Math.floor((w - 22) / 2)), paint(S.gray, '(start of saved history)'));
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
renderHelp(put, x, w, top, height) {
|
|
924
|
+
put(top, x, paint(S.bold, fit(' Help', w)));
|
|
925
|
+
put(top + 1, x, paint(S.gray, 'β'.repeat(w)));
|
|
926
|
+
const keyW = 18;
|
|
927
|
+
const rows = HELP.length > height - 3 ? HELP.filter(([k, d]) => k || d) : HELP; // drop spacing when short
|
|
928
|
+
rows.slice(0, height - 3).forEach(([k, d], i) => {
|
|
929
|
+
const r = top + 2 + i;
|
|
930
|
+
if (!d && k) put(r, x + 1, paint(S.bold + S.green, k));
|
|
931
|
+
else if (k || d) put(r, x + 1, paint(S.cyan, fit(k, keyW)) + fit(d, Math.max(1, w - keyW - 2)));
|
|
932
|
+
});
|
|
933
|
+
put(top + height - 1, x + 1, paint(S.gray, 'Press any key to close'));
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** The line above the message box: a plain rule, or the files waiting to be sent. */
|
|
937
|
+
renderAttachments(put, r, x, w) {
|
|
938
|
+
const atts = this.attachments;
|
|
939
|
+
if (!atts.length) return put(r, x, paint(S.gray, 'β'.repeat(w)));
|
|
940
|
+
let line = paint(S.gray, 'β ') + 'π ';
|
|
941
|
+
let used = 5;
|
|
942
|
+
for (let i = 0; i < atts.length; i++) {
|
|
943
|
+
const a = atts[i];
|
|
944
|
+
const chip = ` ${KIND_ICON[a.kind]} ${a.name} ${formatSize(a.size)} `;
|
|
945
|
+
const left = atts.length - i - 1;
|
|
946
|
+
const reserve = left ? width(` +${left} more`) : 0;
|
|
947
|
+
let chipW = width(chip);
|
|
948
|
+
if (used + chipW + 1 + reserve > w) {
|
|
949
|
+
chipW = w - used - 1 - reserve;
|
|
950
|
+
if (chipW < 12) { // no room for even a short name
|
|
951
|
+
line += paint(S.gray, ` +${atts.length - i} more`);
|
|
952
|
+
used += width(` +${atts.length - i} more`);
|
|
953
|
+
break;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
line += paint(S.inverse, fit(chip, chipW)) + ' ';
|
|
957
|
+
used += chipW + 1;
|
|
958
|
+
if (chipW < width(chip) && left) {
|
|
959
|
+
line += paint(S.gray, `+${left} more`);
|
|
960
|
+
used += width(`+${left} more`);
|
|
961
|
+
break;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
if (used < w) line += paint(S.gray, 'β'.repeat(w - used));
|
|
965
|
+
put(r, x, line);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
renderInput(put, L) {
|
|
969
|
+
const r = L.rows;
|
|
970
|
+
const { x, w } = L.input;
|
|
971
|
+
if (this.focus !== 'input' || !this.chat) {
|
|
972
|
+
const hint = this.chat
|
|
973
|
+
? ' ββ choose Β· Enter open Β· Tab back to the message box Β· F1 help'
|
|
974
|
+
: ' ββ choose a chat Β· Enter open Β· type to search Β· F1 help';
|
|
975
|
+
put(r, x, paint(S.gray, fit(hint, w)));
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
const prompt = ' βΊ ';
|
|
979
|
+
const avail = Math.max(4, w - width(prompt) - 1);
|
|
980
|
+
const shown = this.input.map((g) => (g === '\n' ? 'β΅' : g));
|
|
981
|
+
const widths = shown.map(width);
|
|
982
|
+
// Keep the cursor visible by scrolling the line sideways.
|
|
983
|
+
if (this.cursor < this.inputScroll) this.inputScroll = this.cursor;
|
|
984
|
+
const span = (a, b) => widths.slice(a, b).reduce((s, n) => s + n, 0);
|
|
985
|
+
while (this.inputScroll < this.cursor && span(this.inputScroll, this.cursor) > avail - 1) this.inputScroll++;
|
|
986
|
+
let used = 0;
|
|
987
|
+
let text = '';
|
|
988
|
+
for (let i = this.inputScroll; i < shown.length && used + widths[i] <= avail; i++) {
|
|
989
|
+
text += shown[i] === 'β΅' ? paint(S.gray, 'β΅') : shown[i];
|
|
990
|
+
used += widths[i];
|
|
991
|
+
}
|
|
992
|
+
if (!shown.length) {
|
|
993
|
+
text = paint(S.gray, this.attachments.length
|
|
994
|
+
? 'Add a caption (optional) Β· Enter send Β· Backspace remove file'
|
|
995
|
+
: `Message ${store.displayName(this.chat)} Β· drop a file or ${PASTE_KEY} to paste an image`);
|
|
996
|
+
}
|
|
997
|
+
put(r, x, paint(S.green + S.bold, prompt) + text);
|
|
998
|
+
return { r, c: x + width(prompt) + span(this.inputScroll, this.cursor) };
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** Pasted images and GIFs are downloaded to a temp folder; delete them once sent or removed. */
|
|
1003
|
+
function discardTemp(att) {
|
|
1004
|
+
if (att?.path && path.resolve(att.path).startsWith(TMP_DIR + path.sep)) rmSync(att.path, { force: true });
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function isPrintable(str, key) {
|
|
1008
|
+
if (!str || key.ctrl || key.meta) return false;
|
|
1009
|
+
// eslint-disable-next-line no-control-regex
|
|
1010
|
+
return !/[\x00-\x1f\x7f]/.test(str);
|
|
1011
|
+
}
|