config.js 12 KB

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