| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- #!/usr/bin/env node
- /*
- * 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, URL */
- const fileUrl = require("file-url");
- const fs = require("fs");
- const options = require("./args");
- 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"
- };
- options.compressCSS = options.compressCss;
- options.compressHTML = options.compressHtml;
- options.includeBOM = options.includeBom;
- if (options.url && !/^(https?|file):\/\//.test(options.url)) {
- options.url = fileUrl(options.url);
- }
- options.retrieveLinks = true;
- options.browserScripts = options.browserScripts.map(path => require.resolve(path));
- const backend = require(backEnds[options.backEnd]);
- run(options);
- async function run(options) {
- await backend.initialize(options);
- let tasks;
- if (options.urlsFile) {
- tasks = fs.readFileSync(options.urlsFile).toString().split("\n")
- .map(url => ({ url: rewriteURL(url, options.urlRewriteRules), depth: 0 }))
- .filter(task => task.url);
- } else {
- tasks = [{ url: rewriteURL(options.url, options.urlRewriteRules), depth: 0 }];
- }
- await runTasks(tasks, options);
- if (!options.browserDebug) {
- return backend.closeBrowser();
- }
- }
- async function runTasks(tasks, options) {
- const availableTasks = tasks.filter(task => !task.status).length;
- const processingTasks = tasks.filter(task => task.status == "processing").length;
- const promisesTasks = [];
- for (let workerIndex = 0; workerIndex < Math.min(availableTasks, options.maxParallelWorkers - processingTasks); workerIndex++) {
- promisesTasks.push(runNextTask(tasks, options));
- }
- await Promise.all(promisesTasks);
- }
- async function runNextTask(tasks, options) {
- const task = tasks.find(task => !task.status);
- if (task) {
- options = JSON.parse(JSON.stringify(options));
- options.url = task.url;
- options.output = null;
- task.status = "processing";
- const pageData = await capturePage(options);
- task.status = "processed";
- if (pageData && options.crawlLinks) {
- pageData.links = pageData.links
- .map(urlLink => rewriteURL(urlLink, options.urlRewriteRules))
- .filter(urlLink => !tasks.find(task => task.url == urlLink));
- if (options.crawlInnerLinksOnly) {
- const urlHost = getHostURL(options.url);
- pageData.links = pageData.links.filter(urlLink => urlLink.startsWith(urlHost));
- }
- if (task.depth < options.crawlMaxDepth) {
- tasks.splice(tasks.length, 0, ...pageData.links.map(url => ({ url, depth: task.depth + 1 })));
- }
- }
- await runTasks(tasks, options);
- }
- }
- function rewriteURL(url, rewriteRules) {
- url = url.trim();
- rewriteRules.forEach(rewriteRule => {
- const parts = rewriteRule.split(/ +/);
- if (parts.length == 2) {
- 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 {
- const pageData = await backend.getPageData(options);
- if (options.output) {
- fs.writeFileSync(getFilename(options.output), pageData.content);
- } else {
- if (options.filenameTemplate && pageData.filename) {
- fs.writeFileSync(getFilename(pageData.filename), pageData.content);
- } else {
- console.log(pageData.content); // eslint-disable-line no-console
- }
- }
- 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(message); // eslint-disable-line no-console
- }
- }
- }
- function getFilename(filename, index = 1) {
- let newFilename = filename;
- if (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)) {
- return getFilename(filename, index + 1);
- } else {
- return newFilename;
- }
- }
|