business.js 8.0 KB

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