-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsingle-file-cli-api.js
294 lines (276 loc) · 9.56 KB
/
single-file-cli-api.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
/*
* Copyright 2010-2020 Gildas Lormeau
* contact : gildas.lormeau <at> gmail.com
*
* This file is part of SingleFile.
*
* The code in this file is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* (GNU AGPL) as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* The code in this file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* As additional permission under GNU AGPL version 3 section 7, you may
* distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
* AGPL normally required by section 4, provided you include this license
* notice and a URL through which recipients can access the Corresponding
* Source.
*/
/* global require, exports, URL, process */
const fs = require("fs");
const path = require("path");
const VALID_URL_TEST = /^(https?|file):\/\//;
const DEFAULT_OPTIONS = {
removeHiddenElements: true,
removeUnusedStyles: true,
removeUnusedFonts: true,
removeSavedDate: false,
removeFrames: false,
compressHTML: true,
compressCSS: false,
loadDeferredImages: true,
loadDeferredImagesMaxIdleTime: 1500,
loadDeferredImagesBlockCookies: false,
loadDeferredImagesBlockStorage: false,
loadDeferredImagesKeepZoomLevel: false,
loadDeferredImagesDispatchScrollEvent: false,
filenameTemplate: "{page-title} ({date-locale} {time-locale}).html",
infobarTemplate: "",
includeInfobar: false,
filenameMaxLength: 192,
filenameMaxLengthUnit: "bytes",
filenameReplacedCharacters: ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\x00-\x1f", "\x7F"],
filenameReplacementCharacter: "_",
maxResourceSizeEnabled: false,
maxResourceSize: 10,
backgroundSave: true,
removeAlternativeFonts: true,
removeAlternativeMedias: true,
removeAlternativeImages: true,
saveRawPage: false,
resolveFragmentIdentifierURLs: false,
userScriptEnabled: false,
saveFavicon: true,
includeBOM: false,
insertMetaCSP: true,
insertMetaNoIndex: false,
password: "",
insertSingleFileComment: true,
blockImages: false,
blockStylesheets: false,
blockFonts: false,
blockScripts: true,
blockVideos: true,
blockAudios: true
};
const STATE_PROCESSING = "processing";
const STATE_PROCESSED = "processed";
const backEnds = {
jsdom: "./back-ends/jsdom.js",
puppeteer: "./back-ends/puppeteer.js",
"puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
"webdriver-chromium": "./back-ends/webdriver-chromium.js",
"webdriver-gecko": "./back-ends/webdriver-gecko.js",
"playwright-firefox": "./back-ends/playwright-firefox.js",
"playwright-chromium": "./back-ends/playwright-chromium.js",
"playwright-webkit": "./back-ends/playwright-webkit.js"
};
let backend, tasks = [], maxParallelWorkers = 8, sessionFilename;
exports.getBackEnd = backEndName => require(backEnds[backEndName]);
exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
exports.VALID_URL_TEST = VALID_URL_TEST;
exports.initialize = initialize;
async function initialize(options) {
options = Object.assign({}, DEFAULT_OPTIONS, options);
maxParallelWorkers = options.maxParallelWorkers;
backend = require(backEnds[options.backEnd]);
await backend.initialize(options);
if (options.crawlSyncSession || options.crawlLoadSession) {
try {
tasks = JSON.parse(fs.readFileSync(options.crawlSyncSession || options.crawlLoadSession).toString());
} catch (error) {
if (options.crawlLoadSession) {
throw error;
}
}
}
if (options.crawlSyncSession || options.crawlSaveSession) {
sessionFilename = options.crawlSyncSession || options.crawlSaveSession;
}
return {
capture: urls => capture(urls, options),
finish: () => finish(options)
};
}
async function capture(urls, options) {
let newTasks;
const taskUrls = tasks.map(task => task.url);
newTasks = urls.map(url => createTask(url, options));
newTasks = newTasks.filter(task => task && !taskUrls.includes(task.url));
if (newTasks.length) {
tasks = tasks.concat(newTasks);
saveTasks();
}
await runTasks();
}
async function finish(options) {
const promiseTasks = tasks.map(task => task.promise);
await Promise.all(promiseTasks);
if (!options.browserDebug) {
return backend.closeBrowser();
}
}
async function runTasks() {
const availableTasks = tasks.filter(task => !task.status).length;
const processingTasks = tasks.filter(task => task.status == STATE_PROCESSING).length;
const promisesTasks = [];
for (let workerIndex = 0; workerIndex < Math.min(availableTasks, maxParallelWorkers - processingTasks); workerIndex++) {
promisesTasks.push(runNextTask());
}
return Promise.all(promisesTasks);
}
async function runNextTask() {
const task = tasks.find(task => !task.status);
if (task) {
const options = task.options;
let taskOptions = JSON.parse(JSON.stringify(options));
taskOptions.url = task.url;
task.status = STATE_PROCESSING;
saveTasks();
task.promise = capturePage(taskOptions);
const pageData = await task.promise;
task.status = STATE_PROCESSED;
if (pageData) {
task.filename = pageData.filename;
if (options.crawlLinks && testMaxDepth(task)) {
let newTasks = pageData.links
.map(urlLink => createTask(urlLink, options, task, tasks[0]))
.filter(task => task &&
testMaxDepth(task) &&
!tasks.find(otherTask => otherTask.url == task.url) &&
(!options.crawlInnerLinksOnly || task.isInnerLink) &&
(!options.crawlNoParent || (task.isChild || !task.isInnerLink)));
tasks.splice(tasks.length, 0, ...newTasks);
}
}
saveTasks();
await runTasks();
}
}
function testMaxDepth(task) {
const options = task.options;
return (options.crawlMaxDepth == 0 || task.depth <= options.crawlMaxDepth) &&
(options.crawlExternalLinksMaxDepth == 0 || task.externalLinkDepth < options.crawlExternalLinksMaxDepth);
}
function createTask(url, options, parentTask, rootTask) {
url = parentTask ? rewriteURL(url, options.crawlRemoveURLFragment, options.crawlRewriteRules) : url;
if (VALID_URL_TEST.test(url)) {
const isInnerLink = rootTask && url.startsWith(getHostURL(rootTask.url));
const rootBaseURIMatch = rootTask && rootTask.url.match(/(.*?)[^/]*$/);
const isChild = isInnerLink && rootBaseURIMatch && rootBaseURIMatch[1] && url.startsWith(rootBaseURIMatch[1]);
return {
url,
isInnerLink,
isChild,
originalUrl: url,
rootBaseURI: rootBaseURIMatch && rootBaseURIMatch[1],
depth: parentTask ? parentTask.depth + 1 : 0,
externalLinkDepth: isInnerLink ? -1 : parentTask ? parentTask.externalLinkDepth + 1 : -1,
options
};
}
}
function saveTasks() {
if (sessionFilename) {
fs.writeFileSync(sessionFilename, JSON.stringify(
tasks.map(task => Object.assign({}, task, {
status: task.status == STATE_PROCESSING ? undefined : task.status,
promise: undefined,
options: task.status && task.status == STATE_PROCESSED ? undefined : task.options
}))
));
}
}
function rewriteURL(url, crawlRemoveURLFragment, crawlRewriteRules) {
url = url.trim();
if (crawlRemoveURLFragment) {
url = url.replace(/^(.*?)#.*$/, "$1");
}
crawlRewriteRules.forEach(rewriteRule => {
const parts = rewriteRule.trim().split(/ +/);
if (parts.length) {
url = url.replace(new RegExp(parts[0]), parts[1] || "").trim();
}
});
return url;
}
function getHostURL(url) {
url = new URL(url);
return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
}
async function capturePage(options) {
try {
let filename;
options.zipScript = fs.readFileSync(require.resolve("./lib/single-file-zip.min.js")).toString();
const pageData = await backend.getPageData(options);
if (options.output) {
filename = getFilename(options.output, options);
} else if (options.dumpContent) {
await new Promise(resolve => process.stdout.write(pageData.content, resolve));
} else {
filename = getFilename(pageData.filename, options);
}
if (filename) {
const dirname = path.dirname(filename);
if (dirname) {
fs.mkdirSync(dirname, { recursive: true });
}
fs.writeFileSync(filename, pageData.content);
}
return pageData;
} catch (error) {
const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
if (options.errorFile) {
fs.writeFileSync(options.errorFile, message, { flag: "a" });
} else {
console.error(error.message || error, message); // eslint-disable-line no-console
}
}
}
function getFilename(filename, options, index = 1) {
if (Array.isArray(options.outputDirectory)) {
const outputDirectory = options.outputDirectory.pop();
if (outputDirectory.startsWith("/")) {
options.outputDirectory = outputDirectory;
} else {
options.outputDirectory = options.outputDirectory[0] + outputDirectory;
}
}
let outputDirectory = options.outputDirectory || "";
if (outputDirectory && !outputDirectory.endsWith("/")) {
outputDirectory += "/";
}
let newFilename = outputDirectory + filename;
if (options.filenameConflictAction == "overwrite") {
return filename;
} else if (options.filenameConflictAction == "uniquify" && index > 1) {
const regExpMatchExtension = /(\.[^.]+)$/;
const matchExtension = newFilename.match(regExpMatchExtension);
if (matchExtension && matchExtension[1]) {
newFilename = newFilename.replace(regExpMatchExtension, " (" + index + ")" + matchExtension[1]);
} else {
newFilename += " (" + index + ")";
}
}
if (fs.existsSync(newFilename)) {
if (options.filenameConflictAction != "skip") {
return getFilename(filename, options, index + 1);
}
} else {
return newFilename;
}
}