visendx 1.0.0 → 1.1.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/lib/cli.js +36 -2
- package/lib/commands/file.js +2 -3
- package/lib/commands/help.js +8 -0
- package/lib/commands/setup.js +107 -12
- package/lib/commands/text.js +13 -7
- package/lib/config.js +5 -0
- package/lib/errors.js +5 -2
- package/lib/output.js +15 -0
- package/lib/send.js +47 -15
- package/lib/telegram.js +15 -2
- package/package.json +3 -2
package/lib/cli.js
CHANGED
|
@@ -25,7 +25,7 @@ function usageError(argv) {
|
|
|
25
25
|
|
|
26
26
|
function parseArgs(argv) {
|
|
27
27
|
const positionals = [];
|
|
28
|
-
const flags = { yes: false, forceAsText: false, name: null, help: false, version: false };
|
|
28
|
+
const flags = { yes: false, forceAsText: false, stdin: false, json: false, quiet: false, name: null, help: false, version: false };
|
|
29
29
|
for (let i = 0; i < argv.length; i++) {
|
|
30
30
|
const a = argv[i];
|
|
31
31
|
if (a === '--') {
|
|
@@ -34,6 +34,12 @@ function parseArgs(argv) {
|
|
|
34
34
|
}
|
|
35
35
|
if (a === '-y' || a === '--yes') {
|
|
36
36
|
flags.yes = true;
|
|
37
|
+
} else if (a === '--stdin') {
|
|
38
|
+
flags.stdin = true;
|
|
39
|
+
} else if (a === '--json') {
|
|
40
|
+
flags.json = true;
|
|
41
|
+
} else if (a === '--quiet') {
|
|
42
|
+
flags.quiet = true;
|
|
37
43
|
} else if (a === '--force-as-text') {
|
|
38
44
|
flags.forceAsText = true;
|
|
39
45
|
} else if (a === '-h' || a === '--help') {
|
|
@@ -61,6 +67,15 @@ function parseArgs(argv) {
|
|
|
61
67
|
} else if (key === 'force-as-text') {
|
|
62
68
|
if (value !== 'true') throw new VisendError('--force-as-text does not take a value (use it on its own).');
|
|
63
69
|
flags.forceAsText = true;
|
|
70
|
+
} else if (key === 'stdin') {
|
|
71
|
+
if (value !== 'true') throw new VisendError('--stdin does not take a value (use it on its own).');
|
|
72
|
+
flags.stdin = true;
|
|
73
|
+
} else if (key === 'json') {
|
|
74
|
+
if (value !== 'true') throw new VisendError('--json does not take a value (use it on its own).');
|
|
75
|
+
flags.json = true;
|
|
76
|
+
} else if (key === 'quiet') {
|
|
77
|
+
if (value !== 'true') throw new VisendError('--quiet does not take a value (use it on its own).');
|
|
78
|
+
flags.quiet = true;
|
|
64
79
|
} else throw new VisendError('Unknown flag "--' + key + '". Run `visend help`.');
|
|
65
80
|
} else if (a.indexOf('-') === 0 && a.length > 1 && !(a === '-')) {
|
|
66
81
|
throw new VisendError('Unknown flag "' + a + '". Run `visend help`.');
|
|
@@ -68,14 +83,24 @@ function parseArgs(argv) {
|
|
|
68
83
|
positionals.push(a);
|
|
69
84
|
}
|
|
70
85
|
}
|
|
86
|
+
if (flags.json && flags.quiet) {
|
|
87
|
+
throw new VisendError('--json and --quiet are mutually exclusive.');
|
|
88
|
+
}
|
|
71
89
|
return { positionals: positionals, flags: flags };
|
|
72
90
|
}
|
|
73
91
|
|
|
92
|
+
// Output mode for the failure handler in entry(): set once the flags are
|
|
93
|
+
// parsed, so errors after parsing honor --json / --quiet too.
|
|
94
|
+
let jsonMode = false;
|
|
95
|
+
let quietMode = false;
|
|
96
|
+
|
|
74
97
|
async function main() {
|
|
75
98
|
const argv = process.argv.slice(2);
|
|
76
99
|
const parsed = parseArgs(argv);
|
|
77
100
|
const positionals = parsed.positionals;
|
|
78
101
|
const flags = parsed.flags;
|
|
102
|
+
jsonMode = flags.json;
|
|
103
|
+
quietMode = flags.quiet;
|
|
79
104
|
|
|
80
105
|
if (flags.version) {
|
|
81
106
|
process.stdout.write('visend ' + VERSION + '\n');
|
|
@@ -117,8 +142,17 @@ function entry() {
|
|
|
117
142
|
const msg = err && err.name === 'VisendError'
|
|
118
143
|
? err.message
|
|
119
144
|
: (err && err.stack ? err.stack : String(err));
|
|
120
|
-
process.stderr.write('Error: ' + msg + '\n');
|
|
121
145
|
process.exitCode = 1;
|
|
146
|
+
if (jsonMode) {
|
|
147
|
+
// One JSON line on stdout; the error text never contains the token.
|
|
148
|
+
// A stray newline in a raw message must not break the one-line contract.
|
|
149
|
+
const payload = { ok: false, error: msg.replace(/\s*\r?\n\s*/g, ' ') };
|
|
150
|
+
if (err && err.kind) payload.kind = err.kind;
|
|
151
|
+
process.stdout.write(JSON.stringify(payload) + '\n');
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (quietMode) return;
|
|
155
|
+
process.stderr.write('Error: ' + msg + '\n');
|
|
122
156
|
}
|
|
123
157
|
);
|
|
124
158
|
}
|
package/lib/commands/file.js
CHANGED
|
@@ -4,6 +4,7 @@ const fs = require('fs');
|
|
|
4
4
|
const path = require('path');
|
|
5
5
|
const send = require('../send');
|
|
6
6
|
const stdin = require('../stdin');
|
|
7
|
+
const output = require('../output');
|
|
7
8
|
const { VisendError } = require('../errors');
|
|
8
9
|
|
|
9
10
|
const TELEGRAM_FILE_LIMIT = 50 * 1024 * 1024;
|
|
@@ -70,9 +71,7 @@ async function run(args, flags) {
|
|
|
70
71
|
);
|
|
71
72
|
}
|
|
72
73
|
|
|
73
|
-
|
|
74
|
-
await send.deliverFile(cfg, buf, name) + '\n'
|
|
75
|
-
);
|
|
74
|
+
output.emitSendResult(await send.deliverFile(cfg, buf, name), flags);
|
|
76
75
|
}
|
|
77
76
|
|
|
78
77
|
module.exports = { run: run };
|
package/lib/commands/help.js
CHANGED
|
@@ -14,6 +14,8 @@ const HELP = [
|
|
|
14
14
|
' `visend file -` reads the file from stdin',
|
|
15
15
|
' visend setup pair visend with your Telegram (own bot or',
|
|
16
16
|
' shared server)',
|
|
17
|
+
' visend setup --stdin non-interactive setup for programs: read the',
|
|
18
|
+
' bot token (and optional chat id) from stdin',
|
|
17
19
|
' visend settings show current settings',
|
|
18
20
|
' visend forget [-y|--yes] delete all settings except the server URL',
|
|
19
21
|
' visend server show server URL, status and bot link',
|
|
@@ -23,7 +25,13 @@ const HELP = [
|
|
|
23
25
|
'',
|
|
24
26
|
'Options:',
|
|
25
27
|
' -y, --yes answer "yes" to all confirmation prompts',
|
|
28
|
+
' --stdin with `visend setup`: read the bot token (and optional chat id)',
|
|
29
|
+
' on stdin instead of prompting',
|
|
26
30
|
' --name <name> file name to use for `visend file`',
|
|
31
|
+
' --json for send commands: print exactly one JSON line on stdout,',
|
|
32
|
+
' {"ok":true,"message_id":123} or {"ok":false,"error":"..."}',
|
|
33
|
+
' --quiet for send commands: no stdout output (the exit code still',
|
|
34
|
+
' reports the result)',
|
|
27
35
|
' --force-as-text send text longer than 4096 chars as text anyway (it will be cut',
|
|
28
36
|
' to the Telegram limit)',
|
|
29
37
|
' -v, --version print the version and exit',
|
package/lib/commands/setup.js
CHANGED
|
@@ -4,6 +4,7 @@ const config = require('../config');
|
|
|
4
4
|
const telegram = require('../telegram');
|
|
5
5
|
const serverapi = require('../serverapi');
|
|
6
6
|
const send = require('../send');
|
|
7
|
+
const stdin = require('../stdin');
|
|
7
8
|
const tty = require('../tty');
|
|
8
9
|
const { VisendError } = require('../errors');
|
|
9
10
|
|
|
@@ -127,7 +128,11 @@ function extractStart(updates) {
|
|
|
127
128
|
return null;
|
|
128
129
|
}
|
|
129
130
|
|
|
130
|
-
async function waitForStart(token, yes) {
|
|
131
|
+
async function waitForStart(token, yes, opts) {
|
|
132
|
+
opts = opts || {};
|
|
133
|
+
// Progress chatter can be redirected (the non-interactive setup keeps
|
|
134
|
+
// stdout to the single status line and reports progress on stderr).
|
|
135
|
+
const write = opts.write || process.stdout.write.bind(process.stdout);
|
|
131
136
|
// First call only establishes the baseline update_id; queued (stale)
|
|
132
137
|
// updates are never shown to the user.
|
|
133
138
|
let lastId = 0;
|
|
@@ -138,7 +143,7 @@ async function waitForStart(token, yes) {
|
|
|
138
143
|
break;
|
|
139
144
|
} catch (err) {
|
|
140
145
|
if (err instanceof telegram.TelegramError && err.errorCode === 409) {
|
|
141
|
-
const proceed = await handleWebhookConflict(token, yes);
|
|
146
|
+
const proceed = await handleWebhookConflict(token, yes, opts.nonInteractive);
|
|
142
147
|
if (!proceed) return null;
|
|
143
148
|
continue;
|
|
144
149
|
}
|
|
@@ -149,23 +154,23 @@ async function waitForStart(token, yes) {
|
|
|
149
154
|
if (first[i].update_id > lastId) lastId = first[i].update_id;
|
|
150
155
|
}
|
|
151
156
|
const deadline = Date.now() + WAIT_LIMIT_MS;
|
|
152
|
-
|
|
157
|
+
write('Waiting for your /start...');
|
|
153
158
|
for (;;) {
|
|
154
|
-
|
|
159
|
+
write('.');
|
|
155
160
|
let updates;
|
|
156
161
|
// Never start a long poll that would outlive the deadline: cap its
|
|
157
162
|
// timeout to the time that is actually left.
|
|
158
163
|
const remainingSec = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
|
159
164
|
if (remainingSec <= 0) {
|
|
160
|
-
|
|
165
|
+
write('\n');
|
|
161
166
|
return null;
|
|
162
167
|
}
|
|
163
168
|
try {
|
|
164
169
|
updates = await telegram.getUpdates(token, lastId + 1, Math.min(25, remainingSec));
|
|
165
170
|
} catch (err) {
|
|
166
171
|
if (err instanceof telegram.TelegramError && err.errorCode === 409) {
|
|
167
|
-
|
|
168
|
-
const proceed = await handleWebhookConflict(token, yes);
|
|
172
|
+
write('\n');
|
|
173
|
+
const proceed = await handleWebhookConflict(token, yes, opts.nonInteractive);
|
|
169
174
|
if (!proceed) return null;
|
|
170
175
|
out('Continuing to wait...');
|
|
171
176
|
continue;
|
|
@@ -178,17 +183,25 @@ async function waitForStart(token, yes) {
|
|
|
178
183
|
}
|
|
179
184
|
const found = extractStart(updates);
|
|
180
185
|
if (found) {
|
|
181
|
-
|
|
186
|
+
write('\n');
|
|
182
187
|
return found;
|
|
183
188
|
}
|
|
184
189
|
if (Date.now() >= deadline) {
|
|
185
|
-
|
|
190
|
+
write('\n');
|
|
186
191
|
return null;
|
|
187
192
|
}
|
|
188
193
|
}
|
|
189
194
|
}
|
|
190
195
|
|
|
191
|
-
async function handleWebhookConflict(token, yes) {
|
|
196
|
+
async function handleWebhookConflict(token, yes, nonInteractive) {
|
|
197
|
+
if (nonInteractive) {
|
|
198
|
+
// A program must never silently break an existing integration by
|
|
199
|
+
// deleting the webhook; surface the conflict as a plain failure.
|
|
200
|
+
throw new VisendError(
|
|
201
|
+
'Another getUpdates poller or a webhook is active on this bot (HTTP 409).' +
|
|
202
|
+
' Stop the other poller or delete the webhook manually, then retry.'
|
|
203
|
+
);
|
|
204
|
+
}
|
|
192
205
|
out('Another getUpdates poller or a webhook is active on this bot (HTTP 409).');
|
|
193
206
|
out('This usually means the bot is used by another integration.');
|
|
194
207
|
const drop = await tty.confirm(
|
|
@@ -200,11 +213,88 @@ async function handleWebhookConflict(token, yes) {
|
|
|
200
213
|
return true;
|
|
201
214
|
}
|
|
202
215
|
|
|
203
|
-
|
|
204
|
-
const token = (await tty.askRequired('Bot token (from @BotFather): ')).trim();
|
|
216
|
+
function assertTokenFormat(token) {
|
|
205
217
|
if (!/^\d{5,}:[A-Za-z0-9_-]{30,}$/.test(token)) {
|
|
206
218
|
throw new VisendError('That does not look like a bot token. Expected format: 123456789:AA...');
|
|
207
219
|
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function saveBotConfig(token, userId, me) {
|
|
223
|
+
const cfg = config.load();
|
|
224
|
+
cfg.mode = 'bot';
|
|
225
|
+
cfg.bot_token = token;
|
|
226
|
+
cfg.user_id = userId;
|
|
227
|
+
config.save(cfg);
|
|
228
|
+
const botName = me.username ? '@' + me.username : ('bot id ' + (me.id || '?'));
|
|
229
|
+
out('Configured. Mode: own bot, chat ' + userId + ', bot ' + botName + '.');
|
|
230
|
+
// Confirm end-to-end delivery; the outcome is a diagnostic, the status
|
|
231
|
+
// line above stays the only stdout line.
|
|
232
|
+
try {
|
|
233
|
+
await telegram.sendMessage(token, userId, 'visend is set up! Everything you pipe will arrive here.');
|
|
234
|
+
process.stderr.write('Test message sent to chat ' + userId + '.\n');
|
|
235
|
+
} catch (err) {
|
|
236
|
+
warn('settings saved, but the test message failed: ' + send.describeTelegramError(err));
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Non-interactive setup for host programs: the bot token comes from stdin
|
|
241
|
+
// (optionally followed by the chat id as a second line), no terminal and
|
|
242
|
+
// no prompts are involved, the server mode is never offered.
|
|
243
|
+
async function setupBotFromStdin() {
|
|
244
|
+
if (stdin.isPiped()) {
|
|
245
|
+
const raw = await stdin.readAll();
|
|
246
|
+
const lines = raw.toString('utf8').split(/\r?\n/).map(function (s) { return s.trim(); })
|
|
247
|
+
.filter(function (s) { return s.length > 0; });
|
|
248
|
+
if (lines.length === 0 || lines.length > 2) {
|
|
249
|
+
throw new VisendError(
|
|
250
|
+
'Expected the bot token and (optionally) the chat id on stdin - one or two lines.' +
|
|
251
|
+
' Usage: printf %s "$BOT_TOKEN" | visend setup --stdin'
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
const token = lines[0];
|
|
255
|
+
assertTokenFormat(token);
|
|
256
|
+
let me;
|
|
257
|
+
try {
|
|
258
|
+
me = await telegram.getMe(token);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
throw new VisendError('Token check (getMe) failed: ' + err.message);
|
|
261
|
+
}
|
|
262
|
+
process.stderr.write('Token is valid. Bot: @' + (me.username || me.first_name) + '\n');
|
|
263
|
+
let userId;
|
|
264
|
+
if (lines.length === 2) {
|
|
265
|
+
if (!/^\d{1,16}$/.test(lines[1])) {
|
|
266
|
+
throw new VisendError('The optional second stdin line must be the numeric chat id (yours from @userinfobot).');
|
|
267
|
+
}
|
|
268
|
+
userId = Number(lines[1]);
|
|
269
|
+
} else {
|
|
270
|
+
const found = await waitForStart(token, false, { nonInteractive: true, write: stderrWrite });
|
|
271
|
+
if (!found) {
|
|
272
|
+
throw new VisendError(
|
|
273
|
+
'Timed out waiting for /start. Send /start to the bot and retry,' +
|
|
274
|
+
' or pass the chat id as the second stdin line.'
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
process.stderr.write('Got it: user_id ' + found.userId +
|
|
278
|
+
(found.username ? ' (@' + found.username + ')' : '') + '\n');
|
|
279
|
+
userId = found.userId;
|
|
280
|
+
}
|
|
281
|
+
await saveBotConfig(token, userId, me);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
throw new VisendError(
|
|
285
|
+
'setup --stdin reads the token from stdin. Pipe it in:' +
|
|
286
|
+
' printf %s "$BOT_TOKEN" | visend setup --stdin'
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function stderrWrite(chunk) {
|
|
291
|
+
process.stderr.write(chunk);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function setupBot(yes) {
|
|
296
|
+
const token = (await tty.askRequired('Bot token (from @BotFather): ')).trim();
|
|
297
|
+
assertTokenFormat(token);
|
|
208
298
|
let me;
|
|
209
299
|
try {
|
|
210
300
|
me = await telegram.getMe(token);
|
|
@@ -249,6 +339,11 @@ async function setupBot(yes) {
|
|
|
249
339
|
}
|
|
250
340
|
|
|
251
341
|
async function run(args, flags) {
|
|
342
|
+
if (flags.stdin) {
|
|
343
|
+
if (args.length) throw new VisendError('`visend setup --stdin` takes no arguments.');
|
|
344
|
+
await setupBotFromStdin();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
252
347
|
const cfg = config.load();
|
|
253
348
|
const serverUrl = config.effectiveServerUrl(cfg);
|
|
254
349
|
out('visend setup');
|
package/lib/commands/text.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const binary = require('../binary');
|
|
4
4
|
const send = require('../send');
|
|
5
5
|
const stdin = require('../stdin');
|
|
6
|
+
const output = require('../output');
|
|
6
7
|
const tty = require('../tty');
|
|
7
8
|
const { VisendError } = require('../errors');
|
|
8
9
|
|
|
@@ -57,9 +58,14 @@ async function run(args, flags) {
|
|
|
57
58
|
'Warning: the input looks like binary data (' + detected.reason + ').\n' +
|
|
58
59
|
'First bytes: ' + binary.preview(buf) + '\n'
|
|
59
60
|
);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
// Outside a terminal (stdin is a pipe) there is nobody to answer the
|
|
62
|
+
// confirm: send the text instead of aborting the run. Humans at a
|
|
63
|
+
// terminal keep the prompt (-y still auto-confirms).
|
|
64
|
+
if (!flags.yes && !stdin.isPiped()) {
|
|
65
|
+
const ok = await tty.confirm('Send it as text anyway?', flags.yes);
|
|
66
|
+
if (!ok) {
|
|
67
|
+
throw new VisendError('Aborted. Use `visend file` to send binary data as a file.');
|
|
68
|
+
}
|
|
63
69
|
}
|
|
64
70
|
}
|
|
65
71
|
|
|
@@ -72,10 +78,10 @@ async function run(args, flags) {
|
|
|
72
78
|
TELEGRAM_TEXT_LIMIT + ' characters. Sending the first ' + TELEGRAM_TEXT_LIMIT + ' (--force-as-text).\n'
|
|
73
79
|
);
|
|
74
80
|
const cut = truncateToLimit(buf, TELEGRAM_TEXT_LIMIT);
|
|
75
|
-
|
|
81
|
+
output.emitSendResult(await send.deliverText(send.requireConfig(), cut), flags);
|
|
76
82
|
return;
|
|
77
83
|
}
|
|
78
|
-
|
|
84
|
+
output.emitSendResult(await send.deliverText(send.requireConfig(), buf), flags);
|
|
79
85
|
return;
|
|
80
86
|
}
|
|
81
87
|
|
|
@@ -85,11 +91,11 @@ async function run(args, flags) {
|
|
|
85
91
|
TELEGRAM_TEXT_LIMIT + ' characters. Sending it as a file "visend.txt" instead.' +
|
|
86
92
|
' Use --force-as-text to send it as text anyway (it will be cut).\n'
|
|
87
93
|
);
|
|
88
|
-
|
|
94
|
+
output.emitSendResult(await send.deliverFile(send.requireConfig(), buf, 'visend.txt'), flags);
|
|
89
95
|
return;
|
|
90
96
|
}
|
|
91
97
|
|
|
92
|
-
|
|
98
|
+
output.emitSendResult(await send.deliverText(send.requireConfig(), buf), flags);
|
|
93
99
|
}
|
|
94
100
|
|
|
95
101
|
module.exports = { run: run };
|
package/lib/config.js
CHANGED
|
@@ -13,6 +13,11 @@ const DEFAULT_SERVER_URL = 'https://visend.vishota.com';
|
|
|
13
13
|
const KEYS = ['mode', 'bot_token', 'user_id', 'server_url', 'server_token', 'server_refresh_token'];
|
|
14
14
|
|
|
15
15
|
function configDir() {
|
|
16
|
+
// A host program can isolate its own config (and keep the user's one
|
|
17
|
+
// untouched) by pointing VISEND_CONFIG_DIR at a private directory.
|
|
18
|
+
// The same permission hardening applies there as to the default path.
|
|
19
|
+
const override = process.env.VISEND_CONFIG_DIR;
|
|
20
|
+
if (override) return override;
|
|
16
21
|
return path.join(os.homedir(), '.config', 'visend');
|
|
17
22
|
}
|
|
18
23
|
|
package/lib/errors.js
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* User-facing error. `main()` catches it, prints the message to stderr
|
|
5
|
-
* and exits with code 1.
|
|
5
|
+
* and exits with code 1. `kind` is an optional short machine-readable
|
|
6
|
+
* reason (used by --json output): "auth" | "rate_limited" | "network" |
|
|
7
|
+
* "config".
|
|
6
8
|
*/
|
|
7
9
|
class VisendError extends Error {
|
|
8
|
-
constructor(message) {
|
|
10
|
+
constructor(message, kind) {
|
|
9
11
|
super(message);
|
|
10
12
|
this.name = 'VisendError';
|
|
13
|
+
if (kind) this.kind = kind;
|
|
11
14
|
}
|
|
12
15
|
}
|
|
13
16
|
|
package/lib/output.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// One stdout line for the send commands (`text`, `file`): the human
|
|
4
|
+
// message by default, a single JSON line with --json, nothing with
|
|
5
|
+
// --quiet. Diagnostics and warnings keep going to stderr in every mode.
|
|
6
|
+
function emitSendResult(res, flags) {
|
|
7
|
+
if (flags.quiet) return;
|
|
8
|
+
if (flags.json) {
|
|
9
|
+
process.stdout.write(JSON.stringify({ ok: true, message_id: res.messageId }) + '\n');
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
process.stdout.write(res.message + '\n');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { emitSendResult: emitSendResult };
|
package/lib/send.js
CHANGED
|
@@ -14,12 +14,31 @@ function requireConfig() {
|
|
|
14
14
|
if (!cfg.server_token && !cfg.server_refresh_token) {
|
|
15
15
|
throw new VisendError(
|
|
16
16
|
'The server token is missing (the server URL was changed after setup). ' +
|
|
17
|
-
'Run `visend setup` again to get a new one-time code.'
|
|
17
|
+
'Run `visend setup` again to get a new one-time code.',
|
|
18
|
+
'config'
|
|
18
19
|
);
|
|
19
20
|
}
|
|
20
21
|
return cfg;
|
|
21
22
|
}
|
|
22
|
-
throw new VisendError('visend is not configured yet. Run `visend setup` first.');
|
|
23
|
+
throw new VisendError('visend is not configured yet. Run `visend setup` first.', 'config');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Short machine-readable reason for --json output; omitted when no kind
|
|
27
|
+
// maps cleanly.
|
|
28
|
+
function kindForDeliveryError(err) {
|
|
29
|
+
if (err instanceof serverapi.ServerError) {
|
|
30
|
+
if (err.status === 401) return 'auth';
|
|
31
|
+
if (err.status === 429) return 'rate_limited';
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
if (!err || !err.errorCode) return 'network'; // transport-level failure
|
|
35
|
+
if (err.errorCode === 429) return 'rate_limited';
|
|
36
|
+
if (err.errorCode === 401 || err.errorCode === 403) return 'auth';
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function messageIdOf(result) {
|
|
41
|
+
return result && typeof result.message_id === 'number' ? result.message_id : null;
|
|
23
42
|
}
|
|
24
43
|
|
|
25
44
|
function describeTelegramError(err) {
|
|
@@ -75,14 +94,15 @@ async function rotateTokens(cfg) {
|
|
|
75
94
|
} catch (err) {
|
|
76
95
|
if (err instanceof serverapi.ServerError && err.status === 401) {
|
|
77
96
|
throw new VisendError(
|
|
78
|
-
'The refresh token is invalid or expired. Run `visend setup` again to get a new one-time code.'
|
|
97
|
+
'The refresh token is invalid or expired. Run `visend setup` again to get a new one-time code.',
|
|
98
|
+
'auth'
|
|
79
99
|
);
|
|
80
100
|
}
|
|
81
101
|
throw err;
|
|
82
102
|
}
|
|
83
103
|
if (!pair || !pair.token || !pair.refresh_token) {
|
|
84
104
|
// Saving an incomplete pair would silently drop the refresh capability.
|
|
85
|
-
throw new VisendError('The server sent an incomplete token pair. Run `visend setup` again.');
|
|
105
|
+
throw new VisendError('The server sent an incomplete token pair. Run `visend setup` again.', 'auth');
|
|
86
106
|
}
|
|
87
107
|
cfg.server_token = pair.token;
|
|
88
108
|
cfg.server_refresh_token = pair.refresh_token;
|
|
@@ -95,19 +115,25 @@ async function deliverText(cfg, textBuf) {
|
|
|
95
115
|
if (cfg.mode === 'bot') {
|
|
96
116
|
try {
|
|
97
117
|
const result = await telegram.sendMessage(cfg.bot_token, cfg.user_id, text);
|
|
98
|
-
return
|
|
118
|
+
return {
|
|
119
|
+
message: 'Text sent to Telegram (message_id ' + result.message_id + ').',
|
|
120
|
+
messageId: messageIdOf(result),
|
|
121
|
+
};
|
|
99
122
|
} catch (err) {
|
|
100
|
-
throw new VisendError(describeTelegramError(err));
|
|
123
|
+
throw new VisendError(describeTelegramError(err), kindForDeliveryError(err));
|
|
101
124
|
}
|
|
102
125
|
}
|
|
103
126
|
try {
|
|
104
127
|
const result = await withRefresh(cfg, function (url, token) {
|
|
105
128
|
return serverapi.sendText(url, token, textBuf);
|
|
106
129
|
});
|
|
107
|
-
return
|
|
108
|
-
'
|
|
130
|
+
return {
|
|
131
|
+
message: 'Text sent to Telegram via ' + config.effectiveServerUrl(cfg) +
|
|
132
|
+
' (message_id ' + (result.message_id || '?') + ').',
|
|
133
|
+
messageId: messageIdOf(result),
|
|
134
|
+
};
|
|
109
135
|
} catch (err) {
|
|
110
|
-
throw new VisendError(describeServerError(err));
|
|
136
|
+
throw new VisendError(describeServerError(err), kindForDeliveryError(err));
|
|
111
137
|
}
|
|
112
138
|
}
|
|
113
139
|
|
|
@@ -122,20 +148,26 @@ async function deliverFile(cfg, buf, name) {
|
|
|
122
148
|
}
|
|
123
149
|
if (cfg.mode === 'bot') {
|
|
124
150
|
try {
|
|
125
|
-
await telegram.sendDocument(cfg.bot_token, cfg.user_id, buf, name);
|
|
126
|
-
return
|
|
151
|
+
const result = await telegram.sendDocument(cfg.bot_token, cfg.user_id, buf, name);
|
|
152
|
+
return {
|
|
153
|
+
message: 'File "' + name + '" (' + sizeMb + ' MB) sent to Telegram.',
|
|
154
|
+
messageId: messageIdOf(result),
|
|
155
|
+
};
|
|
127
156
|
} catch (err) {
|
|
128
|
-
throw new VisendError(describeTelegramError(err));
|
|
157
|
+
throw new VisendError(describeTelegramError(err), kindForDeliveryError(err));
|
|
129
158
|
}
|
|
130
159
|
}
|
|
131
160
|
try {
|
|
132
161
|
const result = await withRefresh(cfg, function (url, token) {
|
|
133
162
|
return serverapi.sendFile(url, token, buf, name);
|
|
134
163
|
});
|
|
135
|
-
return
|
|
136
|
-
|
|
164
|
+
return {
|
|
165
|
+
message: 'File "' + name + '" (' + sizeMb + ' MB) sent to Telegram via ' +
|
|
166
|
+
config.effectiveServerUrl(cfg) + '.',
|
|
167
|
+
messageId: messageIdOf(result),
|
|
168
|
+
};
|
|
137
169
|
} catch (err) {
|
|
138
|
-
throw new VisendError(describeServerError(err));
|
|
170
|
+
throw new VisendError(describeServerError(err), kindForDeliveryError(err));
|
|
139
171
|
}
|
|
140
172
|
}
|
|
141
173
|
|
package/lib/telegram.js
CHANGED
|
@@ -20,7 +20,11 @@ class TelegramError extends Error {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
// Telegram asks to slow down (HTTP 429 + retry_after): wait at most this
|
|
24
|
+
// many seconds before the single bounded retry.
|
|
25
|
+
const RETRY_AFTER_CAP_SEC = 30;
|
|
26
|
+
|
|
27
|
+
async function call(token, method, payload, timeoutMs, retriedAfter429) {
|
|
24
28
|
const opts = {
|
|
25
29
|
method: payload ? 'POST' : 'GET',
|
|
26
30
|
headers: {},
|
|
@@ -33,7 +37,16 @@ async function call(token, method, payload, timeoutMs) {
|
|
|
33
37
|
const res = await httpx.request(apiUrl(token, method), opts);
|
|
34
38
|
const json = httpx.parseJsonBody(res);
|
|
35
39
|
if (!json.ok) {
|
|
36
|
-
|
|
40
|
+
const err = new TelegramError(json.description, json.error_code, json.parameters);
|
|
41
|
+
if (
|
|
42
|
+
err.errorCode === 429 && !retriedAfter429 &&
|
|
43
|
+
err.params && typeof err.params.retry_after === 'number' && err.params.retry_after >= 0
|
|
44
|
+
) {
|
|
45
|
+
const waitSec = Math.min(err.params.retry_after, RETRY_AFTER_CAP_SEC);
|
|
46
|
+
await new Promise(function (resolve) { setTimeout(resolve, waitSec * 1000); });
|
|
47
|
+
return call(token, method, payload, timeoutMs, true);
|
|
48
|
+
}
|
|
49
|
+
throw err;
|
|
37
50
|
}
|
|
38
51
|
return json.result;
|
|
39
52
|
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "visendx",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "visend - a fast cross-platform tool to send anything to Telegram",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "vishota",
|
|
7
7
|
"email": "vishota@vishota.com"
|
|
8
8
|
},
|
|
9
9
|
"bin": {
|
|
10
|
-
"visend": "bin/visend.js"
|
|
10
|
+
"visend": "bin/visend.js",
|
|
11
|
+
"visendx": "bin/visend.js"
|
|
11
12
|
},
|
|
12
13
|
"files": [
|
|
13
14
|
"bin",
|