config.js 13 KB

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