business.js 7.8 KB

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