config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. browser.runtime.onMessage.addListener(request => {
  62. if (request.getOptions) {
  63. return getUrlOptions(request.url);
  64. }
  65. });
  66. async function upgrade() {
  67. const config = await browser.storage.local.get();
  68. if (!config.profiles) {
  69. const defaultConfig = config;
  70. delete defaultConfig.tabsData;
  71. applyUpgrade(defaultConfig);
  72. const newConfig = { profiles: {}, rules: [] };
  73. newConfig.profiles[DEFAULT_PROFILE_NAME] = defaultConfig;
  74. browser.storage.local.remove(Object.keys(DEFAULT_CONFIG));
  75. await browser.storage.local.set(newConfig);
  76. } else {
  77. if (!config.rules) {
  78. config.rules = [];
  79. }
  80. Object.keys(config.profiles).forEach(profileName => applyUpgrade(config.profiles[profileName]));
  81. await browser.storage.local.remove(["profiles", "defaultProfile", "rules"]);
  82. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  83. }
  84. }
  85. function applyUpgrade(config) {
  86. if (config.autoSaveLoadOrUnload === undefined && !config.autoSaveUnload && !config.autoSaveLoad) {
  87. config.autoSaveLoadOrUnload = true;
  88. config.autoSaveLoad = false;
  89. config.autoSaveUnload = false;
  90. }
  91. if (!config.maxResourceSize) {
  92. config.maxResourceSize = DEFAULT_CONFIG.maxResourceSize;
  93. }
  94. if (config.appendSaveDate !== undefined) {
  95. delete config.appendSaveDate;
  96. }
  97. if ((config.compressHTML === undefined || config.compressCSS === undefined) && config.compress !== undefined) {
  98. config.compressHTML = config.compressCSS = config.compress;
  99. delete config.compress;
  100. }
  101. upgradeOldConfig(config, "removeUnusedFonts", "removeUnusedStyles");
  102. upgradeOldConfig(config, "removeUnusedStyles", "removeUnusedCSSRules");
  103. upgradeOldConfig(config, "removeAlternativeImages", "removeSrcSet");
  104. upgradeOldConfig(config, "confirmInfobarContent", "confirmInfobar");
  105. upgradeOldConfig(config, "filenameConflictAction", "conflictAction");
  106. upgradeOldConfig(config, "loadDeferredImages", "lazyLoadImages");
  107. upgradeOldConfig(config, "loadDeferredImagesMaxIdleTime", "maxLazyLoadImagesIdleTime");
  108. Object.keys(DEFAULT_CONFIG).forEach(configKey => upgradeConfig(config, configKey));
  109. }
  110. function upgradeOldConfig(config, newKey, oldKey) {
  111. if (config[newKey] === undefined && config[oldKey] !== undefined) {
  112. config[newKey] = config[oldKey];
  113. delete config[oldKey];
  114. }
  115. }
  116. function upgradeConfig(config, key) {
  117. if (config[key] === undefined) {
  118. config[key] = DEFAULT_CONFIG[key];
  119. }
  120. }
  121. async function getUrlOptions(url) {
  122. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  123. const rule = await getRule(url);
  124. return rule ? config.profiles[rule["profile"]] : config.profiles[tabsData.profileName || singlefile.config.DEFAULT_PROFILE_NAME];
  125. }
  126. async function getRule(url) {
  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 => 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"]);
  139. }
  140. function sortRules(ruleLeft, ruleRight) {
  141. ruleRight.url.length - ruleLeft.url.length;
  142. }
  143. function testRegExpRule(rule) {
  144. return rule.url.toLowerCase().startsWith(REGEXP_RULE_PREFIX);
  145. }
  146. return {
  147. DISABLED_PROFILE_NAME,
  148. DEFAULT_PROFILE_NAME,
  149. async createProfile(profileName) {
  150. const config = await getConfig();
  151. if (Object.keys(config.profiles).includes(profileName)) {
  152. throw new Error("Duplicate profile name");
  153. }
  154. config.profiles[profileName] = DEFAULT_CONFIG;
  155. await browser.storage.local.set({ profiles: config.profiles });
  156. },
  157. async getProfiles() {
  158. const config = await getConfig();
  159. return config.profiles;
  160. },
  161. async getRule(url) {
  162. return getRule(url);
  163. },
  164. async getOptions(profileName, url, autoSave) {
  165. const [config, rule] = await Promise.all([getConfig(), getRule(url)]);
  166. return rule ? config.profiles[rule[autoSave ? "autoSaveProfile" : "profile"]] : config.profiles[profileName || singlefile.config.DEFAULT_PROFILE_NAME];
  167. },
  168. async updateProfile(profileName, profile) {
  169. const config = await getConfig();
  170. if (!Object.keys(config.profiles).includes(profileName)) {
  171. throw new Error("Profile not found");
  172. }
  173. config.profiles[profileName] = profile;
  174. await browser.storage.local.set({ profiles: config.profiles });
  175. },
  176. async renameProfile(oldProfileName, profileName) {
  177. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  178. if (!Object.keys(config.profiles).includes(oldProfileName)) {
  179. throw new Error("Profile not found");
  180. }
  181. if (Object.keys(config.profiles).includes(profileName)) {
  182. throw new Error("Duplicate profile name");
  183. }
  184. if (oldProfileName == DEFAULT_PROFILE_NAME) {
  185. throw new Error("Default settings cannot be renamed");
  186. }
  187. if (tabsData.profileName == oldProfileName) {
  188. tabsData.profileName = profileName;
  189. await singlefile.tabsData.set(tabsData);
  190. }
  191. config.profiles[profileName] = config.profiles[oldProfileName];
  192. config.rules.forEach(rule => {
  193. if (rule.profile == oldProfileName) {
  194. rule.profile = profileName;
  195. }
  196. if (rule.autoSaveProfile == oldProfileName) {
  197. rule.autoSaveProfile = profileName;
  198. }
  199. });
  200. delete config.profiles[oldProfileName];
  201. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  202. },
  203. async deleteProfile(profileName) {
  204. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  205. if (!Object.keys(config.profiles).includes(profileName)) {
  206. throw new Error("Profile not found");
  207. }
  208. if (profileName == DEFAULT_PROFILE_NAME) {
  209. throw new Error("Default settings cannot be deleted");
  210. }
  211. if (tabsData.profileName == profileName) {
  212. delete tabsData.profileName;
  213. await singlefile.tabsData.set(tabsData);
  214. }
  215. config.rules.forEach(rule => {
  216. if (rule.profile == profileName) {
  217. rule.profile = DEFAULT_PROFILE_NAME;
  218. }
  219. if (rule.autoSaveProfile == profileName) {
  220. rule.autoSaveProfile = DEFAULT_PROFILE_NAME;
  221. }
  222. });
  223. delete config.profiles[profileName];
  224. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  225. },
  226. async getRules() {
  227. const config = await getConfig();
  228. return config.rules;
  229. },
  230. async addRule(url, profile, autoSaveProfile) {
  231. if (!url) {
  232. throw new Error("URL is empty");
  233. }
  234. const config = await getConfig();
  235. if (config.rules.find(rule => rule.url == url)) {
  236. throw new Error("URL already exists");
  237. }
  238. config.rules.push({
  239. url,
  240. profile,
  241. autoSaveProfile
  242. });
  243. await browser.storage.local.set({ rules: config.rules });
  244. },
  245. async deleteRule(url) {
  246. if (!url) {
  247. throw new Error("URL is empty");
  248. }
  249. const config = await getConfig();
  250. config.rules = config.rules.filter(rule => rule.url != url);
  251. await browser.storage.local.set({ rules: config.rules });
  252. },
  253. async deleteRules(profileName) {
  254. const config = await getConfig();
  255. config.rules = config.rules = profileName ? config.rules.filter(rule => rule.autoSaveProfile != profileName && rule.profile != profileName) : [];
  256. await browser.storage.local.set({ rules: config.rules });
  257. },
  258. async updateRule(url, newURL, profile, autoSaveProfile) {
  259. if (!url || !newURL) {
  260. throw new Error("URL is empty");
  261. }
  262. const config = await getConfig();
  263. const urlConfig = config.rules.find(rule => rule.url == url);
  264. if (!urlConfig) {
  265. throw new Error("URL not found");
  266. }
  267. if (config.rules.find(rule => rule.url == newURL && rule.url != url)) {
  268. throw new Error("New URL already exists");
  269. }
  270. urlConfig.url = newURL;
  271. urlConfig.profile = profile;
  272. urlConfig.autoSaveProfile = autoSaveProfile;
  273. await browser.storage.local.set({ rules: config.rules });
  274. },
  275. async reset() {
  276. await pendingUpgradePromise;
  277. const tabsData = await singlefile.tabsData.get();
  278. delete tabsData.profileName;
  279. await singlefile.tabsData.set(tabsData);
  280. await browser.storage.local.remove(["profiles", "rules"]);
  281. await browser.storage.local.set({ profiles: { [DEFAULT_PROFILE_NAME]: DEFAULT_CONFIG }, rules: [] });
  282. },
  283. async export() {
  284. const config = await getConfig();
  285. const url = URL.createObjectURL(new Blob([JSON.stringify({ profiles: config.profiles, rules: config.rules }, null, 2)], { type: "text/json" }));
  286. const downloadInfo = {
  287. url,
  288. filename: "singlefile-settings.json",
  289. saveAs: true
  290. };
  291. const downloadId = await browser.downloads.download(downloadInfo);
  292. return new Promise((resolve, reject) => {
  293. browser.downloads.onChanged.addListener(onChanged);
  294. function onChanged(event) {
  295. if (event.id == downloadId && event.state) {
  296. if (event.state.current == "complete") {
  297. URL.revokeObjectURL(url);
  298. resolve({});
  299. browser.downloads.onChanged.removeListener(onChanged);
  300. }
  301. if (event.state.current == "interrupted" && (!event.error || event.error.current != "USER_CANCELED")) {
  302. URL.revokeObjectURL(url);
  303. reject(new Error(event.state.current));
  304. browser.downloads.onChanged.removeListener(onChanged);
  305. }
  306. }
  307. }
  308. });
  309. },
  310. async import(file) {
  311. const reader = new FileReader();
  312. reader.readAsText(file);
  313. const serializedConfig = await new Promise((resolve, reject) => {
  314. reader.addEventListener("load", () => resolve(reader.result), false);
  315. reader.addEventListener("error", reject, false);
  316. });
  317. const config = JSON.parse(serializedConfig);
  318. await browser.storage.local.remove(["profiles", "rules"]);
  319. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  320. await upgrade();
  321. }
  322. };
  323. })();