-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
52 lines (48 loc) · 1.31 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Client, ConnectionError, StorageIndexedDB } from "mtkruto/mod.ts";
export const client = new Client(
new StorageIndexedDB("client"),
1, // replace this with a vaild API ID
"", // replace this with a valid API hash
{ autoStart: false },
);
client.invoke.use(async (ctx, next) => {
if (ctx.error instanceof ConnectionError) {
if (!navigator.onLine) {
await new Promise((r) => addEventListener("online", r, { once: true }));
} else {
await new Promise((r) => setTimeout(r, 1000));
}
return true;
} else {
return await next();
}
});
// @ts-ignore: d
globalThis.client = client; // just to be able to play around with it
async function startClientInner() {
while (true) {
try {
await client.start();
break;
} catch (err) {
if (!navigator.onLine) {
addEventListener("online", async () => {
await startClientInner();
}, { once: true });
break;
}
console.error(err);
console.warn("Failed to start client. Retrying in 5 seconds.");
await new Promise((r) => setTimeout(r, 5_000));
}
}
}
export async function startClient() {
if (navigator.onLine) {
await startClientInner();
} else {
addEventListener("online", async () => {
await startClientInner();
}, { once: true });
}
}