config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. * Copyright 2018 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 getOptions();
  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 getOptions() {
  122. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  123. return config.profiles[tabsData.profileName || DEFAULT_PROFILE_NAME];
  124. }
  125. async function getConfig() {
  126. await pendingUpgradePromise;
  127. return browser.storage.local.get(["profiles", "rules"]);
  128. }
  129. function sortRules(ruleLeft, ruleRight) {
  130. ruleRight.url.length - ruleLeft.url.length;
  131. }
  132. function testRegExpRule(rule) {
  133. return rule.url.toLowerCase().startsWith(REGEXP_RULE_PREFIX);
  134. }
  135. return {
  136. DISABLED_PROFILE_NAME,
  137. DEFAULT_PROFILE_NAME,
  138. async createProfile(profileName) {
  139. const config = await getConfig();
  140. if (Object.keys(config.profiles).includes(profileName)) {
  141. throw new Error("Duplicate profile name");
  142. }
  143. config.profiles[profileName] = DEFAULT_CONFIG;
  144. await browser.storage.local.set({ profiles: config.profiles });
  145. },
  146. async getProfiles() {
  147. const config = await getConfig();
  148. return config.profiles;
  149. },
  150. async getRule(url) {
  151. const config = await getConfig();
  152. const regExpRules = config.rules.filter(rule => testRegExpRule(rule));
  153. let rule = regExpRules.sort(sortRules).find(rule => url && url.match(new RegExp(rule.url.split(REGEXP_RULE_PREFIX)[1])));
  154. if (!rule) {
  155. const normalRules = config.rules.filter(rule => !testRegExpRule(rule));
  156. rule = normalRules.sort(sortRules).find(rule => url && url.includes(rule.url));
  157. }
  158. return rule;
  159. },
  160. async getOptions(profileName, url, autoSave) {
  161. const config = await getConfig();
  162. const rule = await this.getRule(url);
  163. return rule ? config.profiles[rule[autoSave ? "autoSaveProfile" : "profile"]] : config.profiles[profileName || singlefile.config.DEFAULT_PROFILE_NAME];
  164. },
  165. async updateProfile(profileName, profile) {
  166. const config = await getConfig();
  167. if (!Object.keys(config.profiles).includes(profileName)) {
  168. throw new Error("Profile not found");
  169. }
  170. config.profiles[profileName] = profile;
  171. await browser.storage.local.set({ profiles: config.profiles });
  172. },
  173. async renameProfile(oldProfileName, profileName) {
  174. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  175. if (!Object.keys(config.profiles).includes(oldProfileName)) {
  176. throw new Error("Profile not found");
  177. }
  178. if (Object.keys(config.profiles).includes(profileName)) {
  179. throw new Error("Duplicate profile name");
  180. }
  181. if (oldProfileName == DEFAULT_PROFILE_NAME) {
  182. throw new Error("Default settings cannot be renamed");
  183. }
  184. if (tabsData.profileName == oldProfileName) {
  185. tabsData.profileName = profileName;
  186. await singlefile.tabsData.set(tabsData);
  187. }
  188. config.profiles[profileName] = config.profiles[oldProfileName];
  189. config.rules.forEach(rule => {
  190. if (rule.profile == oldProfileName) {
  191. rule.profile = profileName;
  192. }
  193. if (rule.autoSaveProfile == oldProfileName) {
  194. rule.autoSaveProfile = profileName;
  195. }
  196. });
  197. delete config.profiles[oldProfileName];
  198. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  199. },
  200. async deleteProfile(profileName) {
  201. const [config, tabsData] = await Promise.all([getConfig(), singlefile.tabsData.get()]);
  202. if (!Object.keys(config.profiles).includes(profileName)) {
  203. throw new Error("Profile not found");
  204. }
  205. if (profileName == DEFAULT_PROFILE_NAME) {
  206. throw new Error("Default settings cannot be deleted");
  207. }
  208. if (tabsData.profileName == profileName) {
  209. delete tabsData.profileName;
  210. await singlefile.tabsData.set(tabsData);
  211. }
  212. config.rules.forEach(rule => {
  213. if (rule.profile == profileName) {
  214. rule.profile = DEFAULT_PROFILE_NAME;
  215. }
  216. if (rule.autoSaveProfile == profileName) {
  217. rule.autoSaveProfile = DEFAULT_PROFILE_NAME;
  218. }
  219. });
  220. delete config.profiles[profileName];
  221. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  222. },
  223. async getRules() {
  224. const config = await getConfig();
  225. return config.rules;
  226. },
  227. async addRule(url, profile, autoSaveProfile) {
  228. if (!url) {
  229. throw new Error("URL is empty");
  230. }
  231. const config = await getConfig();
  232. if (config.rules.find(rule => rule.url == url)) {
  233. throw new Error("URL already exists");
  234. }
  235. config.rules.push({
  236. url,
  237. profile,
  238. autoSaveProfile
  239. });
  240. await browser.storage.local.set({ rules: config.rules });
  241. },
  242. async deleteRule(url) {
  243. if (!url) {
  244. throw new Error("URL is empty");
  245. }
  246. const config = await getConfig();
  247. config.rules = config.rules.filter(rule => rule.url != url);
  248. await browser.storage.local.set({ rules: config.rules });
  249. },
  250. async deleteRules(profileName) {
  251. const config = await getConfig();
  252. config.rules = config.rules = profileName ? config.rules.filter(rule => rule.autoSaveProfile != profileName && rule.profile != profileName) : [];
  253. await browser.storage.local.set({ rules: config.rules });
  254. },
  255. async updateRule(url, newURL, profile, autoSaveProfile) {
  256. if (!url || !newURL) {
  257. throw new Error("URL is empty");
  258. }
  259. const config = await getConfig();
  260. const urlConfig = config.rules.find(rule => rule.url == url);
  261. if (!urlConfig) {
  262. throw new Error("URL not found");
  263. }
  264. if (config.rules.find(rule => rule.url == newURL && rule.url != url)) {
  265. throw new Error("New URL already exists");
  266. }
  267. urlConfig.url = newURL;
  268. urlConfig.profile = profile;
  269. urlConfig.autoSaveProfile = autoSaveProfile;
  270. await browser.storage.local.set({ rules: config.rules });
  271. },
  272. async reset() {
  273. await pendingUpgradePromise;
  274. const tabsData = await singlefile.tabsData.get();
  275. delete tabsData.profileName;
  276. await singlefile.tabsData.set(tabsData);
  277. await browser.storage.local.remove(["profiles", "rules"]);
  278. await browser.storage.local.set({ profiles: { [DEFAULT_PROFILE_NAME]: DEFAULT_CONFIG }, rules: [] });
  279. },
  280. async export() {
  281. const config = await getConfig();
  282. const url = URL.createObjectURL(new Blob([JSON.stringify({ profiles: config.profiles, rules: config.rules }, null, 2)], { type: "text/json" }));
  283. const downloadInfo = {
  284. url,
  285. filename: "singlefile-settings.json",
  286. saveAs: true
  287. };
  288. const downloadId = await browser.downloads.download(downloadInfo);
  289. return new Promise((resolve, reject) => {
  290. browser.downloads.onChanged.addListener(onChanged);
  291. function onChanged(event) {
  292. if (event.id == downloadId && event.state) {
  293. if (event.state.current == "complete") {
  294. URL.revokeObjectURL(url);
  295. resolve({});
  296. browser.downloads.onChanged.removeListener(onChanged);
  297. }
  298. if (event.state.current == "interrupted" && (!event.error || event.error.current != "USER_CANCELED")) {
  299. URL.revokeObjectURL(url);
  300. reject(new Error(event.state.current));
  301. browser.downloads.onChanged.removeListener(onChanged);
  302. }
  303. }
  304. }
  305. });
  306. },
  307. async import(file) {
  308. const reader = new FileReader();
  309. reader.readAsText(file);
  310. const serializedConfig = await new Promise((resolve, reject) => {
  311. reader.addEventListener("load", () => resolve(reader.result), false);
  312. reader.addEventListener("error", reject, false);
  313. });
  314. const config = JSON.parse(serializedConfig);
  315. await browser.storage.local.remove(["profiles", "rules"]);
  316. await browser.storage.local.set({ profiles: config.profiles, rules: config.rules });
  317. await upgrade();
  318. }
  319. };
  320. })();