config.js 12 KB

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