-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
207 lines (186 loc) · 6.67 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
const puppeteer = require('puppeteer');
const clc = require("cli-color");
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const FileType = require('file-type');
fs.mkdirSync(path.resolve(__dirname, 'images'), {recursive: true});
const imgDir = path.resolve(__dirname, 'images')
const myArgs = process.argv.slice(2);
const threadId = myArgs[0];
const startPage = myArgs[1];
let headFull = myArgs[2];
headFull = !!(headFull);
let ImgUrlsDone = [];
let downloadImage = async (url) => {
return new Promise(async (resolve, reject) => {
if (!url.startsWith("http:")) {
url = `http:${url}`;
}
if (ImgUrlsDone.includes(url)) {
console.log(clc.yellow(`\nDownload Skipped Duplicate: ${url}`));
resolve();
return;
} else {
ImgUrlsDone.push(url);
}
const filePath = path.resolve(imgDir, `${Date.now()}_${Math.floor(Math.random() * 100000) + 10000}.part`)
const writer = fs.createWriteStream(filePath)
let response = null;
let downloadSuccess = true;
let zeroLength = false
try {
let retryCount = 10;
do {
response = await axios({
url,
method: 'GET',
responseType: 'stream',
timeout: 10000
});
retryCount--;
} while (retryCount > 0 && response.length == 0);
if (response.length == 0) {
zeroLength = true;
throw Error('Zero Length File');
}
response.data.pipe(writer);
} catch (error) {
downloadSuccess = false;
writer.end();
let errorCode = null;
if (
error &&
typeof error === "object" &&
error.hasOwnProperty('response') &&
typeof error.response === "object" &&
error.response.hasOwnProperty('status')
) {
errorCode = error.response.status
}
if (zeroLength) {
console.log(clc.yellow(`\nDownload Failed: ${url}`, "Zero Length File"));
} else {
console.log(clc.yellow(`\nDownload Failed: ${url}`, errorCode));
}
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
writer.on('finish', async () => {
if (
response &&
typeof response === "object" &&
response.hasOwnProperty('headers') &&
response.headers.hasOwnProperty('content-type') &&
response.headers['content-type'].includes('text/html')
) {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
} else if(downloadSuccess){
console.log(clc.green(`\nDownload Success: ${url}`));
}
resolve()
});
writer.on('error', (error) => {
console.log(clc.red(`\nWrite Stream Error: ${url}`));
console.log(error)
reject();
});
});
}
let nameFilesBasedOnMime = async (file) => {
file = path.resolve(imgDir, file);
if (fs.existsSync(file)) {
try {
let stream = fs.createReadStream(file);
let mimeInfo = await FileType.fromStream(stream);
if (!!(mimeInfo) && mimeInfo.hasOwnProperty('ext')) {
let newFileBase = file.split('.').slice(0, -1)
fs.renameSync(file, `${newFileBase}.${mimeInfo.ext}`);
} else {
console.log(clc.red(`\nNo mime for file: ${file}`));
}
} catch(error) {
console.log(clc.red(`\nError on mime based rename for file: ${file}`));
console.log(error);
}
}
}
let delay = (timeout) => {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
}
let asyncForEach = async (array, callback) => {
let parallel = [];
for (let index = 0; index < array.length; index++) {
parallel.push(callback(array[index], index, array));
}
await Promise.all(parallel)
}
let main = async (threadId, pageNumber) => {
const browser = await puppeteer.launch({
headless: !headFull,
ignoreHTTPSErrors: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
});
try {
const page = await browser.newPage();
let threadUrl = "http://www.elakiri.com/forum/showthread.php?t=" + threadId + "&page=" + pageNumber
await page.setRequestInterception(true);
await page.on('request', (req) => {
if(req.resourceType() === 'image'){
req.abort();
}
else {
req.continue();
}
});
await page.goto(threadUrl);
let imgUrls = [];
let endOfPages = false;
while (!endOfPages) {
pageNumber++;
console.log(clc.black.bgGreenBright.underline(`Went to page: ${page.url()}`));
await page.addScriptTag({path: require.resolve('jquery')})
imgUrls = await page.$$eval('article.message-body img.bbImage', imgs => imgs.map(img => img.getAttribute('src')));
console.log(clc.black.bgGreenBright.underline(`Found ${(imgUrls.length)} matches`));
await asyncForEach(imgUrls, downloadImage);
let dirCont = fs.readdirSync(imgDir);
let files = dirCont.filter(function (elm) {
return elm.match(/.*\.(part)/ig);
});
await asyncForEach(files, nameFilesBasedOnMime);
if (await page.$('div.pageNav a.pageNav-jump--next') === null) {
endOfPages = true;
pageNumber = 0;
break;
}
console.log(`\nGoing to Page: ${pageNumber}\n`);
await Promise.all([
page.click('div.pageNav a.pageNav-jump--next', {waitUntil: 'domcontentloaded'}),
page.waitForNavigation({waitUntil: 'networkidle0'}),
]);
}
} catch (error) {
pageNumber++;
console.log(clc.black.bgCyanBright(`Skipping to page ${(pageNumber)} due to ${(error.message)}`));
console.log('\n');
} finally {
await delay(3000);
await browser.close();
return pageNumber;
}
};
(async function() {
try {
let pgNumber = startPage ? startPage : 1;
while (pgNumber > 0) {
pgNumber = await main(threadId, pgNumber);
}
} catch (error) {
console.error(error);
}
})();