config.js 13 KB

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