summaryrefslogtreecommitdiffstats
path: root/browser/components/extensions/parent/ext-normandyAddonStudy.js
blob: 24bf08c2a32655616d11489a6a1c86383552fe2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* 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";

const { AddonStudies } = ChromeUtils.import(
  "resource://normandy/lib/AddonStudies.jsm"
);
const { ClientID } = ChromeUtils.importESModule(
  "resource://gre/modules/ClientID.sys.mjs"
);

ChromeUtils.defineModuleGetter(
  this,
  "AddonManager",
  "resource://gre/modules/AddonManager.jsm"
);

this.normandyAddonStudy = class extends ExtensionAPI {
  getAPI(context) {
    let { extension } = context;

    return {
      normandyAddonStudy: {
        /**
         * Returns a study object for the current study.
         *
         * @returns {Study}
         */
        async getStudy() {
          const studies = await AddonStudies.getAll();
          return studies.find(study => study.addonId === extension.id);
        },

        /**
         * Marks the study as ended and then uninstalls the addon.
         *
         * @param {string} reason Why the study is ending
         */
        async endStudy(reason) {
          const study = await this.getStudy();

          // Mark the study as ended
          await AddonStudies.markAsEnded(study, reason);

          // Uninstall the addon
          const addon = await AddonManager.getAddonByID(study.addonId);
          if (addon) {
            await addon.uninstall();
          }
        },

        /**
         * Returns an object with metadata about the client which may
         * be required for constructing survey URLs.
         *
         * @returns {object}
         */
        async getClientMetadata() {
          return {
            updateChannel: Services.appinfo.defaultUpdateChannel,
            fxVersion: Services.appinfo.version,
            clientID: await ClientID.getClientID(),
          };
        },

        onUnenroll: new EventManager({
          context,
          name: "normandyAddonStudy.onUnenroll",
          register: fire => {
            const listener = async reason => {
              await fire.async(reason);
            };

            AddonStudies.addUnenrollListener(extension.id, listener);

            return () => {
              AddonStudies.removeUnenrollListener(extension.id, listener);
            };
          },
        }).api(),
      },
    };
  }
};