config.js 11 KB

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