business.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. /* global browser */
  24. import * as config from "./config.js";
  25. import { autoSaveIsEnabled } from "./autosave-util.js";
  26. import * as editor from "./editor.js";
  27. import * as requests from "./requests.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. ui.setBusiness({ isSavingTab, saveTabs, saveUrls, cancelTab, openEditor, saveSelectedLinks });
  45. export {
  46. isSavingTab,
  47. saveTabs,
  48. saveUrls,
  49. saveSelectedLinks,
  50. cancelTab,
  51. cancelTask,
  52. cancelAllTasks,
  53. getTasksInfo,
  54. getTaskInfo,
  55. setCancelCallback,
  56. openEditor,
  57. onSaveEnd,
  58. onInit,
  59. cancelTab as onTabRemoved
  60. };
  61. async function saveSelectedLinks(tab) {
  62. const tabOptions = { extensionScriptFiles, tabId: tab.id, tabIndex: tab.index };
  63. const scriptsInjected = await injectScript(tab.id, tabOptions);
  64. if (scriptsInjected) {
  65. const response = await browser.tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
  66. if (response.urls && response.urls.length) {
  67. await saveUrls(response.urls);
  68. }
  69. } else {
  70. ui.onForbiddenDomain(tab);
  71. }
  72. }
  73. async function saveUrls(urls, options = {}) {
  74. await initMaxParallelWorkers();
  75. await Promise.all(urls.map(async url => {
  76. const tabOptions = await config.getOptions(url);
  77. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  78. tabOptions.autoClose = true;
  79. tabOptions.extensionScriptFiles = extensionScriptFiles;
  80. if (tabOptions.passReferrerOnError) {
  81. await requests.enableReferrerOnError();
  82. }
  83. addTask({
  84. tab: { url },
  85. status: TASK_PENDING_STATE,
  86. options: tabOptions,
  87. method: "content.save"
  88. });
  89. }));
  90. runTasks();
  91. }
  92. async function saveTabs(tabs, options = {}) {
  93. await initMaxParallelWorkers();
  94. await Promise.all(tabs.map(async tab => {
  95. const tabId = tab.id;
  96. const tabOptions = await config.getOptions(tab.url);
  97. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  98. tabOptions.tabId = tabId;
  99. tabOptions.tabIndex = tab.index;
  100. tabOptions.extensionScriptFiles = extensionScriptFiles;
  101. if (tabOptions.passReferrerOnError) {
  102. await requests.enableReferrerOnError();
  103. }
  104. if (options.autoSave) {
  105. if (autoSaveIsEnabled(tab)) {
  106. const taskInfo = addTask({
  107. status: TASK_PROCESSING_STATE,
  108. tab,
  109. options: tabOptions,
  110. method: "content.autosave"
  111. });
  112. runTask(taskInfo);
  113. }
  114. } else {
  115. ui.onStart(tabId, INJECT_SCRIPTS_STEP);
  116. const scriptsInjected = await injectScript(tabId, tabOptions);
  117. if (scriptsInjected || editor.isEditor(tab)) {
  118. ui.onStart(tabId, EXECUTE_SCRIPTS_STEP);
  119. addTask({
  120. status: TASK_PENDING_STATE,
  121. tab,
  122. options: tabOptions,
  123. method: "content.save"
  124. });
  125. } else {
  126. ui.onForbiddenDomain(tab);
  127. }
  128. }
  129. }));
  130. runTasks();
  131. }
  132. function addTask(info) {
  133. const taskInfo = {
  134. id: currentTaskId,
  135. status: info.status,
  136. tab: info.tab,
  137. options: info.options,
  138. method: info.method,
  139. done: function () {
  140. tasks.splice(tasks.findIndex(taskInfo => taskInfo.id == this.id), 1);
  141. runTasks();
  142. }
  143. };
  144. tasks.push(taskInfo);
  145. currentTaskId++;
  146. return taskInfo;
  147. }
  148. function openEditor(tab) {
  149. browser.tabs.sendMessage(tab.id, { method: "content.openEditor" });
  150. }
  151. async function initMaxParallelWorkers() {
  152. if (!maxParallelWorkers) {
  153. maxParallelWorkers = (await config.get()).maxParallelWorkers;
  154. }
  155. }
  156. function runTasks() {
  157. const processingCount = tasks.filter(taskInfo => taskInfo.status == TASK_PROCESSING_STATE).length;
  158. for (let index = 0; index < Math.min(tasks.length - processingCount, (maxParallelWorkers - processingCount)); index++) {
  159. const taskInfo = tasks.find(taskInfo => taskInfo.status == TASK_PENDING_STATE);
  160. if (taskInfo) {
  161. runTask(taskInfo);
  162. }
  163. }
  164. }
  165. async function runTask(taskInfo) {
  166. const taskId = taskInfo.id;
  167. taskInfo.status = TASK_PROCESSING_STATE;
  168. if (!taskInfo.tab.id) {
  169. let scriptsInjected;
  170. try {
  171. const tab = await createTabAndWaitUntilComplete({ url: taskInfo.tab.url, active: false });
  172. taskInfo.tab.id = taskInfo.options.tabId = tab.id;
  173. taskInfo.tab.index = taskInfo.options.tabIndex = tab.index;
  174. ui.onStart(taskInfo.tab.id, INJECT_SCRIPTS_STEP);
  175. scriptsInjected = await injectScript(taskInfo.tab.id, taskInfo.options);
  176. } catch (tabId) {
  177. taskInfo.tab.id = tabId;
  178. }
  179. if (scriptsInjected) {
  180. ui.onStart(taskInfo.tab.id, EXECUTE_SCRIPTS_STEP);
  181. } else {
  182. taskInfo.done();
  183. return;
  184. }
  185. }
  186. taskInfo.options.taskId = taskId;
  187. try {
  188. await browser.tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
  189. } catch (error) {
  190. if (error && (!error.message || !isIgnoredError(error))) {
  191. console.log(error.message ? error.message : error); // eslint-disable-line no-console
  192. ui.onError(taskInfo.tab.id, error.message, error.link);
  193. taskInfo.done();
  194. }
  195. }
  196. }
  197. function isIgnoredError(error) {
  198. return error.message == ERROR_CONNECTION_LOST_CHROMIUM ||
  199. error.message == ERROR_CONNECTION_ERROR_CHROMIUM ||
  200. error.message == ERROR_CONNECTION_LOST_GECKO ||
  201. error.message.startsWith(ERROR_EDITOR_PAGE_CHROMIUM + JSON.stringify(editor.EDITOR_URL));
  202. }
  203. function isSavingTab(tab) {
  204. return Boolean(tasks.find(taskInfo => taskInfo.tab.id == tab.id));
  205. }
  206. function onInit(tab) {
  207. cancelTab(tab.id);
  208. }
  209. function onSaveEnd(taskId) {
  210. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  211. if (taskInfo) {
  212. if (taskInfo.options.autoClose && !taskInfo.cancelled) {
  213. browser.tabs.remove(taskInfo.tab.id);
  214. }
  215. taskInfo.done();
  216. }
  217. }
  218. async function createTabAndWaitUntilComplete(createProperties) {
  219. const tab = await browser.tabs.create(createProperties);
  220. return new Promise((resolve, reject) => {
  221. browser.tabs.onUpdated.addListener(onTabUpdated);
  222. browser.tabs.onRemoved.addListener(onTabRemoved);
  223. function onTabUpdated(tabId, changeInfo) {
  224. if (tabId == tab.id && changeInfo.status == "complete") {
  225. resolve(tab);
  226. browser.tabs.onUpdated.removeListener(onTabUpdated);
  227. browser.tabs.onRemoved.removeListener(onTabRemoved);
  228. }
  229. }
  230. function onTabRemoved(tabId) {
  231. if (tabId == tab.id) {
  232. reject(tabId);
  233. browser.tabs.onRemoved.removeListener(onTabRemoved);
  234. }
  235. }
  236. });
  237. }
  238. function setCancelCallback(taskId, cancelCallback) {
  239. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  240. if (taskInfo) {
  241. taskInfo.cancel = cancelCallback;
  242. }
  243. }
  244. function cancelTab(tabId) {
  245. Array.from(tasks).filter(taskInfo => taskInfo.tab.id == tabId && !taskInfo.options.autoSave).forEach(cancel);
  246. }
  247. function cancelTask(taskId) {
  248. cancel(tasks.find(taskInfo => taskInfo.id == taskId));
  249. }
  250. function cancelAllTasks() {
  251. Array.from(tasks).forEach(cancel);
  252. }
  253. function getTasksInfo() {
  254. return tasks.map(mapTaskInfo);
  255. }
  256. function getTaskInfo(taskId) {
  257. return tasks.find(taskInfo => taskInfo.id == taskId);
  258. }
  259. function cancel(taskInfo) {
  260. const tabId = taskInfo.tab.id;
  261. taskInfo.cancelled = true;
  262. browser.tabs.sendMessage(tabId, {
  263. method: "content.cancelSave",
  264. options: {
  265. loadDeferredImages: taskInfo.options.loadDeferredImages,
  266. loadDeferredImagesKeepZoomLevel: taskInfo.options.loadDeferredImagesKeepZoomLevel
  267. }
  268. });
  269. if (taskInfo.cancel) {
  270. taskInfo.cancel();
  271. }
  272. if (taskInfo.method == "content.autosave") {
  273. ui.onEnd(tabId, true);
  274. }
  275. ui.onCancelled(taskInfo.tab);
  276. taskInfo.done();
  277. }
  278. function mapTaskInfo(taskInfo) {
  279. 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 };
  280. }