-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
370 lines (306 loc) · 11.6 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
process.env.NTBA_FIX_319 = "1"; //fix node-telegram-bot-api promise cancelation
import config from "./config";
import rezka from "./modules/rezka";
import YummyAnime from "./modules/yummyanime";
import * as fs from "fs";
import "ag-psd/initialize-canvas.js";
import { Client } from "tdl";
import { TDLib } from "tdl-tdlib-addon";
import inquirer from "inquirer";
import TelegramBot from "node-telegram-bot-api";
import ParseModule from "./modules/ParseModule";
import cf_bypass from "./cf-bypass";
import { message, messages } from "tdlib-types";
import EventEmitter from "events";
import {
randomNumber,
log,
getVideoDuration,
generateThumbnail,
wait,
} from "./utils";
let tgClient: Client;
const cfBypass = new cf_bypass();
const modules: ParseModule[] = [new rezka(cfBypass), new YummyAnime(cfBypass)];
const events = new EventEmitter();
//Trying to connect to telegram server and auth
(async () => {
const bot = new TelegramBot(config.telegramBotToken, {
polling: true,
});
let queue: string[] = [];
let disabling = false;
if (config.telegram.appId && config.telegram.apiHash) {
//Init telegram client with tdlib (not a bot)
tgClient = new Client(new TDLib(), {
apiId: config.telegram.appId,
apiHash: config.telegram.apiHash,
verbosityLevel: 0,
});
await tgClient.connect();
await tgClient.login(() => ({
getPhoneNumber: (retry) =>
retry
? Promise.reject("Invalid phone number")
: Promise.resolve(config.telegram.phone),
getAuthCode: (retry) =>
retry
? Promise.reject("Invalid auth code")
: Promise.resolve(config.telegram.code),
getPassword: (_, retry) =>
retry
? Promise.reject("Invalid password")
: Promise.resolve(config.telegram.password),
getName: () =>
Promise.resolve({
firstName: config.telegram.firstName,
lastName: config.telegram.lastName,
}),
}));
//tgClient.on("error", console.error);
tgClient.on("update", (val) => {
if (
val._ == "updateChatLastMessage" &&
val.last_message.chat_id == config.telegramTrashGroup
) {
events.emit("newMessage", val.last_message);
}
});
} else {
log(
"Телеграм (tdlib) не загружен, видео не будут выгружаться в паблик."
);
}
//Create temp folder for templ files (like exported jpg poster and videos)
if (!fs.existsSync("./temp")) fs.mkdirSync("./temp");
sendPrompt();
let working = false;
async function checkNextLink(userId: number) {
if (queue.length == 0 || working) return;
working = true;
const link = queue.shift();
const module = getWorkingModule(link);
if (!module) {
working = false;
return bot.sendMessage(
userId,
`Ссылка "${link}" не кажется мне знакомой`
);
}
await bot.sendMessage(userId, `Начинаю обрабатывать ${link}`);
//Parsing sites
const parsed = await module.parseObjects(link);
if (!parsed) {
working = false;
return await bot.sendMessage(
userId,
"Произошла ошибка при парсинге, не удалось получить ссылку!"
);
}
const outText = module.getOutText(parsed);
//if we have urls - downloaded them
if (parsed.movieLink && parsed.movieLink.length) {
await bot.sendMessage(
userId,
`Скачиваю ${parsed.movieLink.length > 1 ? "серии" : "фильм"}...`
);
//Download a movie
const video = await module.downloadMovie(parsed.movieLink);
if (video) {
const duration = await getVideoDuration(video);
await bot.sendMessage(userId, "Делаю фотку 1");
await generateThumbnail(
video,
randomNumber(30, Math.min(duration, 300))
);
await bot.sendMessage(userId, "Делаю фотку 2");
await generateThumbnail(
video,
randomNumber(50, Math.min(duration, 400)),
2
);
parsed.tempVideoName = video;
//generating psd file and drawing with canvas a poster
const templateName = await module.writePsd(parsed);
await bot.sendMessage(
userId,
`${
parsed.movieLink.length > 1 ? "Аниме" : "Фильм"
} успешно скачан, высылаю в паблик`
);
//sending poster(jpg, psd) and video to trash-channel
await sendPost(
userId,
video,
templateName,
outText,
parsed.name,
duration
);
//if we not connected to telegram - save files cuz we not uploading to public
if (tgClient) {
//delete all temp files after upload
fs.unlinkSync(`./temp/${templateName}.psd`);
fs.unlinkSync(`./temp/${templateName}.jpg`);
fs.unlinkSync(`./temp/${video}.mp4`);
}
}
}
await bot.sendMessage(userId, outText);
await wait(1);
working = false;
checkNextLink(userId);
}
bot.on("message", async (message) => {
if (disabling) return;
if (!message || !message.chat || !message.text)
return bot.sendMessage(message.chat.id, "Не надо так");
if (!config.telegramAdmins.includes(message.chat.id))
return bot.sendMessage(message.chat.id, "Ты кто!?");
//if we writed command
if (message.text.startsWith("/")) {
const command = message.text.replace("/", "");
switch (command) {
case "restartb": {
await bot.sendMessage(message.chat.id, "Перезапускаюсь");
process.exit(1);
}
}
return;
}
queue.push(message.text);
checkNextLink(message.chat.id);
if (queue.length)
bot.sendMessage(message.chat.id, "Ссылка добавлена в очередь");
});
async function awaitTelegramMessage(
message: Promise<void | message | messages>
): Promise<void> {
const anyMessage = await (message as any);
const msg: message[] = [];
if (!anyMessage) return Promise.resolve();
if ((anyMessage as messages).messages)
msg.push(...(anyMessage as messages).messages);
else msg.push(anyMessage as message);
return new Promise((resolve) => {
const isNeededMessage = (message: message) => {
return msg.some((msg) => message.content._ == msg.content._);
};
const checkLoad = (msg: message) => {
if (isNeededMessage(msg)) {
events.removeListener("newMessage", checkLoad);
resolve();
}
};
events.on("newMessage", checkLoad);
});
}
async function sendPost(
userId: number,
video: string,
photo: string,
outText: string,
name: string,
videoDuration: number
): Promise<void | message | messages> {
if (!tgClient) {
bot.sendMessage(
userId,
"Телеграм не подключён, видео не загрузится в паблик."
);
return Promise.resolve();
}
//send poster(jpg) and video as album
await awaitTelegramMessage(
tgClient
.invoke({
_: "sendMessageAlbum",
chat_id: config.telegramTrashGroup,
input_message_contents: [
{
_: "inputMessageVideo",
video: {
_: "inputFileLocal",
path: `./temp/${video}.mp4`,
},
caption: {
_: "formattedText",
text: name,
},
supports_streaming: true,
duration: videoDuration,
},
{
_: "inputMessagePhoto",
photo: {
_: "inputFileLocal",
path: `./temp/${photo}.jpg`,
},
},
],
})
.catch((err) => {
if (err.message) {
bot.sendMessage(userId, err.message);
}
console.log(err);
})
);
return awaitTelegramMessage(
tgClient
.invoke({
_: "sendMessage",
chat_id: config.telegramTrashGroup,
input_message_content: {
_: "inputMessageText",
text: {
_: "formattedText",
text: outText,
},
},
})
.catch((err) => {
if (err.message) {
bot.sendMessage(userId, err.message);
}
console.log(err);
})
);
}
//Mini-console for some commands
function sendPrompt() {
inquirer
.prompt({
type: "input",
name: "command",
message: "Команда:",
})
.then(async (command) => {
if (disabling) return;
if (command.command) {
if (command.command === "exit") {
disabling = true;
log("Сворачиваемся пацаны");
process.exit();
} else {
if (command.command !== "help") {
log("Сорь, команду не нашёл. Вот тебе список:");
command.command = "help";
}
}
if (command.command === "help") {
log("exit - выйти в окно (выключиться)");
}
}
sendPrompt();
});
}
})();
function getWorkingModule(url: string): ParseModule {
if (!url || !(url.startsWith("https://") || url.startsWith("http://")))
return null;
const link = url.match(/\/\/(.*?)\//)[1];
for (let i = 0; i < modules.length; i++)
if (modules[i].getSite().includes(link)) return modules[i];
return null;
}