@cello-protocol/cli 0.0.317 → 0.0.318
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/dist/daemon/telegram.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// Telegram's Bot API: the calls a notifier needs. Every call has a time limit, and a refusal carries Telegram's own words.
|
|
2
|
+
// The bot token is part of the address, so nothing here ever puts an address in an error.
|
|
3
|
+
import { request as httpRequest } from "node:http";
|
|
4
|
+
import { request as httpsRequest } from "node:https";
|
|
5
|
+
export const TELEGRAM = { apiUrl: "https://api.telegram.org", timeoutMs: 6_000, pollSeconds: 25 };
|
|
2
6
|
export class TelegramError extends Error {
|
|
3
7
|
// Telegram's own error number, when it gave one: 401 is a token it doesn't know, 409 is another reader on the same bot.
|
|
4
8
|
code;
|
|
@@ -7,38 +11,82 @@ export class TelegramError extends Error {
|
|
|
7
11
|
this.code = code;
|
|
8
12
|
}
|
|
9
13
|
}
|
|
10
|
-
|
|
14
|
+
class TimedOut extends Error {
|
|
15
|
+
}
|
|
16
|
+
// Why a connection failed, in the system's own codes. Telegram has an IPv4 and an IPv6 address, and a failure to reach it
|
|
17
|
+
// is one error per address with an empty message of its own, so each address's code is listed.
|
|
18
|
+
function reason(err) {
|
|
19
|
+
if (!(err instanceof Error))
|
|
20
|
+
return String(err);
|
|
21
|
+
const each = err.errors;
|
|
22
|
+
if (Array.isArray(each) && each.length > 0)
|
|
23
|
+
return each.map((e) => { const one = e; return `${one.code ?? one.message ?? "failed"}${one.address ? ` at ${one.address}` : ""}`; }).join(", ");
|
|
24
|
+
const code = err.code;
|
|
25
|
+
return [code, err.message].filter((part) => typeof part === "string" && part.length > 0).join(": ") || err.name;
|
|
26
|
+
}
|
|
27
|
+
// One POST. Not fetch, for one reason: fetch gives each of a host's addresses a quarter of a second to connect before it
|
|
28
|
+
// moves to the next, and can't be told otherwise. On a slow link, or a machine with no IPv6 route, that fails a call Telegram
|
|
29
|
+
// would have answered. Here each address gets the call's whole limit.
|
|
30
|
+
function post(url, body, limitMs, stop) {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const send = url.protocol === "http:" ? httpRequest : httpsRequest;
|
|
33
|
+
// The connection option is passed through to the socket. The request's own types don't list it.
|
|
34
|
+
const options = { method: "POST", headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }, autoSelectFamilyAttemptTimeout: limitMs };
|
|
35
|
+
const request = send(url, options, (response) => {
|
|
36
|
+
const parts = [];
|
|
37
|
+
response.on("data", (part) => { parts.push(part); });
|
|
38
|
+
response.on("end", () => { done(); resolve({ status: response.statusCode ?? 0, text: Buffer.concat(parts).toString("utf8") }); });
|
|
39
|
+
response.on("error", (err) => { done(); reject(err); });
|
|
40
|
+
});
|
|
41
|
+
const timer = setTimeout(() => { request.destroy(new TimedOut()); }, limitMs);
|
|
42
|
+
const stopped = () => { request.destroy(new Error("stopped")); };
|
|
43
|
+
function done() {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
stop?.removeEventListener("abort", stopped);
|
|
46
|
+
}
|
|
47
|
+
stop?.addEventListener("abort", stopped);
|
|
48
|
+
request.on("error", (err) => { done(); reject(err); });
|
|
49
|
+
request.end(body);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
// How many times one call is tried. Telegram sometimes doesn't answer a new connection at all: measured on 17 November from
|
|
53
|
+
// two networks, one try in six sat silent for its whole limit while the next was answered in under a second. So a silent
|
|
54
|
+
// try is given up on quickly and made again. A person not being told matters more than their being told twice.
|
|
55
|
+
const TRIES = 3;
|
|
56
|
+
async function call(at, token, method, body, limitMs = at.timeoutMs, stop, tries = TRIES) {
|
|
57
|
+
let url;
|
|
58
|
+
try {
|
|
59
|
+
url = new URL(`${at.apiUrl}/bot${token}/${method}`);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new TelegramError("Telegram couldn't be reached: its address isn't one.");
|
|
63
|
+
}
|
|
11
64
|
let response;
|
|
12
|
-
// A dropped connection is tried once more, because a person not being told matters more than their being told twice.
|
|
13
|
-
// A timeout isn't: the limit is the promise.
|
|
14
65
|
for (let attempt = 1; response === undefined; attempt++) {
|
|
15
66
|
try {
|
|
16
|
-
response = await
|
|
17
|
-
method: "POST",
|
|
18
|
-
headers: { "Content-Type": "application/json" },
|
|
19
|
-
body: JSON.stringify(body),
|
|
20
|
-
signal: stop ? AbortSignal.any([AbortSignal.timeout(limitMs), stop]) : AbortSignal.timeout(limitMs),
|
|
21
|
-
});
|
|
67
|
+
response = await post(url, JSON.stringify(body), limitMs, stop);
|
|
22
68
|
}
|
|
23
69
|
catch (err) {
|
|
24
70
|
if (stop?.aborted)
|
|
25
71
|
throw new TelegramError("Stopped.");
|
|
26
|
-
if (
|
|
27
|
-
throw new TelegramError(`Telegram didn't answer within ${limitMs / 1000} seconds.`);
|
|
28
|
-
if (attempt < 2)
|
|
72
|
+
if (attempt < tries)
|
|
29
73
|
continue;
|
|
30
|
-
const
|
|
31
|
-
|
|
74
|
+
const times = tries === 1 ? "" : `, in ${tries} tries`;
|
|
75
|
+
if (err instanceof TimedOut)
|
|
76
|
+
throw new TelegramError(`Telegram didn't answer within ${limitMs / 1000} seconds${times}.`);
|
|
77
|
+
throw new TelegramError(`Telegram couldn't be reached${times}: ${reason(err).replaceAll(token, "<bot token>")}.`);
|
|
32
78
|
}
|
|
33
79
|
}
|
|
34
80
|
let answer;
|
|
35
81
|
try {
|
|
36
|
-
answer =
|
|
82
|
+
answer = JSON.parse(response.text);
|
|
37
83
|
}
|
|
38
84
|
catch {
|
|
39
85
|
// No number: a page from a proxy or a hotel network isn't Telegram refusing the token.
|
|
40
86
|
throw new TelegramError(`Telegram answered with something unreadable (HTTP ${response.status}).`);
|
|
41
87
|
}
|
|
88
|
+
if (answer === null || typeof answer !== "object")
|
|
89
|
+
throw new TelegramError(`Telegram answered with something unreadable (HTTP ${response.status}).`);
|
|
42
90
|
if (answer.ok !== true)
|
|
43
91
|
throw new TelegramError(`Telegram refused: ${answer.description ?? `HTTP ${response.status}`}.`, answer.error_code);
|
|
44
92
|
return answer.result;
|
|
@@ -60,7 +108,8 @@ export async function newestUpdate(at, token) {
|
|
|
60
108
|
}
|
|
61
109
|
// Everything sent to the bot from this update on, waiting up to pollSeconds for the first. Stopping it ends the wait at once.
|
|
62
110
|
export async function updatesFrom(at, token, offset, stop) {
|
|
63
|
-
|
|
111
|
+
// One try: the reader calls again by itself, with a growing wait.
|
|
112
|
+
return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message"] }, at.pollSeconds * 1000 + at.timeoutMs, stop, 1);
|
|
64
113
|
}
|
|
65
114
|
// Answers only once Telegram has accepted the message, with the ids Telegram gave: the chat's own number, which is what a
|
|
66
115
|
// reply will carry even if the chat was named as @something, and the message's.
|
|
Binary file
|