This repository was archived by the owner on Jul 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.ts
More file actions
231 lines (216 loc) · 6.95 KB
/
Copy pathmain.ts
File metadata and controls
231 lines (216 loc) · 6.95 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
* MTKruto Server
* Copyright (C) 2024 Roj <https://roj.im/>
*
* This file is part of MTKruto Server.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { log } from "./log.ts";
import { assertArgCount, badRequest, drop, methodNotAllowed, notFound } from "./responses.ts";
import { addUser } from "./add_user.ts";
import { displayStats } from "./stats.tsx";
import { parseCliArgs } from "./cli_args.ts";
import { AllowedMethod } from "./client/deps.ts";
import { WorkerManager } from "./worker_manager.ts";
import { isAllowedMethod } from "./allowed_methods.ts";
import { parseFormDataParams, parseGetParams } from "./params.ts";
const args = parseCliArgs(Deno.args);
if (typeof args !== "object") {
log.error(args);
Deno.exit(1);
}
const { port, apiId, apiHash, workerCount, statsPort, addUser: addUser_ } = args;
if (addUser_) {
await addUser(apiId, apiHash);
}
log.info(
`Starting MTKruto Server with ${workerCount} worker${workerCount == 1 ? "" : "s"}.`,
);
const workers = new WorkerManager();
for (let i = 0; i < workerCount; i++) {
const id = workers.create();
await workers.call(id, "init", id, apiId, apiHash);
log.info(`Started worker ${id + 1}.`);
}
const started = await workers.startWebhookLoops();
if (started) {
log.info(`Started ${started} webhook loop${started == 1 ? "" : "s"}.`);
}
Deno.addSignalListener("SIGINT", async () => {
await workers.unload();
Deno.exit();
});
Deno.serve({
port,
onListen: ({ port }) => {
log.info(`Listening for connections on port ${port}.`);
log.info("Started MTKruto Server.");
},
}, async (request) => {
const url = new URL(request.url);
if (request.method != "POST" && request.method != "GET") {
return methodNotAllowed();
}
const parts = url.pathname.slice(1).split("/").map(decodeURIComponent);
if (parts.length != 2) {
return notFound();
}
let params: any[];
if (request.method == "POST") {
const contentType = request.headers.get("content-type");
if (contentType == "application/json") {
try {
params = await request.json();
if (!Array.isArray(params)) {
return badRequest("An array of arguments was expected.");
}
} catch {
return badRequest("Invalid JSON");
}
} else if (contentType?.startsWith("multipart/form-data")) {
params = parseFormDataParams(await request.formData());
} else {
if (contentType) {
return badRequest("Unsupported content type");
} else {
return badRequest(
"The content-type header was expected to be present.",
);
}
}
} else {
params = parseGetParams(url.searchParams);
}
const [id, method] = parts as [string, AllowedMethod | "getUpdates"];
try {
return await handleRequest(id, method, params);
} catch (err) {
if (err instanceof Response) {
return err;
} else {
throw err;
}
}
});
async function handleRequest(id: string, method: string, params: any[]) {
const worker = await workers.getClientWorker(id);
if (isAllowedMethod(method)) {
return await handleMethod(worker, id, method, params);
}
switch (method) {
case "getUpdates":
return await handleGetUpdates(worker, id, params[0]);
case "invoke":
assertArgCount(params.length, 1);
return await handleInvoke(worker, id, params[0]);
case "setWebhook":
assertArgCount(params.length, 1);
return await handleSetWebhook(worker, id, params[0]);
case "deleteWebhook":
assertArgCount(params.length, 0);
return await handleDeleteWebhook(worker, id);
case "dropPendingUpdates":
assertArgCount(params.length, 0);
return await handleDropPendingUpdates(worker, id);
default:
return badRequest("Invalid method");
}
}
async function handleMethod(
worker: number,
id: string,
method: AllowedMethod,
params: any,
) {
const result = await workers.call(worker, "serve", id, method, params);
if (result === "DROP") {
return drop();
} else if (Array.isArray(result)) {
return Response.json(...result);
} else {
const firstChunk = await workers.call(worker, "next", result.streamId);
if (firstChunk == null) {
return badRequest("Invalid stream ID");
}
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(firstChunk.value);
if (firstChunk.done) {
controller.close();
}
},
async pull(controller) {
const chunk = await workers.call(worker, "next", result.streamId);
if (chunk == null) {
controller.close();
} else {
if (chunk.value) {
controller.enqueue(chunk.value);
}
if (chunk.done) {
controller.close();
}
}
},
}),
);
}
}
async function handleGetUpdates(worker: number, id: string, timeout: number) {
const result = await workers.call(worker, "getUpdates", id, timeout || 0);
return Response.json(...result);
}
async function handleInvoke(worker: number, id: string, function_: any) {
const result = await workers.call(worker, "invoke", id, function_);
return Response.json(...result);
}
async function handleSetWebhook(worker: number, id: string, url: string) {
const result = await workers.call(worker, "setWebhook", id, url);
return Response.json(...result);
}
async function handleDeleteWebhook(worker: number, id: string) {
const result = await workers.call(worker, "deleteWebhook", id);
return Response.json(...result);
}
async function handleDropPendingUpdates(worker: number, id: string) {
const result = await workers.call(worker, "dropPendingUpdates", id);
return Response.json(...result);
}
// ============= STATS SERVER ============= //
Deno.serve({
port: statsPort,
onListen: () => {
log.info(`Stats can be accessed from port ${statsPort}.`);
},
}, async (request) => {
const url = new URL(request.url);
switch (url.pathname) {
case "/": {
const stats = await workers.getStats();
return new Response(displayStats(stats));
}
case "/write-logs":
await workers.unload();
return Response.json("Logs were written.");
case "/clear-cache":
for (let i = 0; i < workers.count(); ++i) {
await workers.call(i, "clearCache");
}
return Response.json("Caches were cleared.");
default:
return notFound();
}
});