business.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 browser */
  24. import * as config from "./config.js";
  25. import { autoSaveIsEnabled } from "./autosave-util.js";
  26. import * as editor from "./editor.js";
  27. import * as requests from "./requests.js";
  28. import * as ui from "./../../ui/bg/index.js";
  29. import { injectScript } from "./../../index.js";
  30. const ERROR_CONNECTION_ERROR_CHROMIUM = "Could not establish connection. Receiving end does not exist.";
  31. const ERROR_CONNECTION_LOST_CHROMIUM = "The message port closed before a response was received.";
  32. const ERROR_CONNECTION_LOST_GECKO = "Message manager disconnected";
  33. const ERROR_EDITOR_PAGE_CHROMIUM = "Cannot access contents of url ";
  34. const INJECT_SCRIPTS_STEP = 1;
  35. const EXECUTE_SCRIPTS_STEP = 2;
  36. const TASK_PENDING_STATE = "pending";
  37. const TASK_PROCESSING_STATE = "processing";
  38. const extensionScriptFiles = [
  39. "lib/single-file-extension.js"
  40. ];
  41. const tasks = [];
  42. let currentTaskId = 0, maxParallelWorkers, processInForeground;
  43. ui.init({ isSavingTab, saveTabs, saveUrls, cancelTab, openEditor, saveSelectedLinks, batchSaveUrls });
  44. export {
  45. saveTabs,
  46. saveUrls,
  47. saveSelectedLinks,
  48. cancelTask,
  49. cancelAllTasks,
  50. getTasksInfo,
  51. getTaskInfo,
  52. setCancelCallback,
  53. onSaveEnd,
  54. onInit,
  55. onTabReplaced,
  56. cancelTab as onTabRemoved
  57. };
  58. async function saveSelectedLinks(tab) {
  59. const tabOptions = { extensionScriptFiles, tabId: tab.id, tabIndex: tab.index };
  60. const scriptsInjected = await injectScript(tab.id, tabOptions);
  61. if (scriptsInjected) {
  62. const response = await browser.tabs.sendMessage(tab.id, { method: "content.getSelectedLinks" });
  63. if (response.urls && response.urls.length) {
  64. const tab = await batchSaveUrls();
  65. const onTabUpdated = (tabId, changeInfo) => {
  66. if (changeInfo.status == "complete" && tabId == tab.id) {
  67. browser.tabs.onUpdated.removeListener(onTabUpdated);
  68. browser.tabs.sendMessage(tab.id, { method: "newUrls.addURLs", urls: response.urls });
  69. }
  70. };
  71. browser.tabs.onUpdated.addListener(onTabUpdated);
  72. }
  73. } else {
  74. ui.onForbiddenDomain(tab);
  75. }
  76. }
  77. async function batchSaveUrls() {
  78. return browser.tabs.create({ active: true, url: "/src/ui/pages/batch-save-urls.html" });
  79. }
  80. async function saveUrls(urls, options = {}) {
  81. await initMaxParallelWorkers();
  82. await Promise.all(urls.map(async url => {
  83. const tabOptions = await config.getOptions(url);
  84. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  85. tabOptions.autoClose = true;
  86. tabOptions.extensionScriptFiles = extensionScriptFiles;
  87. if (tabOptions.passReferrerOnError) {
  88. requests.enableReferrerOnError();
  89. }
  90. addTask({
  91. tab: { url },
  92. status: TASK_PENDING_STATE,
  93. options: tabOptions,
  94. method: "content.save"
  95. });
  96. }));
  97. runTasks();
  98. }
  99. async function saveTabs(tabs, options = {}) {
  100. await initMaxParallelWorkers();
  101. await Promise.all(tabs.map(async tab => {
  102. const tabId = tab.id;
  103. const tabOptions = await config.getOptions(tab.url);
  104. Object.keys(options).forEach(key => tabOptions[key] = options[key]);
  105. tabOptions.tabId = tabId;
  106. tabOptions.tabIndex = tab.index;
  107. tabOptions.extensionScriptFiles = extensionScriptFiles;
  108. if (tabOptions.passReferrerOnError) {
  109. requests.enableReferrerOnError();
  110. }
  111. const tabData = {
  112. id: tab.id,
  113. index: tab.index,
  114. url: tab.url,
  115. title: tab.title
  116. };
  117. if (options.autoSave) {
  118. if (autoSaveIsEnabled(tab)) {
  119. const taskInfo = addTask({
  120. status: TASK_PROCESSING_STATE,
  121. tab: tabData,
  122. options: tabOptions,
  123. method: "content.autosave"
  124. });
  125. runTask(taskInfo);
  126. }
  127. } else {
  128. ui.onStart(tabId, INJECT_SCRIPTS_STEP);
  129. const scriptsInjected = await injectScript(tabId, tabOptions);
  130. if (scriptsInjected || editor.isEditor(tab)) {
  131. ui.onStart(tabId, EXECUTE_SCRIPTS_STEP);
  132. addTask({
  133. status: TASK_PENDING_STATE,
  134. tab: tabData,
  135. options: tabOptions,
  136. method: "content.save"
  137. });
  138. } else {
  139. ui.onForbiddenDomain(tab);
  140. }
  141. }
  142. }));
  143. runTasks();
  144. }
  145. function addTask(info) {
  146. const taskInfo = {
  147. id: currentTaskId,
  148. status: info.status,
  149. tab: info.tab,
  150. options: info.options,
  151. method: info.method,
  152. done: function () {
  153. const index = tasks.findIndex(taskInfo => taskInfo.id == this.id);
  154. if (index > -1) {
  155. tasks.splice(index, 1);
  156. runTasks();
  157. }
  158. }
  159. };
  160. tasks.push(taskInfo);
  161. currentTaskId++;
  162. return taskInfo;
  163. }
  164. function openEditor(tab) {
  165. browser.tabs.sendMessage(tab.id, { method: "content.openEditor" });
  166. }
  167. async function initMaxParallelWorkers() {
  168. if (!maxParallelWorkers) {
  169. const configData = await config.get();
  170. processInForeground = configData.processInForeground;
  171. maxParallelWorkers = processInForeground ? 1 : configData.maxParallelWorkers;
  172. }
  173. }
  174. function runTasks() {
  175. const processingCount = tasks.filter(taskInfo => taskInfo.status == TASK_PROCESSING_STATE).length;
  176. for (let index = 0; index < Math.min(tasks.length - processingCount, (maxParallelWorkers - processingCount)); index++) {
  177. const taskInfo = tasks.find(taskInfo => taskInfo.status == TASK_PENDING_STATE);
  178. if (taskInfo) {
  179. runTask(taskInfo);
  180. }
  181. }
  182. }
  183. async function runTask(taskInfo) {
  184. const taskId = taskInfo.id;
  185. taskInfo.status = TASK_PROCESSING_STATE;
  186. if (!taskInfo.tab.id) {
  187. let scriptsInjected;
  188. try {
  189. const tab = await createTabAndWaitUntilComplete({ url: taskInfo.tab.url, active: false });
  190. taskInfo.tab.id = taskInfo.options.tabId = tab.id;
  191. taskInfo.tab.index = taskInfo.options.tabIndex = tab.index;
  192. ui.onStart(taskInfo.tab.id, INJECT_SCRIPTS_STEP);
  193. scriptsInjected = await injectScript(taskInfo.tab.id, taskInfo.options);
  194. } catch (tabId) {
  195. taskInfo.tab.id = tabId;
  196. }
  197. if (scriptsInjected) {
  198. ui.onStart(taskInfo.tab.id, EXECUTE_SCRIPTS_STEP);
  199. } else {
  200. taskInfo.done();
  201. return;
  202. }
  203. }
  204. taskInfo.options.taskId = taskId;
  205. try {
  206. if (processInForeground) {
  207. await browser.tabs.update(taskInfo.tab.id, { active: true });
  208. }
  209. await browser.tabs.sendMessage(taskInfo.tab.id, { method: taskInfo.method, options: taskInfo.options });
  210. } catch (error) {
  211. if (error && (!error.message || !isIgnoredError(error))) {
  212. console.log(error.message ? error.message : error); // eslint-disable-line no-console
  213. ui.onError(taskInfo.tab.id, error.message, error.link);
  214. taskInfo.done();
  215. }
  216. }
  217. }
  218. function isIgnoredError(error) {
  219. return error.message == ERROR_CONNECTION_LOST_CHROMIUM ||
  220. error.message == ERROR_CONNECTION_ERROR_CHROMIUM ||
  221. error.message == ERROR_CONNECTION_LOST_GECKO ||
  222. error.message.startsWith(ERROR_EDITOR_PAGE_CHROMIUM + JSON.stringify(editor.EDITOR_URL));
  223. }
  224. function isSavingTab(tab) {
  225. return Boolean(tasks.find(taskInfo => taskInfo.tab.id == tab.id));
  226. }
  227. function onInit(tab) {
  228. cancelTab(tab.id);
  229. }
  230. function onTabReplaced(addedTabId, removedTabId) {
  231. tasks.forEach(taskInfo => {
  232. if (taskInfo.tab.id == removedTabId) {
  233. taskInfo.tab.id = addedTabId;
  234. }
  235. });
  236. }
  237. async function onSaveEnd(taskId) {
  238. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  239. console.log(taskId, tasks);
  240. if (taskInfo) {
  241. if (taskInfo.options.autoClose && !taskInfo.cancelled) {
  242. await browser.tabs.remove(taskInfo.tab.id);
  243. }
  244. taskInfo.done();
  245. }
  246. }
  247. async function createTabAndWaitUntilComplete(createProperties) {
  248. const tab = await browser.tabs.create(createProperties);
  249. return new Promise((resolve, reject) => {
  250. browser.tabs.onUpdated.addListener(onTabUpdated);
  251. browser.tabs.onRemoved.addListener(onTabRemoved);
  252. function onTabUpdated(tabId, changeInfo) {
  253. if (tabId == tab.id && changeInfo.status == "complete") {
  254. resolve(tab);
  255. browser.tabs.onUpdated.removeListener(onTabUpdated);
  256. browser.tabs.onRemoved.removeListener(onTabRemoved);
  257. }
  258. }
  259. function onTabRemoved(tabId) {
  260. if (tabId == tab.id) {
  261. reject(tabId);
  262. browser.tabs.onRemoved.removeListener(onTabRemoved);
  263. }
  264. }
  265. });
  266. }
  267. function setCancelCallback(taskId, cancelCallback) {
  268. const taskInfo = tasks.find(taskInfo => taskInfo.id == taskId);
  269. if (taskInfo) {
  270. taskInfo.cancel = cancelCallback;
  271. }
  272. }
  273. function cancelTab(tabId) {
  274. Array.from(tasks).filter(taskInfo => taskInfo.tab.id == tabId && !taskInfo.options.autoSave).forEach(cancel);
  275. }
  276. function cancelTask(taskId) {
  277. cancel(tasks.find(taskInfo => taskInfo.id == taskId));
  278. }
  279. function cancelAllTasks() {
  280. Array.from(tasks).forEach(cancel);
  281. }
  282. function getTasksInfo() {
  283. return tasks.map(mapTaskInfo);
  284. }
  285. function getTaskInfo(taskId) {
  286. return tasks.find(taskInfo => taskInfo.id == taskId);
  287. }
  288. function cancel(taskInfo) {
  289. const tabId = taskInfo.tab.id;
  290. taskInfo.cancelled = true;
  291. browser.tabs.sendMessage(tabId, {
  292. method: "content.cancelSave",
  293. options: {
  294. loadDeferredImages: taskInfo.options.loadDeferredImages,
  295. loadDeferredImagesKeepZoomLevel: taskInfo.options.loadDeferredImagesKeepZoomLevel
  296. }
  297. });
  298. if (taskInfo.cancel) {
  299. taskInfo.cancel();
  300. }
  301. if (taskInfo.method == "content.autosave") {
  302. ui.onEnd(tabId, true);
  303. }
  304. ui.onCancelled(taskInfo.tab);
  305. taskInfo.done();
  306. }
  307. function mapTaskInfo(taskInfo) {
  308. 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 };
  309. }