tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

network-locations.js (2110B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 "use strict";
      6 
      7 const NETWORK_LOCATIONS_PREF = "devtools.aboutdebugging.network-locations";
      8 
      9 /**
     10 * This module provides a collection of helper methods to read and update network
     11 * locations monitored by about-debugging.
     12 */
     13 
     14 function addNetworkLocationsObserver(listener) {
     15  Services.prefs.addObserver(NETWORK_LOCATIONS_PREF, listener);
     16 }
     17 exports.addNetworkLocationsObserver = addNetworkLocationsObserver;
     18 
     19 function removeNetworkLocationsObserver(listener) {
     20  Services.prefs.removeObserver(NETWORK_LOCATIONS_PREF, listener);
     21 }
     22 exports.removeNetworkLocationsObserver = removeNetworkLocationsObserver;
     23 
     24 /**
     25 * Read the current preference value for aboutdebugging network locations.
     26 * Will throw if the value cannot be parsed or is not an array.
     27 */
     28 function _parsePreferenceAsArray() {
     29  const pref = Services.prefs.getStringPref(NETWORK_LOCATIONS_PREF, "[]");
     30  const parsedValue = JSON.parse(pref);
     31  if (!Array.isArray(parsedValue)) {
     32    throw new Error("Expected array value in " + NETWORK_LOCATIONS_PREF);
     33  }
     34  return parsedValue;
     35 }
     36 
     37 function getNetworkLocations() {
     38  try {
     39    return _parsePreferenceAsArray();
     40  } catch (e) {
     41    Services.prefs.clearUserPref(NETWORK_LOCATIONS_PREF);
     42    return [];
     43  }
     44 }
     45 exports.getNetworkLocations = getNetworkLocations;
     46 
     47 function addNetworkLocation(location) {
     48  const locations = getNetworkLocations();
     49  const locationsSet = new Set(locations);
     50  locationsSet.add(location);
     51 
     52  Services.prefs.setStringPref(
     53    NETWORK_LOCATIONS_PREF,
     54    JSON.stringify([...locationsSet])
     55  );
     56 }
     57 exports.addNetworkLocation = addNetworkLocation;
     58 
     59 function removeNetworkLocation(location) {
     60  const locations = getNetworkLocations();
     61  const locationsSet = new Set(locations);
     62  locationsSet.delete(location);
     63 
     64  Services.prefs.setStringPref(
     65    NETWORK_LOCATIONS_PREF,
     66    JSON.stringify([...locationsSet])
     67  );
     68 }
     69 exports.removeNetworkLocation = removeNetworkLocation;