browser/modules/ShieldStudySavant.jsm
author Bianca Danforth <bdanforth@mozilla.com>
Mon, 04 Jun 2018 16:18:39 -0700
changeset 803868 c86023e74d2205a58eb28a4fbab1d32c51f3796c
parent 803867 4f5846f1931369f5549c67dcb8cb1584c8888d14
child 798824 6751d94c5da896d9042d98dc797307c1931fba64
child 803319 04e7182ed09a4fb2139859687cb48bd43de6446c
child 803768 5ed589ee26d9411e36d9a0b6a8c970fcbad91acf
child 803780 471166dec28beead83bee08ea0d3f350e09e921c
permissions -rw-r--r--
Bug 1462725 - Add pref-controlled logging to Savant module; r=rhelmer MozReview-Commit-ID: 7dIMl7vHGr6

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var EXPORTED_SYMBOLS = ["ShieldStudySavant"];

ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");

// See LOG_LEVELS in Console.jsm. Examples: "all", "info", "warn", & "error".
const PREF_LOG_LEVEL = "shield.savant.loglevel";

// Create a new instance of the ConsoleAPI so we can control the maxLogLevel with a pref.
XPCOMUtils.defineLazyGetter(this, "log", () => {
  let ConsoleAPI = ChromeUtils.import("resource://gre/modules/Console.jsm", {}).ConsoleAPI;
  let consoleOptions = {
    maxLogLevelPref: PREF_LOG_LEVEL,
    prefix: "ShieldStudySavant",
  };
  return new ConsoleAPI(consoleOptions);
});

class ShieldStudySavantClass {
  constructor() {
    this.SHIELD_STUDY_SAVANT_PREF = "shield.savant.enabled";
  }

  init() {
    // check the pref in case Normandy flipped it on before we could add the pref listener
    this.shouldCollect = Services.prefs.getBoolPref(this.SHIELD_STUDY_SAVANT_PREF);
    if (this.shouldCollect) {
      this.enableCollection();
    }
    Services.prefs.addObserver(this.SHIELD_STUDY_SAVANT_PREF, this);
  }

  observe(subject, topic, data) {
    if (topic === "nsPref:changed" && data === this.SHIELD_STUDY_SAVANT_PREF) {
      // toggle state of the pref
      this.shouldCollect = !this.shouldCollect;
      if (this.shouldCollect) {
        this.enableCollection();
      } else {
        // Normandy has flipped off the pref
        this.endStudy("expired");
      }
    }
  }

  enableCollection() {
    log.debug("Study has been enabled; turning on data collection.");
    // TODO: enable data collection
  }

  endStudy(reason) {
    this.disableCollection();
    // TODO: send endStudy ping with reason code
    this.uninit();
  }

  disableCollection() {
    log.debug("Study has been disabled; turning off data collection.");
    // TODO: disable data collection
  }

  uninit() {
    Services.prefs.removeObserver(this.SHIELD_STUDY_SAVANT_PREF, this);
    Services.prefs.clearUserPref(this.SHIELD_STUDY_SAVANT_PREF);
    Services.prefs.clearUserPref(PREF_LOG_LEVEL);
  }
};

const ShieldStudySavant = new ShieldStudySavantClass();