config.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright 2010-2019 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, singlefile, navigator, URL, Blob */
  24. singlefile.extension.core.bg.config = (() => {
  25. const CURRENT_PROFILE_NAME = "-";
  26. const DEFAULT_PROFILE_NAME = "__Default_Settings__";
  27. const DISABLED_PROFILE_NAME = "__Disabled_Settings__";
  28. const REGEXP_RULE_PREFIX = "regexp:";
  29. const DEFAULT_CONFIG = {
  30. removeHiddenElements: true,
  31. removeUnusedStyles: true,
  32. removeUnusedFonts: true,
  33. removeFrames: false,
  34. removeImports: true,
  35. removeScripts: true,
  36. compressHTML: true,
  37. compressCSS: true,
  38. loadDeferredImages: true,
  39. loadDeferredImagesMaxIdleTime: 1500,
  40. loadDeferredImagesBlockCookies: true,
  41. loadDeferredImagesBlockStorage: false,
  42. filenameTemplate: "{page-title} ({date-iso} {time-locale}).html",
  43. infobarTemplate: "",
  44. includeInfobar: false,
  45. confirmInfobarContent: false,
  46. autoClose: false,
  47. confirmFilename: false,
  48. filenameConflictAction: "uniquify",
  49. filenameMaxLength: 192,
  50. filenameReplacementCharacter: "_",
  51. contextMenuEnabled: true,
  52. tabMenuEnabled: true,
  53. browserActionMenuEnabled: true,
  54. shadowEnabled: true,
  55. logsEnabled: true,
  56. progressBarEnabled: true,
  57. maxResourceSizeEnabled: false,
  58. maxResourceSize: 10,
  59. removeAudioSrc: true,
  60. removeVideoSrc: true,
  61. displayInfobar: true,
  62. displayStats: false,
  63. backgroundSave: true,
  64. autoSaveDelay: 1,
  65. autoSaveLoad: false,
  66. autoSaveUnload: false,
  67. autoSaveLoadOrUnload: true,
  68. autoSaveRepeat: false,
  69. autoSaveRepeatDelay: 10,
  70. removeAlternativeFonts: true,
  71. removeAlternativeMedias: true,
  72. removeAlternativeImages: true,
  73. groupDuplicateImages: true,
  74. saveRawPage: false,
  75. saveToClipboard: false,
  76. resolveFragmentIdentifierURLs: false
  77. };
  78. let pendingUpgradePromise = upgrade();
  79. return {
  80. DEFAULT_PROFILE_NAME,
  81. DISABLED_PROFILE_NAME,
  82. CURRENT_PROFILE_NAME,
  83. get: getConfig,
  84. getRule,
  85. getOptions,
  86. getProfiles,
  87. onMessage,
  88. updateRule,
  89. addRule
  90. };
  91. async function upgrade() {
  92. const config = await browser.storage.local.get();
  93. if (!config.profiles) {
  94. const defaultConfig = config;
  95. delete defaultConfig.tabsData;
  96. applyUpgrade(defaultConfig);
  97. const newConfig = { profiles: {}, rules: [] };
  98. newConfig.profiles[DEFAULT_PROFILE_NAME] = defaultConfig;
  99. browser.storage.local.remove(Object.keys(DEFAULT_CONFIG));
  100. await browser.storage.local.set(newConfig);
  101. } else {
  102. if (!config.rules) {
  103. config.rules = [];
  104. }
  105. Object.keys(config.profiles).forEach(profileName => applyUpgrade(config.profiles[profileName]));
  106. await browser.storage.local.remove(["profiles", "defaultProfile", "rules"]);
  107. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  108. }
  109. if (!config.maxParallelWorkers) {
  110. await browser.storage.local.set({ maxParallelWorkers: navigator.hardwareConcurrency || 4 });
  111. }
  112. }
  113. function applyUpgrade(config) {
  114. Object.keys(DEFAULT_CONFIG).forEach(configKey => upgradeConfig(config, configKey));
  115. }
  116. function upgradeOldConfig(config, newKey, oldKey) { // eslint-disable-line no-unused-vars
  117. if (config[newKey] === undefined && config[oldKey] !== undefined) {
  118. config[newKey] = config[oldKey];
  119. delete config[oldKey];
  120. }
  121. }
  122. function upgradeConfig(config, key) {
  123. if (config[key] === undefined) {
  124. config[key] = DEFAULT_CONFIG[key];
  125. }
  126. }
  127. async function getRule(url, ignoreWildcard) {
  128. const config = await getConfig();
  129. const regExpRules = config.rules.filter(rule => testRegExpRule(rule));
  130. let rule = regExpRules.sort(sortRules).find(rule => url && url.match(new RegExp(rule.url.split(REGEXP_RULE_PREFIX)[1])));
  131. if (!rule) {
  132. const normalRules = config.rules.filter(rule => !testRegExpRule(rule));
  133. rule = normalRules.sort(sortRules).find(rule => (!ignoreWildcard && rule.url == "*") || (url && url.includes(rule.url)));
  134. }
  135. return rule;
  136. }
  137. async function getConfig() {
  138. await pendingUpgradePromise;
  139. return browser.storage.local.get(["profiles", "rules", "maxParallelWorkers"]);
  140. }
  141. function sortRules(ruleLeft, ruleRight) {
  142. return ruleRight.url.length - ruleLeft.url.length;
  143. }
  144. function testRegExpRule(rule) {
  145. return rule.url.toLowerCase().startsWith(REGEXP_RULE_PREFIX);
  146. }
  147. async function onMessage(message) {
  148. if (message.method.endsWith(".deleteRules")) {
  149. await deleteRules(message.profileName);
  150. }
  151. if (message.method.endsWith(".deleteRule")) {
  152. await deleteRule(message.url);
  153. }
  154. if (message.method.endsWith(".addRule")) {
  155. await addRule(message.url, message.profileName, message.autoSaveProfileName);
  156. }
  157. if (message.method.endsWith(".createProfile")) {
  158. await createProfile(message.profileName, message.fromProfileName || DEFAULT_PROFILE_NAME);
  159. }
  160. if (message.method.endsWith(".renameProfile")) {
  161. await renameProfile(message.profileName, message.newProfileName);
  162. }
  163. if (message.method.endsWith(".deleteProfile")) {
  164. await deleteProfile(message.profileName);
  165. }
  166. if (message.method.endsWith(".resetProfiles")) {
  167. await resetProfiles();
  168. }
  169. if (message.method.endsWith(".resetProfile")) {
  170. await resetProfile(message.profileName);
  171. }
  172. if (message.method.endsWith(".importConfig")) {
  173. await importConfig(message.config);
  174. }
  175. if (message.method.endsWith(".updateProfile")) {
  176. await updateProfile(message.profileName, message.profile);
  177. }
  178. if (message.method.endsWith(".updateRule")) {
  179. await updateRule(message.url, message.newUrl, message.profileName, message.autoSaveProfileName);
  180. }
  181. if (message.method.endsWith(".getConstants")) {
  182. return {
  183. DISABLED_PROFILE_NAME,
  184. DEFAULT_PROFILE_NAME,
  185. CURRENT_PROFILE_NAME
  186. };
  187. }
  188. if (message.method.endsWith(".getRules")) {
  189. return getRules();
  190. }
  191. if (message.method.endsWith(".getProfiles")) {
  192. return getProfiles();
  193. }
  194. if (message.method.endsWith(".exportConfig")) {
  195. return exportConfig();
  196. }
  197. return {};
  198. }
  199. async function createProfile(profileName, fromProfileName) {
  200. const config = await getConfig();
  201. if (Object.keys(config.profiles).includes(profileName)) {
  202. throw new Error("Duplicate profile name");
  203. }
  204. config.profiles[profileName] = config.profiles[fromProfileName];
  205. await browser.storage.local.set({ profiles: config.profiles });
  206. }
  207. async function getProfiles() {
  208. const config = await getConfig();
  209. return config.profiles;
  210. }
  211. async function getOptions(url, autoSave) {
  212. const [config, rule, tabsData] = await Promise.all([getConfig(), getRule(url), singlefile.extension.core.bg.tabsData.get()]);
  213. const tabProfileName = tabsData.profileName || DEFAULT_PROFILE_NAME;
  214. if (rule) {
  215. const profileName = rule[autoSave ? "autoSaveProfile" : "profile"];
  216. return config.profiles[profileName == CURRENT_PROFILE_NAME ? tabProfileName : profileName];
  217. } else {
  218. return config.profiles[tabProfileName];
  219. }
  220. }
  221. async function updateProfile(profileName, profile) {
  222. const config = await getConfig();
  223. if (!Object.keys(config.profiles).includes(profileName)) {
  224. throw new Error("Profile not found");
  225. }
  226. Object.keys(profile).forEach(key => config.profiles[profileName][key] = profile[key]);
  227. await browser.storage.local.set({ profiles: config.profiles });
  228. }
  229. async function renameProfile(oldProfileName, profileName) {
  230. const [config, tabsData] = await Promise.all([getConfig(), singlefile.extension.core.bg.tabsData.get()]);
  231. if (!Object.keys(config.profiles).includes(oldProfileName)) {
  232. throw new Error("Profile not found");
  233. }
  234. if (Object.keys(config.profiles).includes(profileName)) {
  235. throw new Error("Duplicate profile name");
  236. }
  237. if (oldProfileName == DEFAULT_PROFILE_NAME) {
  238. throw new Error("Default settings cannot be renamed");
  239. }
  240. if (tabsData.profileName == oldProfileName) {
  241. tabsData.profileName = profileName;
  242. await singlefile.extension.core.bg.tabsData.set(tabsData);
  243. }
  244. config.profiles[profileName] = config.profiles[oldProfileName];
  245. config.rules.forEach(rule => {
  246. if (rule.profile == oldProfileName) {
  247. rule.profile = profileName;
  248. }
  249. if (rule.autoSaveProfile == oldProfileName) {
  250. rule.autoSaveProfile = profileName;
  251. }
  252. });
  253. delete config.profiles[oldProfileName];
  254. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  255. }
  256. async function deleteProfile(profileName) {
  257. const [config, tabsData] = await Promise.all([getConfig(), singlefile.extension.core.bg.tabsData.get()]);
  258. if (!Object.keys(config.profiles).includes(profileName)) {
  259. throw new Error("Profile not found");
  260. }
  261. if (profileName == DEFAULT_PROFILE_NAME) {
  262. throw new Error("Default settings cannot be deleted");
  263. }
  264. if (tabsData.profileName == profileName) {
  265. delete tabsData.profileName;
  266. await singlefile.extension.core.bg.tabsData.set(tabsData);
  267. }
  268. config.rules.forEach(rule => {
  269. if (rule.profile == profileName) {
  270. rule.profile = DEFAULT_PROFILE_NAME;
  271. }
  272. if (rule.autoSaveProfile == profileName) {
  273. rule.autoSaveProfile = DEFAULT_PROFILE_NAME;
  274. }
  275. });
  276. delete config.profiles[profileName];
  277. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  278. }
  279. async function getRules() {
  280. const config = await getConfig();
  281. return config.rules;
  282. }
  283. async function addRule(url, profile, autoSaveProfile) {
  284. if (!url) {
  285. throw new Error("URL is empty");
  286. }
  287. const config = await getConfig();
  288. if (config.rules.find(rule => rule.url == url)) {
  289. throw new Error("URL already exists");
  290. }
  291. config.rules.push({
  292. url,
  293. profile,
  294. autoSaveProfile
  295. });
  296. await browser.storage.local.set({ rules: config.rules });
  297. }
  298. async function deleteRule(url) {
  299. if (!url) {
  300. throw new Error("URL is empty");
  301. }
  302. const config = await getConfig();
  303. config.rules = config.rules.filter(rule => rule.url != url);
  304. await browser.storage.local.set({ rules: config.rules });
  305. }
  306. async function deleteRules(profileName) {
  307. const config = await getConfig();
  308. config.rules = config.rules = profileName ? config.rules.filter(rule => rule.autoSaveProfile != profileName && rule.profile != profileName) : [];
  309. await browser.storage.local.set({ rules: config.rules });
  310. }
  311. async function updateRule(url, newURL, profile, autoSaveProfile) {
  312. if (!url || !newURL) {
  313. throw new Error("URL is empty");
  314. }
  315. const config = await getConfig();
  316. const urlConfig = config.rules.find(rule => rule.url == url);
  317. if (!urlConfig) {
  318. throw new Error("URL not found");
  319. }
  320. if (config.rules.find(rule => rule.url == newURL && rule.url != url)) {
  321. throw new Error("New URL already exists");
  322. }
  323. urlConfig.url = newURL;
  324. urlConfig.profile = profile;
  325. urlConfig.autoSaveProfile = autoSaveProfile;
  326. await browser.storage.local.set({ rules: config.rules });
  327. }
  328. async function resetProfiles() {
  329. await pendingUpgradePromise;
  330. const tabsData = await singlefile.extension.core.bg.tabsData.get();
  331. delete tabsData.profileName;
  332. await singlefile.extension.core.bg.tabsData.set(tabsData);
  333. await browser.storage.local.remove(["profiles", "rules", "maxParallelWorkers"]);
  334. await upgrade();
  335. }
  336. async function resetProfile(profileName) {
  337. const config = await getConfig();
  338. if (!Object.keys(config.profiles).includes(profileName)) {
  339. throw new Error("Profile not found");
  340. }
  341. config.profiles[profileName] = DEFAULT_CONFIG;
  342. await browser.storage.local.set({ profiles: config.profiles });
  343. }
  344. async function exportConfig() {
  345. const config = await getConfig();
  346. const url = URL.createObjectURL(new Blob([JSON.stringify({ profiles: config.profiles, rules: config.rules, maxParallelWorkers: config.maxParallelWorkers }, null, 2)], { type: "text/json" }));
  347. const downloadInfo = {
  348. url,
  349. filename: "singlefile-settings.json",
  350. saveAs: true
  351. };
  352. try {
  353. await singlefile.extension.core.bg.downloads.download(downloadInfo, "_");
  354. } finally {
  355. URL.revokeObjectURL(url);
  356. }
  357. }
  358. async function importConfig(config) {
  359. await browser.storage.local.remove(["profiles", "rules", "maxParallelWorkers"]);
  360. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules, maxParallelWorkers: config.maxParallelWorkers });
  361. await upgrade();
  362. }
  363. })();