config.js 13 KB

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