config.js 13 KB

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