-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
429 lines (340 loc) · 12.1 KB
/
index.js
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
const { Telegraf } = require('telegraf');
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const { PDFDocument, rgb } = require('pdf-lib');
const sharp = require('sharp');
const path = require('path');
const express = require("express");
// const pTimeout = require("p-timeout");
// For uptime API to keep the bot alive
const app = express();
const PORT = process.env.PORT || 3000;
const startTime = Date.now();
app.get("/uptime", (req, res) => {
const currentTime = Date.now();
const uptimeMilliseconds = currentTime - startTime;
const uptimeSeconds = Math.floor(uptimeMilliseconds / 1000);
res.json({
uptime: `${uptimeSeconds} seconds`,
});
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
const botToken = process.env.BOT_TOKEN;
const bot = new Telegraf(botToken);
bot.start((ctx) => {
ctx.reply('Welcome to the Image to PDF bot! Please send me the URL of the images you want to convert to PDF.');
});
bot.help((ctx) => {
ctx.reply(
'Welcome to AsuraScans – Downloader!\n\n' +
'/dl {chapter_url} or just send the chapter_url: Download a specific chapter. \n\n/mdl {chapter_url} | {start_chapter} -> {end_chapter}: Download a range of chapters. \n\n/help: View available commands and instructions.'
);
});
bot.on('text', async (ctx) => {
const messageText = ctx.message.text;
const match = messageText.match(/(https:\/\/www\.mangapill\.com\/manga\/\d+\/[\w-]+) \| (\d+) -> (\d+)/);
if (!match) {
ctx.reply('Invalid command format. Please use "URL | startCh -> endCh".');
return;
}
const url = match[1];
const startPoint = parseInt(match[2]);
const endPoint = parseInt(match[3]);
if (isNaN(startPoint) || isNaN(endPoint) || startPoint <= 0 || endPoint <= 0 || startPoint > endPoint) {
ctx.reply('Invalid chapter range. Please provide valid starting and ending chapter numbers.');
return;
}
try {
const downloadingMessage = await ctx.reply('Downloading, please wait...', {
reply_to_message_id: ctx.message.message_id,
});
const urlsJson = await scrapeChapterUrl(url);
const chapterUrls = getChapterUrls(startPoint, endPoint, urlsJson);
console.log(chapterUrls);
await processAllChapters(chapterUrls, ctx);
await ctx.telegram.editMessageText(
downloadingMessage.chat.id,
downloadingMessage.message_id,
null,
'All chapters Downloaded successfully.'
);
} catch (error) {
console.error('Error:', error);
ctx.reply('An error occurred while processing the URL.');
}
});
const folderPath = 'tmp';
deleteAllFilesAndFoldersInFolder(folderPath);
bot.launch();
async function scrapeImagesAsura(url) {
try {
const folderName = "tmp/" + url.split('/').filter(Boolean).pop().replace(/^(\d+-)/, '');
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const readerArea = $('#readerarea');
const imgElements = readerArea.find('img[decoding="async"][src]');
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
const imgSrcArray = [];
imgElements.each((index, element) => {
const imgSrc = $(element).attr('src');
imgSrcArray.push(imgSrc);
});
for (let i = 0; i < imgSrcArray.length; i++) {
const imgSrc = imgSrcArray[i];
if (imgSrc) {
const imgName = path.basename(imgSrc);
const imgPath = path.join(folderName, imgName);
await axios({
method: 'get',
url: imgSrc,
responseType: 'stream',
}).then((response) => {
response.data.pipe(fs.createWriteStream(imgPath));
console.log(`Downloaded: ${imgPath}`);
}).catch((error) => {
console.error(`Error downloading image: ${imgSrc}`);
});
}
}
return folderName;
} catch (error) {
console.error('Error:', error);
}
}
function getAllFilesInFolder(folderPath) {
const allFiles = [];
function traverseDirectory(currentPath) {
const files = fs.readdirSync(currentPath, { withFileTypes: true });
for (const file of files) {
const filePath = path.join(currentPath, file.name);
if (file.isFile()) {
allFiles.push(filePath);
} else if (file.isDirectory()) {
traverseDirectory(filePath);
}
}
}
traverseDirectory(folderPath);
return allFiles;
}
async function createPdfFromImages(folderName) {
try {
const pdfPath = folderName + '.pdf';
const imageFiles = fs.readdirSync(folderName);
const pdfDoc = await PDFDocument.create();
const pdfPages = [];
console.log('function imageFiles: ', imageFiles)
const allFiles = getAllFilesInFolder(folderPath);
console.log('All files:', allFiles);
for (const imageFile of imageFiles) {
const imagePath = path.join(folderName, imageFile);
let imageExtension = path.extname(imageFile).toLowerCase();
console.log(imagePath);
try {
const { width: imageWidth, height: imageHeight } = await sharp(imagePath).metadata();
const pdfPage = pdfDoc.addPage([imageWidth, imageHeight]);
const image = await sharp(imagePath).toBuffer();
let imageXObject;
if (imageExtension === '.png') {
const pngImageBuffer = fs.readFileSync(imagePath); // Read the PNG image
imageXObject = await pdfDoc.embedPng(pngImageBuffer);
} else if (imageExtension === '.jpeg') {
imageXObject = await pdfDoc.embedJpg(image);
} else {
console.log("something error jpg png")
}
// console.log(imageXObject);
pdfPage.drawImage(imageXObject, {
x: 0,
y: 0,
width: imageWidth,
height: imageHeight,
});
pdfPages.push(pdfPage);
} catch (imageError) {
console.error(`Error processing image: ${imagePath}`, imageError);
continue;
}
}
for (const pdfPage of pdfPages) {
pdfPage.setFontSize(12);
pdfPage.drawText('tg@misfitsdev', {
x: 30,
y: 30,
color: rgb(0, 0, 0),
});
}
const pdfBytes = await pdfDoc.save();
fs.writeFileSync(pdfPath, pdfBytes);
return pdfPath;
} catch (error) {
console.error('Error creating PDF from images:', error);
throw error;
}
}
async function cleanup(folderName, pdfPath) {
try {
fs.rmSync(folderName, { recursive: true });
fs.unlinkSync(pdfPath);
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('Cleanup error:', error);
}
}
async function scrapeChapterUrl(url) {
try {
const baseUrl = new URL(url).origin;
const folderPath = 'chapters';
const fileName = path.join(folderPath, path.basename(url) + '.json');
if (fs.existsSync(fileName)) {
console.log(`File ${fileName} already exists.`);
return fileName
} else {
console.log(`File ${fileName} does not exist. Proceed with file creation.`);
}
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const divWithFilterList = $('div[data-filter-list]');
const aElements = divWithFilterList.find('a');
const hrefArray = [];
aElements.each((index, element) => {
const href = $(element).attr('href');
if (href) {
const completeHref = href.startsWith('http') ? href : baseUrl + href;
hrefArray.push(completeHref);
}
});
const reversedArray = hrefArray.reverse();
const jsonContent = {
mangaName: path.basename(url),
baseUrl: url,
reversedHrefValues: reversedArray,
};
const jsonString = JSON.stringify(jsonContent, null, 2);
// const folderPath = 'chapters';
// const fileName = path.join(folderPath, path.basename(url) + '.json');
fs.writeFileSync(fileName, jsonString);
return fileName;
} catch (error) {
console.error('Error:', error);
}
}
function getChapterUrls(startPoint, endPoint, urlsJson) {
try {
// Read the JSON file containing the URLs
const jsonData = fs.readFileSync(urlsJson, 'utf-8');
const mangaUrls = JSON.parse(jsonData);
// Filter the URLs based on the specified range
const matchingUrls = mangaUrls.reversedHrefValues.filter((url) => {
const match = url.match(/-([0-9]+)$/);
if (match) {
const chapterNumber = parseInt(match[1]);
return chapterNumber >= startPoint && chapterNumber <= endPoint;
}
return false;
});
return matchingUrls; // Return the array of matching URLs
} catch (error) {
console.error('Error:', error);
return []; // Return an empty array in case of an error
}
}
async function scrapeImagesMangapill(url) {
try {
const folderName = "tmp/" + url.split('/').filter(Boolean).pop().replace(/^(\d+-)/, '');
// Make a GET request to the URL
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const readerArea = $('.relative.bg-card.flex.justify-center.items-center');
const imgElements = readerArea.find('img[data-src]');
// Create a directory for the images
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
// Create an array to store the image source URLs
const imgSrcArray = [];
// Loop through the img elements and collect the image source URLs
imgElements.each((index, element) => {
const imgSrc = $(element).attr('data-src');
imgSrcArray.push(imgSrc);
});
console.log(imgSrcArray);
for (let i = 0; i < imgSrcArray.length; i++) {
const imgSrc = imgSrcArray[i];
// Check if imgSrc is defined
if (imgSrc) {
const imgName = path.basename(imgSrc);
const imgPath = path.join(folderName, imgName);
// Define custom headers
const headers = {
'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
'Referer': 'https://www.mangapill.com/',
'DNT': '1',
'sec-ch-ua-mobile': '?0',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
'sec-ch-ua-platform': '"Windows"',
};
// Download the image with custom headers
await axios({
method: 'get',
url: imgSrc,
responseType: 'stream',
headers: headers,
}).then((response) => {
response.data.pipe(fs.createWriteStream(imgPath));
console.log(`Downloaded: ${imgPath}`);
}).catch((error) => {
console.error(`Error downloading image: ${imgSrc}`);
});
}
}
return folderName;
} catch (error) {
console.error('Error:', error);
}
}
async function processAllChapters(chapterUrls, ctx) {
try {
for (const url of chapterUrls) {
try {
// const folderName = await scrapeImagesMangapill(url);
const folderName = await scrapeImagesMangapill(url);
const pdfPath = await createPdfFromImages(folderName);
const pdfFileName = path.basename(pdfPath);
await ctx.replyWithDocument({ source: pdfPath }, { filename: pdfFileName });
cleanup(folderName, pdfPath);
console.log(`Chapter processed successfully: ${url}`);
} catch (error) {
console.error('Error processing chapter:', error);
}
}
console.log('All chapters Downloaded successfully');
} catch (error) {
console.error('Error processing chapters:', error);
}
}
// tmp folder cleaner
function deleteAllFilesAndFoldersInFolder(folderPath) {
fs.readdirSync(folderPath).forEach((file) => {
const filePath = path.join(folderPath, file);
if (fs.statSync(filePath).isFile()) {
fs.unlinkSync(filePath);
console.log(`Deleted file: ${file}`);
} else if (fs.statSync(filePath).isDirectory()) {
// Recursively delete subdirectories and their contents
deleteAllFilesAndFoldersInFolder(filePath);
// After deleting the directory's contents, delete the directory itself
fs.rmdirSync(filePath);
console.log(`Deleted directory: ${file}`);
}
});
}
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// You can add additional error handling logic here if needed
});