config.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, navigator, URL, Blob, File */
  24. import { download } from "./download-util.js";
  25. import * as tabsData from "./tabs-data.js";
  26. const CURRENT_PROFILE_NAME = "-";
  27. const DEFAULT_PROFILE_NAME = "__Default_Settings__";
  28. const DISABLED_PROFILE_NAME = "__Disabled_Settings__";
  29. const REGEXP_RULE_PREFIX = "regexp:";
  30. const PROFILE_NAME_PREFIX = "profile_";
  31. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  32. const BACKGROUND_SAVE_SUPPORTED = !(/Mobile.*Firefox/.test(navigator.userAgent) || /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/Vivaldi/.test(navigator.userAgent) && !/OPR/.test(navigator.userAgent));
  33. const BADGE_COLOR_SUPPORTED = IS_NOT_SAFARI;
  34. const AUTO_SAVE_SUPPORTED = IS_NOT_SAFARI;
  35. const SELECTABLE_TABS_SUPPORTED = IS_NOT_SAFARI;
  36. const AUTO_OPEN_EDITOR_SUPPORTED = IS_NOT_SAFARI;
  37. const INFOBAR_SUPPORTED = IS_NOT_SAFARI;
  38. const BOOKMARKS_API_SUPPORTED = IS_NOT_SAFARI;
  39. const IDENTITY_API_SUPPORTED = IS_NOT_SAFARI;
  40. const CLIPBOARD_API_SUPPORTED = IS_NOT_SAFARI;
  41. const NATIVE_API_API_SUPPORTED = IS_NOT_SAFARI;
  42. const WEB_BLOCKING_API_SUPPORTED = IS_NOT_SAFARI;
  43. const SHARE_API_SUPPORTED = navigator.canShare && navigator.canShare({ files: [new File([new Blob([""], { type: "text/html" })], "test.html")] });
  44. const LEGACY_FILENAME_REPLACED_CHARACTERS = ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\u0000-\u001f", "\u007f"];
  45. const DEFAULT_FILENAME_REPLACED_CHARACTERS = ["~", "+", "?", "%", "*", ":", "|", "\"", "<", ">", "\\\\", "\x00-\x1f", "\x7F"];
  46. const DEFAULT_FILENAME_REPLACEMENT_CHARACTERS = ["~", "+", "?", "%", "*", ":", "|", """, "<", ">", "\"];
  47. const DEFAULT_CONFIG = {
  48. removeHiddenElements: true,
  49. removeUnusedStyles: true,
  50. removeUnusedFonts: true,
  51. removeFrames: false,
  52. compressHTML: true,
  53. compressCSS: false,
  54. loadDeferredImages: true,
  55. loadDeferredImagesMaxIdleTime: 1500,
  56. loadDeferredImagesBlockCookies: false,
  57. loadDeferredImagesBlockStorage: false,
  58. loadDeferredImagesKeepZoomLevel: false,
  59. loadDeferredImagesDispatchScrollEvent: false,
  60. loadDeferredImagesBeforeFrames: false,
  61. filenameTemplate: "%if-empty<{page-title}|No title> ({date-locale} {time-locale}).{filename-extension}",
  62. infobarTemplate: "",
  63. includeInfobar: !IS_NOT_SAFARI,
  64. openInfobar: false,
  65. confirmInfobarContent: false,
  66. autoClose: false,
  67. confirmFilename: false,
  68. filenameConflictAction: "uniquify",
  69. filenameMaxLength: 192,
  70. filenameMaxLengthUnit: "bytes",
  71. filenameReplacedCharacters: DEFAULT_FILENAME_REPLACED_CHARACTERS,
  72. filenameReplacementCharacter: "_",
  73. filenameReplacementCharacters: DEFAULT_FILENAME_REPLACEMENT_CHARACTERS,
  74. replaceEmojisInFilename: false,
  75. saveFilenameTemplateData: false,
  76. contextMenuEnabled: true,
  77. tabMenuEnabled: true,
  78. browserActionMenuEnabled: true,
  79. shadowEnabled: true,
  80. logsEnabled: true,
  81. progressBarEnabled: true,
  82. maxResourceSizeEnabled: false,
  83. maxResourceSize: 10,
  84. displayInfobar: true,
  85. displayStats: false,
  86. backgroundSave: BACKGROUND_SAVE_SUPPORTED,
  87. defaultEditorMode: "normal",
  88. applySystemTheme: true,
  89. autoSaveDelay: 1,
  90. autoSaveLoad: false,
  91. autoSaveUnload: false,
  92. autoSaveLoadOrUnload: true,
  93. autoSaveDiscard: false,
  94. autoSaveRemove: false,
  95. autoSaveRepeat: false,
  96. autoSaveRepeatDelay: 10,
  97. removeAlternativeFonts: true,
  98. removeAlternativeMedias: true,
  99. removeAlternativeImages: true,
  100. groupDuplicateImages: true,
  101. maxSizeDuplicateImages: 512 * 1024,
  102. saveRawPage: false,
  103. saveToClipboard: false,
  104. addProof: false,
  105. saveToGDrive: false,
  106. saveToDropbox: false,
  107. saveWithWebDAV: false,
  108. webDAVURL: "",
  109. webDAVUser: "",
  110. webDAVPassword: "",
  111. saveToGitHub: false,
  112. saveToRestFormApi: false,
  113. saveToS3: false,
  114. githubToken: "",
  115. githubUser: "",
  116. githubRepository: "SingleFile-Archives",
  117. githubBranch: "main",
  118. saveWithCompanion: false,
  119. sharePage: false,
  120. forceWebAuthFlow: false,
  121. resolveFragmentIdentifierURLs: false,
  122. userScriptEnabled: false,
  123. openEditor: false,
  124. openSavedPage: false,
  125. autoOpenEditor: false,
  126. saveCreatedBookmarks: false,
  127. allowedBookmarkFolders: [],
  128. ignoredBookmarkFolders: [],
  129. replaceBookmarkURL: true,
  130. saveFavicon: true,
  131. includeBOM: false,
  132. warnUnsavedPage: true,
  133. displayInfobarInEditor: false,
  134. compressContent: false,
  135. createRootDirectory: false,
  136. selfExtractingArchive: true,
  137. extractDataFromPage: true,
  138. preventAppendedData: false,
  139. insertEmbeddedImage: false,
  140. insertEmbeddedScreenshotImage: false,
  141. insertTextBody: false,
  142. autoSaveExternalSave: false,
  143. insertMetaNoIndex: false,
  144. insertMetaCSP: true,
  145. passReferrerOnError: false,
  146. password: "",
  147. insertSingleFileComment: true,
  148. removeSavedDate: false,
  149. blockMixedContent: false,
  150. saveOriginalURLs: false,
  151. acceptHeaders: {
  152. font: "application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8",
  153. image: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
  154. stylesheet: "text/css,*/*;q=0.1",
  155. script: "*/*",
  156. document: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  157. video: "video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5",
  158. audio: "audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5"
  159. },
  160. moveStylesInHead: false,
  161. networkTimeout: 0,
  162. woleetKey: "",
  163. blockImages: false,
  164. blockAlternativeImages: true,
  165. blockStylesheets: false,
  166. blockFonts: false,
  167. blockScripts: true,
  168. blockVideos: true,
  169. blockAudios: true,
  170. delayBeforeProcessing: 0,
  171. _migratedTemplateFormat: true,
  172. saveToRestFormApiUrl: "",
  173. saveToRestFormApiFileFieldName: "",
  174. saveToRestFormApiUrlFieldName: "",
  175. saveToRestFormApiToken: "",
  176. S3Domain: "s3.amazonaws.com",
  177. S3Region: "",
  178. S3Bucket: "",
  179. S3AccessKey: "",
  180. S3SecretKey: "",
  181. resolveLinks: true,
  182. groupDuplicateStylesheets: false,
  183. infobarPositionAbsolute: false,
  184. infobarPositionTop: "16px",
  185. infobarPositionRight: "16px",
  186. infobarPositionBottom: "",
  187. infobarPositionLeft: ""
  188. };
  189. const DEFAULT_RULES = [{
  190. "url": "file:",
  191. "profile": "__Default_Settings__",
  192. "autoSaveProfile": "__Disabled_Settings__"
  193. }];
  194. const MIGRATION_DEFAULT_VARIABLES_VALUES = {
  195. "page-title": "No title",
  196. "page-heading": "No heading",
  197. "page-language": "No language",
  198. "page-description": "No description",
  199. "page-author": "No author",
  200. "page-creator": "No creator",
  201. "page-publisher": "No publisher",
  202. "url-hash": "No hash",
  203. "url-host": "No host",
  204. "url-hostname": "No hostname",
  205. "url-href": "No href",
  206. "url-href-digest-sha-1": "No hash",
  207. "url-href-flat": "No href",
  208. "url-referrer": "No referrer",
  209. "url-referrer-flat": "No referrer",
  210. "url-password": "No password",
  211. "url-pathname": "No pathname",
  212. "url-pathname-flat": "No pathname",
  213. "url-port": "No port",
  214. "url-protocol": "No protocol",
  215. "url-search": "No search",
  216. "url-username": "No username",
  217. "tab-id": "No tab id",
  218. "tab-index": "No tab index",
  219. "url-last-segment": "No last segment"
  220. };
  221. let configStorage;
  222. let pendingUpgradePromise = upgrade();
  223. export {
  224. DEFAULT_PROFILE_NAME,
  225. DISABLED_PROFILE_NAME,
  226. CURRENT_PROFILE_NAME,
  227. BACKGROUND_SAVE_SUPPORTED,
  228. BADGE_COLOR_SUPPORTED,
  229. AUTO_SAVE_SUPPORTED,
  230. SELECTABLE_TABS_SUPPORTED,
  231. AUTO_OPEN_EDITOR_SUPPORTED,
  232. INFOBAR_SUPPORTED,
  233. BOOKMARKS_API_SUPPORTED,
  234. IDENTITY_API_SUPPORTED,
  235. CLIPBOARD_API_SUPPORTED,
  236. NATIVE_API_API_SUPPORTED,
  237. WEB_BLOCKING_API_SUPPORTED,
  238. SHARE_API_SUPPORTED,
  239. getConfig as get,
  240. getRule,
  241. getOptions,
  242. getProfiles,
  243. onMessage,
  244. updateRule,
  245. addRule,
  246. getAuthInfo,
  247. getDropboxAuthInfo,
  248. setAuthInfo,
  249. setDropboxAuthInfo,
  250. removeAuthInfo,
  251. removeDropboxAuthInfo
  252. };
  253. async function upgrade() {
  254. const { sync } = await browser.storage.local.get();
  255. if (sync) {
  256. configStorage = browser.storage.sync;
  257. } else {
  258. configStorage = browser.storage.local;
  259. }
  260. const config = await configStorage.get();
  261. if (!config[PROFILE_NAME_PREFIX + DEFAULT_PROFILE_NAME]) {
  262. if (config.profiles) {
  263. const profileNames = Object.keys(config.profiles);
  264. for (const profileName of profileNames) {
  265. await setProfile(profileName, config.profiles[profileName]);
  266. }
  267. } else {
  268. await setProfile(DEFAULT_PROFILE_NAME, DEFAULT_CONFIG);
  269. }
  270. } else if (config.profiles) {
  271. await configStorage.remove(["profiles"]);
  272. }
  273. if (!config.rules) {
  274. await configStorage.set({ rules: DEFAULT_RULES });
  275. }
  276. if (!config.maxParallelWorkers) {
  277. await configStorage.set({ maxParallelWorkers: navigator.hardwareConcurrency || 4 });
  278. }
  279. if (!config.processInForeground) {
  280. await configStorage.set({ processInForeground: false });
  281. }
  282. const profileNames = await getProfileNames();
  283. profileNames.map(async profileName => {
  284. const profile = await getProfile(profileName);
  285. if (!profile._migratedTemplateFormat) {
  286. profile.filenameTemplate = updateFilenameTemplate(profile.filenameTemplate);
  287. profile._migratedTemplateFormat = true;
  288. }
  289. for (const key of Object.keys(DEFAULT_CONFIG)) {
  290. if (profile[key] === undefined) {
  291. profile[key] = DEFAULT_CONFIG[key];
  292. }
  293. }
  294. if (isSameArray(profile.filenameReplacedCharacters, LEGACY_FILENAME_REPLACED_CHARACTERS)
  295. && isSameArray(profile.filenameReplacementCharacters, DEFAULT_FILENAME_REPLACEMENT_CHARACTERS)) {
  296. profile.filenameReplacedCharacters = DEFAULT_FILENAME_REPLACED_CHARACTERS;
  297. }
  298. await setProfile(profileName, profile);
  299. });
  300. }
  301. function updateFilenameTemplate(template) {
  302. try {
  303. Object.keys(MIGRATION_DEFAULT_VARIABLES_VALUES).forEach(variable => {
  304. const value = MIGRATION_DEFAULT_VARIABLES_VALUES[variable];
  305. template = template.replaceAll(`{${variable}}`, `%if-empty<{${variable}}|${value}>`);
  306. });
  307. return template;
  308. } catch (_error) {
  309. // ignored
  310. }
  311. }
  312. async function getRule(url, ignoreWildcard) {
  313. const { rules } = await configStorage.get(["rules"]);
  314. const regExpRules = rules.filter(rule => testRegExpRule(rule));
  315. let rule = regExpRules.sort(sortRules).find(rule => url && url.match(new RegExp(rule.url.split(REGEXP_RULE_PREFIX)[1])));
  316. if (!rule) {
  317. const normalRules = rules.filter(rule => !testRegExpRule(rule));
  318. rule = normalRules.sort(sortRules).find(rule => (!ignoreWildcard && rule.url == "*") || (url && url.includes(rule.url)));
  319. }
  320. return rule;
  321. }
  322. async function getConfig() {
  323. await pendingUpgradePromise;
  324. const { maxParallelWorkers, processInForeground } = await configStorage.get(["maxParallelWorkers", "processInForeground"]);
  325. const rules = await getRules();
  326. const profiles = await getProfiles();
  327. return { profiles, rules, maxParallelWorkers, processInForeground };
  328. }
  329. function sortRules(ruleLeft, ruleRight) {
  330. return ruleRight.url.length - ruleLeft.url.length;
  331. }
  332. function testRegExpRule(rule) {
  333. return rule.url.toLowerCase().startsWith(REGEXP_RULE_PREFIX);
  334. }
  335. async function onMessage(message) {
  336. if (message.method.endsWith(".deleteRules")) {
  337. await deleteRules(message.profileName);
  338. }
  339. if (message.method.endsWith(".deleteRule")) {
  340. await deleteRule(message.url);
  341. }
  342. if (message.method.endsWith(".addRule")) {
  343. await addRule(message.url, message.profileName, message.autoSaveProfileName);
  344. }
  345. if (message.method.endsWith(".createProfile")) {
  346. await createProfile(message.profileName, message.fromProfileName || DEFAULT_PROFILE_NAME);
  347. }
  348. if (message.method.endsWith(".renameProfile")) {
  349. await renameProfile(message.profileName, message.newProfileName);
  350. }
  351. if (message.method.endsWith(".deleteProfile")) {
  352. await deleteProfile(message.profileName);
  353. }
  354. if (message.method.endsWith(".resetProfiles")) {
  355. await resetProfiles();
  356. }
  357. if (message.method.endsWith(".resetProfile")) {
  358. await resetProfile(message.profileName);
  359. }
  360. if (message.method.endsWith(".importConfig")) {
  361. await importConfig(message.config);
  362. }
  363. if (message.method.endsWith(".updateProfile")) {
  364. await updateProfile(message.profileName, message.profile);
  365. }
  366. if (message.method.endsWith(".updateRule")) {
  367. await updateRule(message.url, message.newUrl, message.profileName, message.autoSaveProfileName);
  368. }
  369. if (message.method.endsWith(".getConstants")) {
  370. return {
  371. DISABLED_PROFILE_NAME,
  372. DEFAULT_PROFILE_NAME,
  373. CURRENT_PROFILE_NAME,
  374. BACKGROUND_SAVE_SUPPORTED,
  375. BADGE_COLOR_SUPPORTED,
  376. AUTO_SAVE_SUPPORTED,
  377. SELECTABLE_TABS_SUPPORTED,
  378. AUTO_OPEN_EDITOR_SUPPORTED,
  379. INFOBAR_SUPPORTED,
  380. BOOKMARKS_API_SUPPORTED,
  381. IDENTITY_API_SUPPORTED,
  382. CLIPBOARD_API_SUPPORTED,
  383. NATIVE_API_API_SUPPORTED,
  384. WEB_BLOCKING_API_SUPPORTED,
  385. SHARE_API_SUPPORTED
  386. };
  387. }
  388. if (message.method.endsWith(".getRules")) {
  389. return getRules();
  390. }
  391. if (message.method.endsWith(".getProfiles")) {
  392. return getProfiles();
  393. }
  394. if (message.method.endsWith(".exportConfig")) {
  395. return exportConfig();
  396. }
  397. if (message.method.endsWith(".enableSync")) {
  398. await browser.storage.local.set({ sync: true });
  399. const syncConfig = await browser.storage.sync.get();
  400. if (!syncConfig || !syncConfig.rules) {
  401. const profileKeyNames = await getProfileKeyNames();
  402. const localConfig = await browser.storage.local.get(["rules", "maxParallelWorkers", "processInForeground", ...profileKeyNames]);
  403. await browser.storage.sync.set(localConfig);
  404. }
  405. configStorage = browser.storage.sync;
  406. await upgrade();
  407. return {};
  408. }
  409. if (message.method.endsWith(".disableSync")) {
  410. await browser.storage.local.set({ sync: false });
  411. const syncConfig = await browser.storage.sync.get();
  412. const localConfig = await browser.storage.local.get();
  413. if (syncConfig && syncConfig.rules && (!localConfig || !localConfig.rules)) {
  414. await browser.storage.local.set({ rules: syncConfig.rules, maxParallelWorkers: syncConfig.maxParallelWorkers, processInForeground: syncConfig.processInForeground });
  415. const profiles = {};
  416. await browser.storage.local.set(profiles);
  417. }
  418. configStorage = browser.storage.local;
  419. await upgrade();
  420. return {};
  421. }
  422. if (message.method.endsWith(".isSync")) {
  423. return { sync: (await browser.storage.local.get()).sync };
  424. }
  425. return {};
  426. }
  427. async function createProfile(profileName, fromProfileName) {
  428. const profileNames = await getProfileNames();
  429. if (profileNames.includes(profileName)) {
  430. throw new Error("Duplicate profile name");
  431. }
  432. const profileFrom = await getProfile(fromProfileName);
  433. const profile = JSON.parse(JSON.stringify(profileFrom));
  434. await setProfile(profileName, profile);
  435. }
  436. async function getProfiles() {
  437. await pendingUpgradePromise;
  438. const profileKeyNames = await getProfileKeyNames();
  439. const profiles = await configStorage.get(profileKeyNames);
  440. const result = {};
  441. Object.keys(profiles).forEach(profileName => result[profileName.substring(PROFILE_NAME_PREFIX.length)] = profiles[profileName]);
  442. return result;
  443. }
  444. async function getOptions(url, autoSave) {
  445. await pendingUpgradePromise;
  446. const [rule, allTabsData] = await Promise.all([getRule(url), tabsData.get()]);
  447. const tabProfileName = allTabsData.profileName || DEFAULT_PROFILE_NAME;
  448. let selectedProfileName;
  449. if (rule) {
  450. const profileName = rule[autoSave ? "autoSaveProfile" : "profile"];
  451. selectedProfileName = profileName == CURRENT_PROFILE_NAME ? tabProfileName : profileName;
  452. } else {
  453. selectedProfileName = tabProfileName;
  454. }
  455. const profile = await getProfile(selectedProfileName);
  456. return Object.assign({ profileName: selectedProfileName }, profile);
  457. }
  458. async function updateProfile(profileName, profile) {
  459. const profileNames = await getProfileNames();
  460. if (!profileNames.includes(profileName)) {
  461. throw new Error("Profile not found");
  462. }
  463. const previousProfile = await getProfile(profileName);
  464. Object.keys(previousProfile).forEach(key => {
  465. profile[key] = profile[key] === undefined ? previousProfile[key] : profile[key];
  466. });
  467. await setProfile(profileName, profile);
  468. }
  469. async function renameProfile(oldProfileName, profileName) {
  470. const profileNames = await getProfileNames();
  471. const allTabsData = await tabsData.get();
  472. const rules = await getRules();
  473. if (!profileNames.includes(oldProfileName)) {
  474. throw new Error("Profile not found");
  475. }
  476. if (profileNames.includes(profileName)) {
  477. throw new Error("Duplicate profile name");
  478. }
  479. if (oldProfileName == DEFAULT_PROFILE_NAME) {
  480. throw new Error("Default settings cannot be renamed");
  481. }
  482. if (allTabsData.profileName == oldProfileName) {
  483. allTabsData.profileName = profileName;
  484. await tabsData.set(allTabsData);
  485. }
  486. rules.forEach(rule => {
  487. if (rule.profile == oldProfileName) {
  488. rule.profile = profileName;
  489. }
  490. if (rule.autoSaveProfile == oldProfileName) {
  491. rule.autoSaveProfile = profileName;
  492. }
  493. });
  494. const profile = await getProfile(oldProfileName);
  495. await configStorage.remove([PROFILE_NAME_PREFIX + oldProfileName]);
  496. await configStorage.set({ [PROFILE_NAME_PREFIX + profileName]: profile, rules });
  497. }
  498. async function deleteProfile(profileName) {
  499. const profileNames = await getProfileNames();
  500. const allTabsData = await tabsData.get();
  501. const rules = await getRules();
  502. if (!profileNames.includes(profileName)) {
  503. throw new Error("Profile not found");
  504. }
  505. if (profileName == DEFAULT_PROFILE_NAME) {
  506. throw new Error("Default settings cannot be deleted");
  507. }
  508. if (allTabsData.profileName == profileName) {
  509. delete allTabsData.profileName;
  510. await tabsData.set(allTabsData);
  511. }
  512. rules.forEach(rule => {
  513. if (rule.profile == profileName) {
  514. rule.profile = DEFAULT_PROFILE_NAME;
  515. }
  516. if (rule.autoSaveProfile == profileName) {
  517. rule.autoSaveProfile = DEFAULT_PROFILE_NAME;
  518. }
  519. });
  520. configStorage.remove([PROFILE_NAME_PREFIX + profileName]);
  521. await configStorage.set({ rules });
  522. }
  523. async function getRules() {
  524. return (await configStorage.get(["rules"])).rules;
  525. }
  526. async function getProfileNames() {
  527. return Object.keys(await configStorage.get()).filter(key => key.startsWith(PROFILE_NAME_PREFIX)).map(key => key.substring(PROFILE_NAME_PREFIX.length));
  528. }
  529. async function getProfileKeyNames() {
  530. return Object.keys(await configStorage.get()).filter(key => key.startsWith(PROFILE_NAME_PREFIX));
  531. }
  532. async function getProfile(profileName) {
  533. const profileKey = PROFILE_NAME_PREFIX + profileName;
  534. const data = await configStorage.get([profileKey]);
  535. return data[profileKey];
  536. }
  537. async function setProfile(profileName, profileData) {
  538. const profileKey = PROFILE_NAME_PREFIX + profileName;
  539. await configStorage.set({ [profileKey]: profileData });
  540. }
  541. async function addRule(url, profile, autoSaveProfile) {
  542. if (!url) {
  543. throw new Error("URL is empty");
  544. }
  545. const rules = await getRules();
  546. if (rules.find(rule => rule.url == url)) {
  547. throw new Error("URL already exists");
  548. }
  549. rules.push({
  550. url,
  551. profile,
  552. autoSaveProfile
  553. });
  554. await configStorage.set({ rules });
  555. }
  556. async function deleteRule(url) {
  557. if (!url) {
  558. throw new Error("URL is empty");
  559. }
  560. const rules = await getRules();
  561. await configStorage.set({ rules: rules.filter(rule => rule.url != url) });
  562. }
  563. async function deleteRules(profileName) {
  564. const rules = await getRules();
  565. await configStorage.set({ rules: profileName ? rules.filter(rule => rule.autoSaveProfile != profileName && rule.profile != profileName) : [] });
  566. }
  567. async function updateRule(url, newURL, profile, autoSaveProfile) {
  568. if (!url || !newURL) {
  569. throw new Error("URL is empty");
  570. }
  571. const rules = await getRules();
  572. const urlConfig = rules.find(rule => rule.url == url);
  573. if (!urlConfig) {
  574. throw new Error("URL not found");
  575. }
  576. if (rules.find(rule => rule.url == newURL && rule.url != url)) {
  577. throw new Error("New URL already exists");
  578. }
  579. urlConfig.url = newURL;
  580. urlConfig.profile = profile;
  581. urlConfig.autoSaveProfile = autoSaveProfile;
  582. await configStorage.set({ rules });
  583. }
  584. async function getAuthInfo() {
  585. return (await configStorage.get()).authInfo;
  586. }
  587. async function getDropboxAuthInfo() {
  588. return (await configStorage.get()).dropboxAuthInfo;
  589. }
  590. async function setAuthInfo(authInfo) {
  591. await configStorage.set({ authInfo });
  592. }
  593. async function setDropboxAuthInfo(authInfo) {
  594. await configStorage.set({ dropboxAuthInfo: authInfo });
  595. }
  596. async function removeAuthInfo() {
  597. let authInfo = getAuthInfo();
  598. if (authInfo.revokableAccessToken) {
  599. setAuthInfo({ revokableAccessToken: authInfo.revokableAccessToken });
  600. } else {
  601. await configStorage.remove(["authInfo"]);
  602. }
  603. }
  604. async function removeDropboxAuthInfo() {
  605. let authInfo = getDropboxAuthInfo();
  606. if (authInfo.revokableAccessToken) {
  607. setDropboxAuthInfo({ revokableAccessToken: authInfo.revokableAccessToken });
  608. } else {
  609. await configStorage.remove(["dropboxAuthInfo"]);
  610. }
  611. }
  612. async function resetProfiles() {
  613. await pendingUpgradePromise;
  614. const allTabsData = await tabsData.get();
  615. delete allTabsData.profileName;
  616. await tabsData.set(allTabsData);
  617. let profileKeyNames = await getProfileKeyNames();
  618. await configStorage.remove([...profileKeyNames, "rules", "maxParallelWorkers", "processInForeground"]);
  619. await upgrade();
  620. }
  621. async function resetProfile(profileName) {
  622. const profileNames = await getProfileNames();
  623. if (!profileNames.includes(profileName)) {
  624. throw new Error("Profile not found");
  625. }
  626. await setProfile(profileName, DEFAULT_CONFIG);
  627. }
  628. async function exportConfig() {
  629. const config = await getConfig();
  630. const textContent = JSON.stringify({ profiles: config.profiles, rules: config.rules, maxParallelWorkers: config.maxParallelWorkers, processInForeground: config.processInForeground }, null, 2);
  631. const filename = `singlefile-settings-${(new Date()).toISOString().replace(/:/g, "_")}.json`;
  632. if (BACKGROUND_SAVE_SUPPORTED) {
  633. const url = URL.createObjectURL(new Blob([textContent], { type: "text/json" }));
  634. try {
  635. await download({
  636. url,
  637. filename,
  638. saveAs: true
  639. }, "_");
  640. } finally {
  641. URL.revokeObjectURL(url);
  642. }
  643. return {};
  644. } else {
  645. return {
  646. filename,
  647. textContent
  648. };
  649. }
  650. }
  651. async function importConfig(config) {
  652. const profileNames = await getProfileNames();
  653. const profileKeyNames = await getProfileKeyNames();
  654. const allTabsData = await tabsData.get();
  655. if (profileNames.includes(allTabsData.profileName)) {
  656. delete allTabsData.profileName;
  657. await tabsData.set(allTabsData);
  658. }
  659. await configStorage.remove([...profileKeyNames, "rules", "maxParallelWorkers", "processInForeground"]);
  660. const newConfig = { rules: config.rules, maxParallelWorkers: config.maxParallelWorkers, processInForeground: config.processInForeground };
  661. Object.keys(config.profiles).forEach(profileName => newConfig[PROFILE_NAME_PREFIX + profileName] = config.profiles[profileName]);
  662. await configStorage.set(newConfig);
  663. await upgrade();
  664. }
  665. function isSameArray(arrayLeft, arrayRight) {
  666. return arrayLeft.length == arrayRight.length && arrayLeft.every((value, index) => value == arrayRight[index]);
  667. }