business.js 8.8 KB

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