This repository has been archived by the owner on Dec 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
App.js
180 lines (167 loc) · 4.73 KB
/
App.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
/**
* @author IITII <[email protected]>
* @date 2020/11/3 22:34
*/
'use strict';
const axios = require('axios'),
{load} = require('cheerio'),
config = require('./config.js'),
fs = require('fs'),
readline = require('readline'),
{mapLimit} = require('async'),
{uniq} = require('lodash'),
{logger} = require('./logger'),
path = require('path');
function init() {
try {
if (!fs.existsSync(config.links)) {
logger.error(`File NOT FOUND:${path.resolve(config.links)}`);
process.exit(1);
}
if (!fs.existsSync(config.downloadDir)) {
fs.mkdirSync(config.downloadDir);
logger.info(`Created ${path.resolve(config.downloadDir)}`);
}
fs.accessSync(config.links, fs.constants.R_OK);
//Init axios
axios.defaults.timeout = 3000;
axios.defaults.proxy = config.proxy;
axios.defaults.headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36";
} catch (err) {
logger.error(`Unable to read file: ${config.links}!`);
process.exit(1)
}
}
/**
* Checks if value is null or undefined or ''.
* @param object object
* @return {boolean} true for nil or ''
*/
function isNil(object) {
return (object == null) || (object === '');
}
function mkdir(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath)
}
}
/**
* Calc how much time spent on run function.
* @param func Run function
* @param args function's args
*/
async function spendTime(func, ...args) {
return await new Promise(async (resolve, reject) => {
let start = new Date();
try {
await func.apply(this, args);
return resolve();
} catch (e) {
logger.error(e);
return reject();
} finally {
let cost = new Date() - start;
let logInfo = cost > 1000 ? cost / 1000 + 's' : cost + 'ms';
logger.info(`Total spent ${logInfo}.`);
}
});
}
async function getUrl(filePath) {
let rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
const links = [];
for await (let line of rl) {
line = line.trim().replace("\n", "");
if (isNil(line)) {
continue;
}
links.push(line);
}
return uniq(links);
}
async function getImageArray(url) {
return await new Promise((resolve) => {
logger.info(`Getting image urls from ${url}`)
axios.get(url, {
responseType: "document",
})
.then(res => res.data)
.then(doc => load(doc))
.then($ => {
const title = $('header h1').text();
const saveDir = path.resolve(config.downloadDir + path.sep + title);
mkdir(saveDir);
const imgSrc = [];
$("img").each((index, item) => {
imgSrc.push({
url: new URL(url).origin + item.attribs.src,
savePath: path.resolve(saveDir + path.sep + (index + 1) + path.extname(item.attribs.src))
});
});
return resolve(uniq(imgSrc));
})
.catch(e => {
logger.error(`Get ImageArray failed, url: ${url}`);
logger.error(e);
return resolve([]);
});
})
}
async function downloadFile(url, filePath, callback) {
return await new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(filePath);
logger.info(`Downloading ${url}...`)
axios.get(url, {
responseType: "stream",
})
.then(res => {
writeStream.on('finish', resolve);
writeStream.on('error', reject);
res.data.pipe(writeStream);
})
.then(() => logger.info(`Downloaded ${url} to ${filePath}`))
.catch(e => {
logger.error(`Download error: ${e.message}`);
logger.error(e);
return reject({
url: url,
filePath: filePath
});
})
.finally(callback);
})
}
(async () => {
init();
const urls = await getUrl(config.links);
const downloadFailed = [];
// update axios settings
axios.defaults.timeout = Math.max(urls.length, 3) * 1000;
logger.info(`Total urls: ${urls.length}`);
let imagesUrl = [];
await Promise.all(urls.map(url => getImageArray(url)))
.then(matrix => imagesUrl = matrix.flat(Infinity))
.catch(e => logger.error(e))
await spendTime(async () => {
await mapLimit(imagesUrl, config.limit || 10, async function (json, callback) {
await downloadFile(json.url, json.savePath, callback)
.catch(e => {
downloadFailed.push(e);
});
})
.catch(e => logger.error(e))
})
.then(() => logger.info(`Download complete!`))
.catch(e => {
logger.error(`Download Error: ${e.message}`);
logger.error(e);
})
.finally(() => {
//Show failed url
if (downloadFailed.length !== 0) {
logger.error(downloadFailed);
}
})
})()