business.js 8.8 KB

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