config.js 13 KB

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