config.js 24 KB

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