-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
322 lines (304 loc) · 8.62 KB
/
main.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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import * as path from "std/path/mod.ts";
import { Application, Router } from "oak/mod.ts";
import { Bot, type Context, webhookCallback } from "grammy/mod.ts";
import { type FileFlavor, hydrateFiles } from "grammy_files/mod.ts";
import env from "./env.ts";
import * as db from "./db.ts";
import { verifyGitHubWebhook } from "./utils.ts";
const app = new Application();
const router = new Router();
const bot = new Bot<FileFlavor<Context>>(env.BOT_TOKEN);
bot.api.config.use(hydrateFiles(bot.token));
async function applyFile(branch: string, filePath: string) {
const formData = new FormData();
formData.set("repository", env.REPOSITORY_CLONE_URL);
formData.set("branch", branch);
formData.set(
"url",
new URL(`/file/${encodeURIComponent(filePath)}`, env.BASE_URL).href,
);
const res = await fetch(env.PATCH_PUSHER_API_URL, {
method: "POST",
body: formData,
});
if (res.status != 200) {
throw new Error("Failed to submit the patch.");
}
}
bot.chatType(["group", "supergroup"]).filter((ctx) =>
ctx.chat.id == env.CHAT_ID
).on("message:document", async (ctx) => {
if (!ctx.message.document.file_name?.endsWith(".patch")) {
return;
}
const repliedMessage = ctx.message.reply_to_message;
if (
!repliedMessage ||
!(repliedMessage.from?.id == ctx.me.id)
) {
return;
}
const entity = repliedMessage.entities?.[0];
if (!entity || entity.type != "text_link") {
return;
}
const prNumber = Number(
repliedMessage.text?.slice(entity.offset + 1, entity.length),
);
if (!prNumber) {
return;
}
let branch = "";
const res = await fetch(new URL(`pulls/${prNumber}`, env.REPOSITORY_API_URL));
if (res.status != 200) {
await ctx.reply("Failed to fetch PR.");
return;
}
branch = (await res.json())?.head?.ref;
if (!branch) {
await ctx.reply("Could not resolve PR branch.");
return;
}
const { file_path } = await ctx.getFile();
if (!file_path) {
await ctx.reply("Could not resolve file path.");
return;
}
try {
await applyFile(branch, file_path);
await ctx.reply("Patch submitted.");
} catch (err) {
await ctx.reply(err instanceof Error ? err.message : String(err));
}
});
bot.command("apply", async (ctx) => {
const branch = ctx.match;
if (!branch) {
await ctx.reply("Specify a branch name as an argument.");
return;
}
const document = ctx.msg.reply_to_message?.document;
if (!document) {
await ctx.reply("Reply a patch file.");
return;
}
if (!document.file_name?.endsWith(".patch")) {
await ctx.reply("The replied file does not have a .patch extension.");
return;
}
const { file_path } = await ctx.api.getFile(document.file_id);
if (!file_path) {
await ctx.reply("Could not resolve file path.");
return;
}
try {
await applyFile(branch, file_path);
await ctx.reply("Patch submitted.");
} catch (err) {
await ctx.reply(err instanceof Error ? err.message : String(err));
}
});
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
console.error(err);
ctx.response.status = 500;
}
});
router.post(
`/${bot.token.replaceAll(":", "\\:")}`,
webhookCallback(bot, "oak"),
);
router.get(`/file/:path`, async (ctx) => {
const response = await fetch(
`https://api.telegram.org/file/bot${bot.token}/${ctx.params.path}`,
);
ctx.response.status = response.status;
ctx.response.headers = response.headers;
ctx.response.body = response.body;
});
app.use(router.routes());
app.use(async (ctx, next) => {
let verified = false;
try {
const result = await verifyGitHubWebhook(
ctx.request.originalRequest,
);
verified = result.verified;
} catch (_err) {
//
} finally {
if (!verified) {
ctx.response.redirect("https://grammy.dev");
} else {
await next();
}
}
});
const labels: Record<string, string> = JSON.parse(
await Deno.readTextFile(
path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"labels.json",
),
),
);
const labelsInverse = Object.fromEntries(
Object.entries(labels).map(([k, v]) => [v, k]),
);
const labelNames = Object.keys(labelsInverse);
function getUpdatedText(text: string, currLabels: string[]) {
const labelsInText = text.split("\n").slice(1).filter((v) => v).filter((v) =>
v.startsWith("·")
).map((v) => v.split(/\s/)[1]);
for (const label of labelsInText) {
if (!currLabels.includes(labels[label])) {
labelsInText.splice(labelsInText.indexOf(label), 1);
}
}
for (const label of currLabels) {
if (!labelsInText.includes(labelsInverse[label])) {
labelsInText.push(labelsInverse[label]);
}
}
return text.split("\n")[0] + "\n\n" +
labelsInText.filter((v) => v).map((v) => `· ${v}`).join("\n");
}
const other = { parse_mode: "MarkdownV2" as const };
// deno-lint-ignore no-explicit-any
async function updateLabels(payload: any) {
if (
labelNames.includes(
payload.label.name,
)
) {
const notification = await db.getNotification(
payload.pull_request.number,
);
if (notification) {
const updatedText = getUpdatedText(
notification.text,
// deno-lint-ignore no-explicit-any
payload.pull_request.labels.map((v: any) => v.name),
);
if (updatedText != notification.text) {
await bot.api.editMessageText(
env.CHAT_ID,
notification.messageId,
updatedText,
other,
);
await db.updateNotification(
notification.messageId,
updatedText,
);
}
}
}
}
app.use(async (ctx) => {
let payload;
try {
payload = await ctx.request.body().value;
} catch (_err) {
return;
}
if (payload.repository.full_name == "grammyjs/website") {
switch (payload.action) {
case "labeled": {
switch (payload.label.name) {
case "ready for translation": {
const text =
`[\\#${payload.pull_request.number}](${payload.pull_request.html_url}) with ${payload.pull_request.additions} addition${
payload.pull_request.additions != 1 ? "s" : ""
} and ${payload.pull_request.deletions} deletion${
payload.pull_request.deletions != 1 ? "s" : ""
} is ready for translation\\.`;
const notification = await db.getNotification(
payload.pull_request.number,
);
if (notification) {
await bot.api.editMessageText(
env.CHAT_ID,
notification.messageId,
text,
other,
);
await db.updateNotification(notification.messageId, text);
} else {
const notification = await bot.api.sendMessage(
env.CHAT_ID,
text,
other,
);
await bot.api.pinChatMessage(
env.CHAT_ID,
notification.message_id,
);
await db.createNotification(
payload.pull_request.number,
notification.message_id,
text,
);
}
break;
}
default: {
await updateLabels(payload);
}
}
break;
}
case "unlabeled": {
switch (payload.label.name) {
case "ready for translation": {
const notification = await db.getNotification(
payload.pull_request.number,
);
if (notification) {
await bot.api.editMessageText(
env.CHAT_ID,
notification.messageId,
`~${notification.text}~`,
other,
);
}
break;
}
default: {
await updateLabels(payload);
}
}
break;
}
case "closed": {
if (payload.pull_request) {
const notification = await db.getNotification(
payload.pull_request.number,
);
if (notification) {
await bot.api.editMessageText(
env.CHAT_ID,
notification.messageId,
`__${notification.text}__`,
other,
);
await bot.api.unpinChatMessage(
env.CHAT_ID,
notification.messageId,
);
await db.deleteNotification(payload.pull_request.number);
}
}
break;
}
}
}
ctx.response.status = 200;
});
const promises = [db.connect(), app.listen({ port: 8000 })];
if (Deno.env.get("DEBUG")) {
promises.push(bot.start({ drop_pending_updates: true }));
}
await Promise.all(promises);