config.js 13 KB

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