visendx 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/lib/send.js ADDED
@@ -0,0 +1,148 @@
1
+ 'use strict';
2
+
3
+ const config = require('./config');
4
+ const telegram = require('./telegram');
5
+ const serverapi = require('./serverapi');
6
+ const { VisendError } = require('./errors');
7
+
8
+ const TELEGRAM_FILE_LIMIT = 50 * 1024 * 1024;
9
+
10
+ function requireConfig() {
11
+ const cfg = config.load();
12
+ if (cfg.mode === 'bot' && cfg.bot_token && cfg.user_id) return cfg;
13
+ if (cfg.mode === 'server' && cfg.user_id) {
14
+ if (!cfg.server_token && !cfg.server_refresh_token) {
15
+ throw new VisendError(
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.'
18
+ );
19
+ }
20
+ return cfg;
21
+ }
22
+ throw new VisendError('visend is not configured yet. Run `visend setup` first.');
23
+ }
24
+
25
+ function describeTelegramError(err) {
26
+ let msg = 'Telegram API error: ' + err.message;
27
+ if (err.errorCode) msg += ' (code ' + err.errorCode + ')';
28
+ if (err.errorCode === 401) msg += ' - the bot token is invalid or was revoked. Run `visend setup`.';
29
+ if (err.errorCode === 403 && /chat not found|bot was blocked/i.test(err.message)) {
30
+ msg += ' - run `visend setup` to re-pair with your chat.';
31
+ }
32
+ return msg;
33
+ }
34
+
35
+ function describeServerError(err) {
36
+ if (err instanceof serverapi.ServerError && err.code === 'file_too_large') {
37
+ const limit = err.maxFileSize
38
+ ? Math.round(err.maxFileSize / (1024 * 1024) * 10) / 10 + ' MB'
39
+ : 'unknown';
40
+ return 'The server rejected the file: its own size limit is ' + limit +
41
+ ' (this is a server-side limit, not the Telegram one).';
42
+ }
43
+ if (err instanceof serverapi.ServerError && err.status === 401) {
44
+ if (err.code === 'token_expired') {
45
+ return 'The access token expired and the refresh token did not work. Run `visend setup` again.';
46
+ }
47
+ return 'The server rejected the token. Run `visend setup` again to get a new one-time code.';
48
+ }
49
+ return err.message;
50
+ }
51
+
52
+ // Run a server request; on 401 (expired access) refresh the token pair,
53
+ // persist it and retry the request once.
54
+ async function withRefresh(cfg, fn) {
55
+ const url = config.effectiveServerUrl(cfg);
56
+ if (!cfg.server_token && cfg.server_refresh_token) {
57
+ // Nothing to retry with yet - go straight to refresh.
58
+ await rotateTokens(cfg);
59
+ }
60
+ try {
61
+ return await fn(url, cfg.server_token);
62
+ } catch (err) {
63
+ if (!(err instanceof serverapi.ServerError) || err.status !== 401) throw err;
64
+ if (!cfg.server_refresh_token) throw err;
65
+ await rotateTokens(cfg);
66
+ return await fn(url, cfg.server_token);
67
+ }
68
+ }
69
+
70
+ async function rotateTokens(cfg) {
71
+ const url = config.effectiveServerUrl(cfg);
72
+ let pair;
73
+ try {
74
+ pair = await serverapi.refresh(url, cfg.server_refresh_token);
75
+ } catch (err) {
76
+ if (err instanceof serverapi.ServerError && err.status === 401) {
77
+ throw new VisendError(
78
+ 'The refresh token is invalid or expired. Run `visend setup` again to get a new one-time code.'
79
+ );
80
+ }
81
+ throw err;
82
+ }
83
+ if (!pair || !pair.token || !pair.refresh_token) {
84
+ // 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.');
86
+ }
87
+ cfg.server_token = pair.token;
88
+ cfg.server_refresh_token = pair.refresh_token;
89
+ config.save(cfg);
90
+ }
91
+
92
+ async function deliverText(cfg, textBuf) {
93
+ const text = textBuf.toString('utf8');
94
+ if (!text.trim()) throw new VisendError('Refusing to send an empty message.');
95
+ if (cfg.mode === 'bot') {
96
+ try {
97
+ const result = await telegram.sendMessage(cfg.bot_token, cfg.user_id, text);
98
+ return 'Text sent to Telegram (message_id ' + result.message_id + ').';
99
+ } catch (err) {
100
+ throw new VisendError(describeTelegramError(err));
101
+ }
102
+ }
103
+ try {
104
+ const result = await withRefresh(cfg, function (url, token) {
105
+ return serverapi.sendText(url, token, textBuf);
106
+ });
107
+ return 'Text sent to Telegram via ' + config.effectiveServerUrl(cfg) +
108
+ ' (message_id ' + (result.message_id || '?') + ').';
109
+ } catch (err) {
110
+ throw new VisendError(describeServerError(err));
111
+ }
112
+ }
113
+
114
+ async function deliverFile(cfg, buf, name) {
115
+ const sizeMb = Math.round(buf.length / (1024 * 1024) * 10) / 10;
116
+ // Telegram bot API hard limit - applies to every delivery path, including
117
+ // the text->file fallback for >4096-char input.
118
+ if (buf.length > TELEGRAM_FILE_LIMIT) {
119
+ throw new VisendError(
120
+ 'The file is ' + sizeMb + ' MB, but Telegram bots can only send files up to 50 MB.'
121
+ );
122
+ }
123
+ if (cfg.mode === 'bot') {
124
+ try {
125
+ await telegram.sendDocument(cfg.bot_token, cfg.user_id, buf, name);
126
+ return 'File "' + name + '" (' + sizeMb + ' MB) sent to Telegram.';
127
+ } catch (err) {
128
+ throw new VisendError(describeTelegramError(err));
129
+ }
130
+ }
131
+ try {
132
+ const result = await withRefresh(cfg, function (url, token) {
133
+ return serverapi.sendFile(url, token, buf, name);
134
+ });
135
+ return 'File "' + name + '" (' + sizeMb + ' MB) sent to Telegram via ' +
136
+ config.effectiveServerUrl(cfg) + '.';
137
+ } catch (err) {
138
+ throw new VisendError(describeServerError(err));
139
+ }
140
+ }
141
+
142
+ module.exports = {
143
+ requireConfig: requireConfig,
144
+ deliverText: deliverText,
145
+ deliverFile: deliverFile,
146
+ describeTelegramError: describeTelegramError,
147
+ describeServerError: describeServerError,
148
+ };
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ const httpx = require('./httpx');
4
+
5
+ class ServerError extends Error {
6
+ constructor(message, status, code, maxFileSize) {
7
+ super(message);
8
+ this.name = 'ServerError';
9
+ this.status = status;
10
+ this.code = code;
11
+ this.maxFileSize = maxFileSize;
12
+ }
13
+ }
14
+ function checkResponse(res, what) {
15
+ let json = null;
16
+ try {
17
+ json = JSON.parse(res.body.toString('utf8'));
18
+ } catch (err) { /* non-JSON error page */ }
19
+ if (res.status >= 200 && res.status < 300 && json && json.ok) return json;
20
+ const description =
21
+ (json && (json.description || json.error)) ||
22
+ 'HTTP ' + res.status + ' ' + res.body.toString('utf8').slice(0, 200);
23
+ throw new ServerError(
24
+ what + ' failed: ' + description,
25
+ res.status,
26
+ json && json.error,
27
+ json && json.max_file_size
28
+ );
29
+ }
30
+
31
+ async function fetchStatus(serverUrl) {
32
+ const res = await httpx.request(serverUrl.replace(/\/+$/, '') + '/status', { timeoutMs: 10000 });
33
+ return checkResponse(res, 'Server status check');
34
+ }
35
+
36
+ async function fetchConfig(serverUrl) {
37
+ const res = await httpx.request(serverUrl.replace(/\/+$/, '') + '/config', { timeoutMs: 10000 });
38
+ return checkResponse(res, 'Server config fetch');
39
+ }
40
+
41
+ async function connect(serverUrl, userId, code) {
42
+ const res = await httpx.request(serverUrl.replace(/\/+$/, '') + '/connect', {
43
+ method: 'POST',
44
+ headers: { 'Content-Type': 'application/json' },
45
+ body: JSON.stringify({ user_id: userId, code: code }),
46
+ timeoutMs: 15000,
47
+ });
48
+ return checkResponse(res, 'Server connect');
49
+ }
50
+
51
+ // Exchange a refresh token for a new access+refresh pair.
52
+ async function refresh(serverUrl, refreshToken) {
53
+ const res = await httpx.request(serverUrl.replace(/\/+$/, '') + '/refresh', {
54
+ method: 'POST',
55
+ headers: { Authorization: 'Bearer ' + refreshToken },
56
+ timeoutMs: 20000,
57
+ });
58
+ return checkResponse(res, 'Token refresh');
59
+ }
60
+
61
+ async function sendText(serverUrl, token, textBuf) {
62
+ const res = await httpx.request(serverUrl.replace(/\/+$/, '') + '/text', {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Authorization': 'Bearer ' + token,
66
+ 'Content-Type': 'text/plain; charset=utf-8',
67
+ },
68
+ body: textBuf,
69
+ timeoutMs: 60000,
70
+ });
71
+ return checkResponse(res, 'Sending text');
72
+ }
73
+
74
+ async function sendFile(serverUrl, token, fileBuf, name) {
75
+ const res = await httpx.request(
76
+ serverUrl.replace(/\/+$/, '') + '/file?name=' + encodeURIComponent(name),
77
+ {
78
+ method: 'POST',
79
+ headers: {
80
+ 'Authorization': 'Bearer ' + token,
81
+ 'Content-Type': 'application/octet-stream',
82
+ },
83
+ body: fileBuf,
84
+ timeoutMs: 180000,
85
+ }
86
+ );
87
+ return checkResponse(res, 'Sending file');
88
+ }
89
+
90
+ module.exports = {
91
+ ServerError: ServerError,
92
+ fetchStatus: fetchStatus,
93
+ fetchConfig: fetchConfig,
94
+ connect: connect,
95
+ refresh: refresh,
96
+ sendText: sendText,
97
+ sendFile: sendFile,
98
+ };
package/lib/stdin.js ADDED
@@ -0,0 +1,32 @@
1
+ 'use strict';
2
+
3
+ const { VisendError } = require('./errors');
4
+
5
+ const MAX_INPUT_BYTES = 64 * 1024 * 1024;
6
+
7
+ function isPiped() {
8
+ return !process.stdin.isTTY;
9
+ }
10
+
11
+ function readAll() {
12
+ return new Promise(function (resolve, reject) {
13
+ const chunks = [];
14
+ let size = 0;
15
+ process.stdin.on('data', function (c) {
16
+ size += c.length;
17
+ if (size > MAX_INPUT_BYTES) {
18
+ reject(new VisendError(
19
+ 'Input exceeds ' + MAX_INPUT_BYTES / (1024 * 1024) + ' MB.' +
20
+ ' Note: Telegram itself accepts files only up to 50 MB.'
21
+ ));
22
+ process.stdin.destroy();
23
+ return;
24
+ }
25
+ chunks.push(c);
26
+ });
27
+ process.stdin.on('end', function () { resolve(Buffer.concat(chunks)); });
28
+ process.stdin.on('error', function (err) { reject(new VisendError('Failed to read stdin: ' + err.message)); });
29
+ });
30
+ }
31
+
32
+ module.exports = { isPiped: isPiped, readAll: readAll };
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const httpx = require('./httpx');
5
+
6
+ function apiBase() {
7
+ return process.env.VISEND_TELEGRAM_API_BASE || 'https://api.telegram.org';
8
+ }
9
+
10
+ function apiUrl(token, method) {
11
+ return apiBase() + '/bot' + token + '/' + method;
12
+ }
13
+
14
+ class TelegramError extends Error {
15
+ constructor(description, errorCode, params) {
16
+ super(description || 'Telegram API error');
17
+ this.name = 'TelegramError';
18
+ this.errorCode = errorCode;
19
+ this.params = params;
20
+ }
21
+ }
22
+
23
+ async function call(token, method, payload, timeoutMs) {
24
+ const opts = {
25
+ method: payload ? 'POST' : 'GET',
26
+ headers: {},
27
+ timeoutMs: timeoutMs || 30000,
28
+ };
29
+ if (payload) {
30
+ opts.headers['Content-Type'] = 'application/json';
31
+ opts.body = JSON.stringify(payload);
32
+ }
33
+ const res = await httpx.request(apiUrl(token, method), opts);
34
+ const json = httpx.parseJsonBody(res);
35
+ if (!json.ok) {
36
+ throw new TelegramError(json.description, json.error_code, json.parameters);
37
+ }
38
+ return json.result;
39
+ }
40
+
41
+ async function getMe(token) {
42
+ return call(token, 'getMe');
43
+ }
44
+
45
+ async function sendMessage(token, chatId, text) {
46
+ return call(token, 'sendMessage', {
47
+ chat_id: chatId,
48
+ text: text,
49
+ disable_web_page_preview: true,
50
+ });
51
+ }
52
+
53
+ async function deleteWebhook(token) {
54
+ return call(token, 'deleteWebhook', { drop_pending_updates: false });
55
+ }
56
+
57
+ async function getUpdates(token, offset, timeoutSec) {
58
+ const payload = { timeout: timeoutSec === undefined ? 0 : timeoutSec, limit: 100 };
59
+ if (offset !== undefined && offset !== null) payload.offset = offset;
60
+ // long poll of 25s + network overhead
61
+ return call(token, 'getUpdates', payload, (timeoutSec || 0) * 1000 + 15000);
62
+ }
63
+
64
+ // Zero-dependency multipart/form-data builder for sendDocument.
65
+ async function sendDocument(token, chatId, fileBuf, filename) {
66
+ const boundary = 'visend' + crypto.randomBytes(16).toString('hex');
67
+ const safeName = String(filename).replace(/[\r\n"]/g, '_');
68
+ const head = Buffer.from(
69
+ '--' + boundary + '\r\n' +
70
+ 'Content-Disposition: form-data; name="chat_id"\r\n\r\n' +
71
+ chatId + '\r\n' +
72
+ '--' + boundary + '\r\n' +
73
+ 'Content-Disposition: form-data; name="document"; filename="' + safeName + '"\r\n' +
74
+ 'Content-Type: application/octet-stream\r\n\r\n'
75
+ );
76
+ const tail = Buffer.from('\r\n--' + boundary + '--\r\n');
77
+ // Written sequentially: no head+file+tail concat, so a 50 MB file does
78
+ // not briefly occupy 100 MB of memory.
79
+ const res = await httpx.request(apiUrl(token, 'sendDocument'), {
80
+ method: 'POST',
81
+ headers: { 'Content-Type': 'multipart/form-data; boundary=' + boundary },
82
+ parts: [head, fileBuf, tail],
83
+ timeoutMs: 180000,
84
+ });
85
+ const json = httpx.parseJsonBody(res);
86
+ if (!json.ok) {
87
+ throw new TelegramError(json.description, json.error_code, json.parameters);
88
+ }
89
+ return json.result;
90
+ }
91
+
92
+ module.exports = {
93
+ TelegramError: TelegramError,
94
+ getMe: getMe,
95
+ sendMessage: sendMessage,
96
+ getUpdates: getUpdates,
97
+ deleteWebhook: deleteWebhook,
98
+ sendDocument: sendDocument,
99
+ };
package/lib/tty.js ADDED
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const readline = require('readline');
5
+ const { VisendError } = require('./errors');
6
+
7
+ // Interactive input must NOT come from stdin: stdin carries piped data.
8
+ // If stdin is the terminal itself we can use it; otherwise we open the
9
+ // controlling terminal directly (/dev/tty on POSIX, CONIN$ on Windows).
10
+
11
+ let cachedFd; // false = no tty, number = raw fd
12
+
13
+ function openTty() {
14
+ if (cachedFd !== undefined) return cachedFd;
15
+ cachedFd = false;
16
+ if (process.stdin.isTTY) return (cachedFd = 'stdin');
17
+ const dev = process.platform === 'win32' ? 'CONIN$' : '/dev/tty';
18
+ try {
19
+ cachedFd = fs.openSync(dev, 'r');
20
+ } catch (err) {
21
+ cachedFd = false;
22
+ }
23
+ return cachedFd;
24
+ }
25
+
26
+ function noTty(extraAdvice) {
27
+ throw new VisendError(
28
+ 'This prompt needs an interactive terminal. ' +
29
+ 'Re-run from a console' + (extraAdvice || ', or pass -y / --yes to auto-confirm') + '.'
30
+ );
31
+ }
32
+
33
+ function readLineFromFd(fd) {
34
+ const one = Buffer.alloc(1);
35
+ let line = '';
36
+ for (;;) {
37
+ let n;
38
+ try {
39
+ n = fs.readSync(fd, one, 0, 1, null);
40
+ } catch (err) {
41
+ if (line.length) return line;
42
+ throw new VisendError('Failed to read input: ' + err.message);
43
+ }
44
+ if (n <= 0) {
45
+ if (line.length) return line;
46
+ throw new VisendError('Input stream closed (EOF).');
47
+ }
48
+ const ch = one[0];
49
+ if (ch === 10) return line; // \n
50
+ if (ch !== 13) line += one.toString('latin1'); // drop \r; answers are ASCII
51
+ }
52
+ }
53
+
54
+ // Prompts and their hints go to stderr: stdout may carry the piped payload
55
+ // or be redirected by the user, while the answer still comes from the console.
56
+ function prompt(question, noTtyAdvice) {
57
+ return new Promise(function (resolve) {
58
+ const fd = openTty();
59
+ if (fd === false) return resolve(noTty(noTtyAdvice));
60
+ process.stderr.write(question);
61
+ if (fd === 'stdin') {
62
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
63
+ rl.question('', function (answer) {
64
+ rl.close();
65
+ resolve(answer);
66
+ });
67
+ } else {
68
+ try {
69
+ resolve(readLineFromFd(fd));
70
+ } catch (err) {
71
+ resolve(Promise.reject(err));
72
+ }
73
+ }
74
+ });
75
+ }
76
+
77
+ async function confirm(question, yes) {
78
+ if (yes) return true;
79
+ const answer = await module.exports.prompt(question + ' [y/N] ');
80
+ return /^[ \t]*y(es)?[ \t]*$/i.test(answer);
81
+ }
82
+
83
+ async function askRequired(question) {
84
+ for (;;) {
85
+ const answer = await module.exports.prompt(question, ' (run `visend setup` from a console)');
86
+ if (answer.trim()) return answer.trim();
87
+ process.stderr.write('Value is required.\n');
88
+ }
89
+ }
90
+
91
+ async function askUserId(question) {
92
+ for (;;) {
93
+ const answer = await module.exports.prompt(question, ' (run `visend setup` from a console)');
94
+ const trimmed = answer.trim();
95
+ if (/^\d{1,16}$/.test(trimmed)) return Number(trimmed);
96
+ process.stderr.write('User id must be a number (yours from @userinfobot).\n');
97
+ }
98
+ }
99
+
100
+ module.exports = {
101
+ prompt: prompt,
102
+ confirm: confirm,
103
+ askRequired: askRequired,
104
+ askUserId: askUserId,
105
+ };
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "visendx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "visend - a fast cross-platform tool to send anything to Telegram",
5
+ "author": {
6
+ "name": "vishota",
7
+ "email": "vishota@vishota.com"
8
+ },
9
+ "bin": {
10
+ "visend": "bin/visend.js"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "lib",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=10.12"
20
+ },
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/vishota/visend.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/vishota/visend/issues"
28
+ },
29
+ "homepage": "https://github.com/vishota/visend#readme",
30
+ "keywords": [
31
+ "telegram",
32
+ "cli",
33
+ "send-to-self",
34
+ "notes",
35
+ "files",
36
+ "pipe"
37
+ ],
38
+ "dependencies": {},
39
+ "devDependencies": {}
40
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.