business.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 singlefile */
  24. singlefile.extension.core.bg.business = (() => {
  25. const ERROR_CONNECTION_ERROR_CHROMIUM = "Could not establish connection. Receiving end does not exist.";
  26. const ERROR_CONNECTION_LOST_CHROMIUM = "The message port closed before a response was received.";
  27. const ERROR_CONNECTION_LOST_GECKO = "Message manager disconnected";
  28. const INJECT_SCRIPTS_STEP = 1;
  29. const EXECUTE_SCRIPTS_STEP = 2;
  30. const TASK_PENDING_STATE = "pending";
  31. const TASK_PROCESSING_STATE = "processing";
  32. const extensionScriptFiles = [
  33. "common/index.js",
  34. "common/ui/content/content-infobar.js",
  35. "extension/lib/single-file/index.js",
  36. "extension/core/index.js",
  37. "extension/ui/index.js",
  38. "extension/core/content/content-main.js",
  39. "extension/core/content/content-download.js",
  40. "extension/ui/content/content-ui-main.js"
  41. ];
  42. const tasks = [];
  43. let currentTaskId = 0, maxParallelWorkers;
  44. return {
  45. isSavingTab: tab => Boolean(tasks.find(taskInfo => taskInfo.tab.id == tab.id)),
  46. saveTabs,
  47. saveUrls,
  48. saveSelectedLinks,
  49. cancelTab,
  50. cancelTask: taskId => cancelTask(tasks.find(taskInfo => taskInfo.id == taskId)),
  51. cancelAllTasks: () => Array.from(tasks).forEach(cancelTask),
  52. getTasksInfo: () => tasks.map(mapTaskInfo),
  53. getTaskInfo: taskId => tasks.find(taskInfo => taskInfo.id == taskId),
  54. setCancelCallback: (taskId, cancelCallback) => {
  55. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  56. if (taskInfo) {
  57. taskInfo.cancel = cancelCallback;
  58. }
  59. },
  60. openEditor,
  61. onSaveEnd: taskId => {
  62. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  63. if (taskInfo && taskInfo.done) {
  64. taskInfo.done();
  65. }
  66. },
  67. onInit: tab => cancelTab(tab.id),
  68. onTabRemoved: cancelTab
  69. };
  70. async function saveSelectedLinks(tab) {
  71. const tabs = singlefile.extension.core.bg.tabs;
  72. const tabOptions = { extensionScriptFiles, tabId: tab.id, tabIndex: tab.index };
  73. const scriptsInjected = await singlefile.extension.injectScript(tab.id, tabOptions);
  74. if (scriptsInjected) {
  75. const response = await tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
  76. if (response.urls && response.urls.length) {
  77. await saveUrls(response.urls);
  78. }
  79. } else {
  80. singlefile.extension.ui.bg.main.onForbiddenDomain(tab);
  81. }
  82. }
  83. async function saveUrls(urls, options = {}) {
  84. await initMaxParallelWorkers();
  85. await Promise.all(urls.map(async url => {
  86. const tabOptions = await singlefile.extension.core.bg.config.getOptions(url);
  87. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  88. tabOptions.autoClose = true;
  89. tabOptions.extensionScriptFiles = extensionScriptFiles;
  90. tasks.push({ id: currentTaskId, status: TASK_PENDING_STATE, tab: { url }, options: tabOptions, method: "content.save" });
  91. currentTaskId++;
  92. }));
  93. runTasks();
  94. }
  95. async function saveTabs(tabs, options = {}) {
  96. const config = singlefile.extension.core.bg.config;
  97. const autosave = singlefile.extension.core.bg.autosave;
  98. const ui = singlefile.extension.ui.bg.main;
  99. await initMaxParallelWorkers();
  100. await Promise.all(tabs.map(async tab => {
  101. const tabId = tab.id;
  102. const tabOptions = await config.getOptions(tab.url);
  103. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  104. tabOptions.tabId = tabId;
  105. tabOptions.tabIndex = tab.index;
  106. tabOptions.extensionScriptFiles = extensionScriptFiles;
  107. if (options.autoSave) {
  108. if (autosave.isEnabled(tab)) {
  109. const taskInfo = { id: currentTaskId, status: TASK_PROCESSING_STATE, tab, options: tabOptions, method: "content.autosave" };
  110. tasks.push(taskInfo);
  111. runTask(taskInfo);
  112. currentTaskId++;
  113. }
  114. } else {
  115. ui.onStart(tabId, INJECT_SCRIPTS_STEP);
  116. const scriptsInjected = await singlefile.extension.injectScript(tabId, tabOptions);
  117. if (scriptsInjected) {
  118. ui.onStart(tabId, EXECUTE_SCRIPTS_STEP);
  119. tasks.push({ id: currentTaskId, status: TASK_PENDING_STATE, tab, options: tabOptions, method: "content.save" });
  120. currentTaskId++;
  121. } else {
  122. ui.onForbiddenDomain(tab);
  123. }
  124. }
  125. }));
  126. runTasks();
  127. }
  128. function openEditor(tab) {
  129. singlefile.extension.core.bg.tabs.sendMessage(tab.id, { method: "content.openEditor" });
  130. }
  131. async function initMaxParallelWorkers() {
  132. if (!maxParallelWorkers) {
  133. maxParallelWorkers = (await singlefile.extension.core.bg.config.get()).maxParallelWorkers;
  134. }
  135. }
  136. function runTasks() {
  137. const processingCount = tasks.filter(taskInfo => taskInfo.status == TASK_PROCESSING_STATE).length;
  138. for (let index = 0; index < Math.min(tasks.length - processingCount, (maxParallelWorkers - processingCount)); index++) {
  139. const taskInfo = tasks.find(taskInfo => taskInfo.status == TASK_PENDING_STATE);
  140. if (taskInfo) {
  141. runTask(taskInfo);
  142. }
  143. }
  144. }
  145. async function runTask(taskInfo) {
  146. const ui = singlefile.extension.ui.bg.main;
  147. const tabs = singlefile.extension.core.bg.tabs;
  148. const taskId = taskInfo.id;
  149. taskInfo.status = TASK_PROCESSING_STATE;
  150. taskInfo.done = () => {
  151. tasks.splice(tasks.findIndex(taskInfo => taskInfo.id == taskId), 1);
  152. runTasks();
  153. };
  154. if (!taskInfo.tab.id) {
  155. let scriptsInjected;
  156. try {
  157. const tab = await tabs.createAndWait({ url: taskInfo.tab.url, active: false });
  158. taskInfo.tab.id = taskInfo.options.tabId = tab.id;
  159. taskInfo.tab.index = taskInfo.options.tabIndex = tab.index;
  160. ui.onStart(taskInfo.tab.id, INJECT_SCRIPTS_STEP);
  161. scriptsInjected = await singlefile.extension.injectScript(taskInfo.tab.id, taskInfo.options);
  162. } catch (tabId) {
  163. taskInfo.tab.id = tabId;
  164. }
  165. if (scriptsInjected) {
  166. ui.onStart(taskInfo.tab.id, EXECUTE_SCRIPTS_STEP);
  167. } else {
  168. taskInfo.done();
  169. return;
  170. }
  171. }
  172. taskInfo.options.taskId = taskId;
  173. try {
  174. await tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
  175. if (taskInfo.options.autoClose && !taskInfo.cancelled) {
  176. tabs.remove(taskInfo.tab.id);
  177. }
  178. } catch (error) {
  179. if (error && (!error.message || !isIgnoredError(error))) {
  180. console.log(error); // eslint-disable-line no-console
  181. ui.onError(taskInfo.tab.id);
  182. taskInfo.done();
  183. }
  184. }
  185. }
  186. function isIgnoredError(error) {
  187. return error.message == ERROR_CONNECTION_LOST_CHROMIUM ||
  188. error.message == ERROR_CONNECTION_ERROR_CHROMIUM ||
  189. error.message == ERROR_CONNECTION_LOST_GECKO;
  190. }
  191. function cancelTab(tabId) {
  192. Array.from(tasks).filter(taskInfo => taskInfo.tab.id == tabId && !taskInfo.options.autoSave).forEach(cancelTask);
  193. }
  194. function cancelTask(taskInfo) {
  195. const tabId = taskInfo.tab.id;
  196. const taskId = taskInfo.id;
  197. taskInfo.cancelled = true;
  198. singlefile.extension.core.bg.tabs.sendMessage(tabId, { method: "content.cancelSave", resetZoomLevel: taskInfo.options.loadDeferredImagesKeepZoomLevel });
  199. if (taskInfo.cancel) {
  200. taskInfo.cancel();
  201. }
  202. if (taskInfo.method == "content.autosave") {
  203. singlefile.extension.ui.bg.main.onEnd(tabId, true);
  204. }
  205. singlefile.extension.ui.bg.main.onCancelled(taskInfo.tab);
  206. tasks.splice(tasks.findIndex(taskInfo => taskInfo.id == taskId), 1);
  207. if (taskInfo.done) {
  208. taskInfo.done();
  209. }
  210. }
  211. function mapTaskInfo(taskInfo) {
  212. 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 };
  213. }
  214. })();