config.js 13 KB

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