business.js 9.0 KB

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