config.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global browser, singlefile, URL, Blob, FileReader */
  21. singlefile.config = (() => {
  22. const DEFAULT_PROFILE_NAME = "__Default_Settings__";
  23. const DISABLED_PROFILE_NAME = "__Disabled_Settings__";
  24. const REGEXP_RULE_PREFIX = "regexp:";
  25. const DEFAULT_CONFIG = {
  26. removeHiddenElements: true,
  27. removeUnusedStyles: true,
  28. removeUnusedFonts: true,
  29. removeFrames: false,
  30. removeImports: true,
  31. removeScripts: true,
  32. compressHTML: true,
  33. compressCSS: true,
  34. loadDeferredImages: true,
  35. loadDeferredImagesMaxIdleTime: 1500,
  36. filenameTemplate: "{page-title} ({date-iso} {time-locale}).html",
  37. infobarTemplate: "",
  38. confirmInfobarContent: false,
  39. confirmFilename: false,
  40. filenameConflictAction: "uniquify",
  41. contextMenuEnabled: true,
  42. shadowEnabled: true,
  43. maxResourceSizeEnabled: false,
  44. maxResourceSize: 10,
  45. removeAudioSrc: true,
  46. removeVideoSrc: true,
  47. displayInfobar: true,
  48. displayStats: false,
  49. backgroundSave: true,
  50. autoSaveDelay: 1,
  51. autoSaveLoad: false,
  52. autoSaveUnload: false,
  53. autoSaveLoadOrUnload: true,
  54. removeAlternativeFonts: true,
  55. removeAlternativeMedias: true,
  56. removeAlternativeImages: true,
  57. groupDuplicateImages: true,
  58. saveRawPage: false
  59. };
  60. let pendingUpgradePromise = upgrade();
  61. async function upgrade() {
  62. const config = await browser.storage.local.get();
  63. if (!config.profiles) {
  64. const defaultConfig = config;
  65. delete defaultConfig.tabsData;
  66. applyUpgrade(defaultConfig);
  67. const newConfig = { profiles: {}, rules: [] };
  68. newConfig.profiles[DEFAULT_PROFILE_NAME] = defaultConfig;
  69. browser.storage.local.remove(Object.keys(DEFAULT_CONFIG));
  70. await browser.storage.local.set(newConfig);
  71. } else {
  72. if (!config.rules) {
  73. config.rules = [];
  74. }
  75. Object.keys(config.profiles).forEach(profileName => applyUpgrade(config.profiles[profileName]));
  76. await browser.storage.local.remove(["profiles", "defaultProfile", "rules"]);
  77. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  78. }
  79. }
  80. function applyUpgrade(config) {
  81. if (config.autoSaveLoadOrUnload === undefined && !config.autoSaveUnload && !config.autoSaveLoad) {
  82. config.autoSaveLoadOrUnload = true;
  83. config.autoSaveLoad = false;
  84. config.autoSaveUnload = false;
  85. }
  86. if (!config.maxResourceSize) {
  87. config.maxResourceSize = DEFAULT_CONFIG.maxResourceSize;
  88. }
  89. if (config.appendSaveDate !== undefined) {
  90. delete config.appendSaveDate;
  91. }
  92. if ((config.compressHTML === undefined || config.compressCSS === undefined) && config.compress !== undefined) {
  93. config.compressHTML = config.compressCSS = config.compress;
  94. delete config.compress;
  95. }
  96. upgradeOldConfig(config, "removeUnusedFonts", "removeUnusedStyles");
  97. upgradeOldConfig(config, "removeUnusedStyles", "removeUnusedCSSRules");
  98. upgradeOldConfig(config, "removeAlternativeImages", "removeSrcSet");
  99. upgradeOldConfig(config, "confirmInfobarContent", "confirmInfobar");
  100. upgradeOldConfig(config, "filenameConflictAction", "conflictAction");
  101. upgradeOldConfig(config, "loadDeferredImages", "lazyLoadImages");
  102. upgradeOldConfig(config, "loadDeferredImagesMaxIdleTime", "maxLazyLoadImagesIdleTime");
  103. Object.keys(DEFAULT_CONFIG).forEach(configKey => upgradeConfig(config, configKey));
  104. }
  105. function upgradeOldConfig(config, newKey, oldKey) {
  106. if (config[newKey] === undefined && config[oldKey] !== undefined) {
  107. config[newKey] = config[oldKey];
  108. delete config[oldKey];
  109. }
  110. }
  111. function upgradeConfig(config, key) {
  112. if (config[key] === undefined) {
  113. config[key] = DEFAULT_CONFIG[key];
  114. }
  115. }
  116. async function getRule(url) {
  117. const config = await getConfig();
  118. const regExpRules = config.rules.filter(rule => testRegExpRule(rule));
  119. let rule = regExpRules.sort(sortRules).find(rule => url && url.match(new RegExp(rule.url.split(REGEXP_RULE_PREFIX)[1])));
  120. if (!rule) {
  121. const normalRules = config.rules.filter(rule => !testRegExpRule(rule));
  122. rule = normalRules.sort(sortRules).find(rule => url && url.includes(rule.url));
  123. }
  124. return rule;
  125. }
  126. async function getConfig() {
  127. await pendingUpgradePromise;
  128. return browser.storage.local.get(["profiles", "rules"]);
  129. }
  130. function sortRules(ruleLeft, ruleRight) {
  131. ruleRight.url.length - ruleLeft.url.length;
  132. }
  133. function testRegExpRule(rule) {
  134. return rule.url.toLowerCase().startsWith(REGEXP_RULE_PREFIX);
  135. }
  136. return {
  137. DISABLED_PROFILE_NAME,
  138. DEFAULT_PROFILE_NAME,
  139. async createProfile(profileName) {
  140. const config = await getConfig();
  141. if (Object.keys(config.profiles).includes(profileName)) {
  142. throw new Error("Duplicate profile name");
  143. }
  144. config.profiles[profileName] = DEFAULT_CONFIG;
  145. await browser.storage.local.set({ profiles: config.profiles });
  146. },
  147. async getProfiles() {
  148. const config = await getConfig();
  149. return config.profiles;
  150. },
  151. async getRule(url) {
  152. return getRule(url);
  153. },
  154. async getOptions(url, autoSave) {
  155. const [config, rule, tabsData] = await Promise.all([getConfig(), getRule(url), singlefile.tabsData.get()]);
  156. const profileName = tabsData.profileName;
  157. return rule ? config.profiles[rule[autoSave ? "autoSaveProfile" : "profile"]] : config.profiles[profileName || singlefile.config.DEFAULT_PROFILE_NAME];
  158. },
  159. async updateProfile(profileName, profile) {
  160. const config = await getConfig();
  161. if (!Object.keys(config.profiles).includes(profileName)) {
  162. throw new Error("Profile not found");
  163. }
  164. config.profiles[profileName] = profile;
  165. await browser.storage.local.set({ profiles: config.profiles });
  166. },
  167. async renameProfile(oldProfileName, profileName) {
  168. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  169. if (!Object.keys(config.profiles).includes(oldProfileName)) {
  170. throw new Error("Profile not found");
  171. }
  172. if (Object.keys(config.profiles).includes(profileName)) {
  173. throw new Error("Duplicate profile name");
  174. }
  175. if (oldProfileName == DEFAULT_PROFILE_NAME) {
  176. throw new Error("Default settings cannot be renamed");
  177. }
  178. if (tabsData.profileName == oldProfileName) {
  179. tabsData.profileName = profileName;
  180. await singlefile.tabsData.set(tabsData);
  181. }
  182. config.profiles[profileName] = config.profiles[oldProfileName];
  183. config.rules.forEach(rule => {
  184. if (rule.profile == oldProfileName) {
  185. rule.profile = profileName;
  186. }
  187. if (rule.autoSaveProfile == oldProfileName) {
  188. rule.autoSaveProfile = profileName;
  189. }
  190. });
  191. delete config.profiles[oldProfileName];
  192. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  193. },
  194. async deleteProfile(profileName) {
  195. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  196. if (!Object.keys(config.profiles).includes(profileName)) {
  197. throw new Error("Profile not found");
  198. }
  199. if (profileName == DEFAULT_PROFILE_NAME) {
  200. throw new Error("Default settings cannot be deleted");
  201. }
  202. if (tabsData.profileName == profileName) {
  203. delete tabsData.profileName;
  204. await singlefile.tabsData.set(tabsData);
  205. }
  206. config.rules.forEach(rule => {
  207. if (rule.profile == profileName) {
  208. rule.profile = DEFAULT_PROFILE_NAME;
  209. }
  210. if (rule.autoSaveProfile == profileName) {
  211. rule.autoSaveProfile = DEFAULT_PROFILE_NAME;
  212. }
  213. });
  214. delete config.profiles[profileName];
  215. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  216. },
  217. async getRules() {
  218. const config = await getConfig();
  219. return config.rules;
  220. },
  221. async addRule(url, profile, autoSaveProfile) {
  222. if (!url) {
  223. throw new Error("URL is empty");
  224. }
  225. const config = await getConfig();
  226. if (config.rules.find(rule => rule.url == url)) {
  227. throw new Error("URL already exists");
  228. }
  229. config.rules.push({
  230. url,
  231. profile,
  232. autoSaveProfile
  233. });
  234. await browser.storage.local.set({ rules: config.rules });
  235. },
  236. async deleteRule(url) {
  237. if (!url) {
  238. throw new Error("URL is empty");
  239. }
  240. const config = await getConfig();
  241. config.rules = config.rules.filter(rule => rule.url != url);
  242. await browser.storage.local.set({ rules: config.rules });
  243. },
  244. async deleteRules(profileName) {
  245. const config = await getConfig();
  246. config.rules = config.rules = profileName ? config.rules.filter(rule => rule.autoSaveProfile != profileName && rule.profile != profileName) : [];
  247. await browser.storage.local.set({ rules: config.rules });
  248. },
  249. async updateRule(url, newURL, profile, autoSaveProfile) {
  250. if (!url || !newURL) {
  251. throw new Error("URL is empty");
  252. }
  253. const config = await getConfig();
  254. const urlConfig = config.rules.find(rule => rule.url == url);
  255. if (!urlConfig) {
  256. throw new Error("URL not found");
  257. }
  258. if (config.rules.find(rule => rule.url == newURL && rule.url != url)) {
  259. throw new Error("New URL already exists");
  260. }
  261. urlConfig.url = newURL;
  262. urlConfig.profile = profile;
  263. urlConfig.autoSaveProfile = autoSaveProfile;
  264. await browser.storage.local.set({ rules: config.rules });
  265. },
  266. async reset() {
  267. await pendingUpgradePromise;
  268. const tabsData = await singlefile.tabsData.get();
  269. delete tabsData.profileName;
  270. await singlefile.tabsData.set(tabsData);
  271. await browser.storage.local.remove(["profiles", "rules"]);
  272. await browser.storage.local.set({ profiles: { [DEFAULT_PROFILE_NAME]: DEFAULT_CONFIG }, rules: [] });
  273. },
  274. async export() {
  275. const config = await getConfig();
  276. const url = URL.createObjectURL(new Blob([JSON.stringify({ profiles: config.profiles, rules: config.rules }, null, 2)], { type: "text/json" }));
  277. const downloadInfo = {
  278. url,
  279. filename: "singlefile-settings.json",
  280. saveAs: true
  281. };
  282. const downloadId = await browser.downloads.download(downloadInfo);
  283. return new Promise((resolve, reject) => {
  284. browser.downloads.onChanged.addListener(onChanged);
  285. function onChanged(event) {
  286. if (event.id == downloadId && event.state) {
  287. if (event.state.current == "complete") {
  288. URL.revokeObjectURL(url);
  289. resolve({});
  290. browser.downloads.onChanged.removeListener(onChanged);
  291. }
  292. if (event.state.current == "interrupted" && (!event.error || event.error.current != "USER_CANCELED")) {
  293. URL.revokeObjectURL(url);
  294. reject(new Error(event.state.current));
  295. browser.downloads.onChanged.removeListener(onChanged);
  296. }
  297. }
  298. }
  299. });
  300. },
  301. async import(file) {
  302. const reader = new FileReader();
  303. reader.readAsText(file);
  304. const serializedConfig = await new Promise((resolve, reject) => {
  305. reader.addEventListener("load", () => resolve(reader.result), false);
  306. reader.addEventListener("error", reject, false);
  307. });
  308. const config = JSON.parse(serializedConfig);
  309. await browser.storage.local.remove(["profiles", "rules"]);
  310. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  311. await upgrade();
  312. }
  313. };
  314. })();