business.js 8.2 KB

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