config.js 13 KB

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