business.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. import * as config from "./config.js";
  24. import * as autosave from "./autosave.js";
  25. import * as editor from "./editor.js";
  26. import * as requests from "./requests.js";
  27. import * as tabs from "./tabs.js";
  28. import * as ui from "./../../ui/bg/index.js";
  29. import { injectScript } from "./../../index.js";
  30. const ERROR_CONNECTION_ERROR_CHROMIUM = "Could not establish connection. Receiving end does not exist.";
  31. const ERROR_CONNECTION_LOST_CHROMIUM = "The message port closed before a response was received.";
  32. const ERROR_CONNECTION_LOST_GECKO = "Message manager disconnected";
  33. const ERROR_EDITOR_PAGE_CHROMIUM = "Cannot access contents of url ";
  34. const INJECT_SCRIPTS_STEP = 1;
  35. const EXECUTE_SCRIPTS_STEP = 2;
  36. const TASK_PENDING_STATE = "pending";
  37. const TASK_PROCESSING_STATE = "processing";
  38. const extensionScriptFiles = [
  39. "dist/infobar.js",
  40. "dist/extension.js"
  41. ];
  42. const tasks = [];
  43. let currentTaskId = 0, maxParallelWorkers;
  44. export {
  45. isSavingTab,
  46. saveTabs,
  47. saveUrls,
  48. saveSelectedLinks,
  49. cancelTab,
  50. cancelTask,
  51. cancelAllTasks,
  52. getTasksInfo,
  53. getTaskInfo,
  54. setCancelCallback,
  55. openEditor,
  56. onSaveEnd,
  57. onInit,
  58. cancelTab as onTabRemoved
  59. };
  60. async function saveSelectedLinks(tab) {
  61. const tabOptions = { extensionScriptFiles, tabId: tab.id, tabIndex: tab.index };
  62. const scriptsInjected = await injectScript(tab.id, tabOptions);
  63. if (scriptsInjected) {
  64. const response = await tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
  65. if (response.urls && response.urls.length) {
  66. await saveUrls(response.urls);
  67. }
  68. } else {
  69. ui.onForbiddenDomain(tab);
  70. }
  71. }
  72. async function saveUrls(urls, options = {}) {
  73. await initMaxParallelWorkers();
  74. await Promise.all(urls.map(async url => {
  75. const tabOptions = await config.getOptions(url);
  76. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  77. tabOptions.autoClose = true;
  78. tabOptions.extensionScriptFiles = extensionScriptFiles;
  79. if (tabOptions.passReferrerOnError) {
  80. await requests.enableReferrerOnError();
  81. }
  82. addTask({
  83. tab: { url },
  84. status: TASK_PENDING_STATE,
  85. options: tabOptions,
  86. method: "content.save"
  87. });
  88. }));
  89. runTasks();
  90. }
  91. async function saveTabs(tabs, options = {}) {
  92. await initMaxParallelWorkers();
  93. await Promise.all(tabs.map(async tab => {
  94. const tabId = tab.id;
  95. const tabOptions = await config.getOptions(tab.url);
  96. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  97. tabOptions.tabId = tabId;
  98. tabOptions.tabIndex = tab.index;
  99. tabOptions.extensionScriptFiles = extensionScriptFiles;
  100. if (tabOptions.passReferrerOnError) {
  101. await requests.enableReferrerOnError();
  102. }
  103. if (options.autoSave) {
  104. if (autosave.isEnabled(tab)) {
  105. const taskInfo = addTask({
  106. status: TASK_PROCESSING_STATE,
  107. tab,
  108. options: tabOptions,
  109. method: "content.autosave"
  110. });
  111. runTask(taskInfo);
  112. }
  113. } else {
  114. ui.onStart(tabId, INJECT_SCRIPTS_STEP);
  115. const scriptsInjected = await injectScript(tabId, tabOptions);
  116. if (scriptsInjected || editor.isEditor(tab)) {
  117. ui.onStart(tabId, EXECUTE_SCRIPTS_STEP);
  118. addTask({
  119. status: TASK_PENDING_STATE,
  120. tab,
  121. options: tabOptions,
  122. method: "content.save"
  123. });
  124. } else {
  125. ui.onForbiddenDomain(tab);
  126. }
  127. }
  128. }));
  129. runTasks();
  130. }
  131. function addTask(info) {
  132. const taskInfo = {
  133. id: currentTaskId,
  134. status: info.status,
  135. tab: info.tab,
  136. options: info.options,
  137. method: info.method,
  138. done: function () {
  139. tasks.splice(tasks.findIndex(taskInfo => taskInfo.id == this.id), 1);
  140. runTasks();
  141. }
  142. };
  143. tasks.push(taskInfo);
  144. currentTaskId++;
  145. return taskInfo;
  146. }
  147. function openEditor(tab) {
  148. tabs.sendMessage(tab.id, { method: "content.openEditor" });
  149. }
  150. async function initMaxParallelWorkers() {
  151. if (!maxParallelWorkers) {
  152. maxParallelWorkers = (await config.get()).maxParallelWorkers;
  153. }
  154. }
  155. function runTasks() {
  156. const processingCount = tasks.filter(taskInfo => taskInfo.status == TASK_PROCESSING_STATE).length;
  157. for (let index = 0; index < Math.min(tasks.length - processingCount, (maxParallelWorkers - processingCount)); index++) {
  158. const taskInfo = tasks.find(taskInfo => taskInfo.status == TASK_PENDING_STATE);
  159. if (taskInfo) {
  160. runTask(taskInfo);
  161. }
  162. }
  163. }
  164. async function runTask(taskInfo) {
  165. const taskId = taskInfo.id;
  166. taskInfo.status = TASK_PROCESSING_STATE;
  167. if (!taskInfo.tab.id) {
  168. let scriptsInjected;
  169. try {
  170. const tab = await tabs.createAndWait({ url: taskInfo.tab.url, active: false });
  171. taskInfo.tab.id = taskInfo.options.tabId = tab.id;
  172. taskInfo.tab.index = taskInfo.options.tabIndex = tab.index;
  173. ui.onStart(taskInfo.tab.id, INJECT_SCRIPTS_STEP);
  174. scriptsInjected = await injectScript(taskInfo.tab.id, taskInfo.options);
  175. } catch (tabId) {
  176. taskInfo.tab.id = tabId;
  177. }
  178. if (scriptsInjected) {
  179. ui.onStart(taskInfo.tab.id, EXECUTE_SCRIPTS_STEP);
  180. } else {
  181. taskInfo.done();
  182. return;
  183. }
  184. }
  185. taskInfo.options.taskId = taskId;
  186. try {
  187. await tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
  188. } catch (error) {
  189. if (error && (!error.message || !isIgnoredError(error))) {
  190. console.log(error.message ? error.message : error); // eslint-disable-line no-console
  191. ui.onError(taskInfo.tab.id);
  192. taskInfo.done();
  193. }
  194. }
  195. }
  196. function isIgnoredError(error) {
  197. return error.message == ERROR_CONNECTION_LOST_CHROMIUM ||
  198. error.message == ERROR_CONNECTION_ERROR_CHROMIUM ||
  199. error.message == ERROR_CONNECTION_LOST_GECKO ||
  200. error.message.startsWith(ERROR_EDITOR_PAGE_CHROMIUM + JSON.stringify(editor.EDITOR_URL));
  201. }
  202. function isSavingTab(tab) {
  203. return Boolean(tasks.find(taskInfo => taskInfo.tab.id == tab.id));
  204. }
  205. function onInit(tab) {
  206. cancelTab(tab.id);
  207. }
  208. function onSaveEnd(taskId) {
  209. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  210. if (taskInfo) {
  211. if (taskInfo.options.autoClose && !taskInfo.cancelled) {
  212. tabs.remove(taskInfo.tab.id);
  213. }
  214. taskInfo.done();
  215. }
  216. }
  217. function setCancelCallback(taskId, cancelCallback) {
  218. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  219. if (taskInfo) {
  220. taskInfo.cancel = cancelCallback;
  221. }
  222. }
  223. function cancelTab(tabId) {
  224. Array.from(tasks).filter(taskInfo => taskInfo.tab.id == tabId && !taskInfo.options.autoSave).forEach(cancel);
  225. }
  226. function cancelTask(taskId) {
  227. cancel(tasks.find(taskInfo => taskInfo.id == taskId));
  228. }
  229. function cancelAllTasks() {
  230. Array.from(tasks).forEach(cancel);
  231. }
  232. function getTasksInfo() {
  233. return tasks.map(mapTaskInfo);
  234. }
  235. function getTaskInfo(taskId) {
  236. return tasks.find(taskInfo => taskInfo.id == taskId);
  237. }
  238. function cancel(taskInfo) {
  239. const tabId = taskInfo.tab.id;
  240. taskInfo.cancelled = true;
  241. tabs.sendMessage(tabId, {
  242. method: "content.cancelSave",
  243. options: {
  244. loadDeferredImages: taskInfo.options.loadDeferredImages,
  245. loadDeferredImagesKeepZoomLevel: taskInfo.options.loadDeferredImagesKeepZoomLevel
  246. }
  247. });
  248. if (taskInfo.cancel) {
  249. taskInfo.cancel();
  250. }
  251. if (taskInfo.method == "content.autosave") {
  252. ui.onEnd(tabId, true);
  253. }
  254. ui.onCancelled(taskInfo.tab);
  255. taskInfo.done();
  256. }
  257. function mapTaskInfo(taskInfo) {
  258. return { id: taskInfo.id, tabId: taskInfo.tab.id, index: taskInfo.tab.index, url: taskInfo.tab.url, title: taskInfo.tab.title, cancelled: taskInfo.cancelled, status: taskInfo.status };
  259. }