summaryrefslogtreecommitdiffstats
path: root/toolkit/components/normandy/lib/Heartbeat.sys.mjs
blob: fa66844acb0f7ff02379271abc0be62836e225db (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/* 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/. */

import { Preferences } from "resource://gre/modules/Preferences.sys.mjs";
import { TelemetryController } from "resource://gre/modules/TelemetryController.sys.mjs";
import { clearTimeout, setTimeout } from "resource://gre/modules/Timer.sys.mjs";
import { CleanupManager } from "resource://normandy/lib/CleanupManager.sys.mjs";
import { EventEmitter } from "resource://normandy/lib/EventEmitter.sys.mjs";
import { LogManager } from "resource://normandy/lib/LogManager.sys.mjs";

const PREF_SURVEY_DURATION = "browser.uitour.surveyDuration";
const NOTIFICATION_TIME = 3000;
const HEARTBEAT_CSS_URI = Services.io.newURI(
  "resource://normandy/skin/shared/Heartbeat.css"
);
const log = LogManager.getLogger("heartbeat");
const windowsWithInjectedCss = new WeakSet();
let anyWindowsWithInjectedCss = false;

// Add cleanup handler for CSS injected into windows by Heartbeat
CleanupManager.addCleanupHandler(() => {
  if (anyWindowsWithInjectedCss) {
    for (let window of Services.wm.getEnumerator("navigator:browser")) {
      if (windowsWithInjectedCss.has(window)) {
        const utils = window.windowUtils;
        utils.removeSheet(HEARTBEAT_CSS_URI, window.AGENT_SHEET);
        windowsWithInjectedCss.delete(window);
      }
    }
  }
});

/**
 * Show the Heartbeat UI to request user feedback.
 *
 * @param chromeWindow
 *        The chrome window that the heartbeat notification is displayed in.
 * @param {Object} options Options object.
 * @param {String} options.message
 *        The message, or question, to display on the notification.
 * @param {String} options.thanksMessage
 *        The thank you message to display after user votes.
 * @param {String} options.flowId
 *        An identifier for this rating flow. Please note that this is only used to
 *        identify the notification box.
 * @param {String} [options.engagementButtonLabel=null]
 *        The text of the engagement button to use instead of stars. If this is null
 *        or invalid, rating stars are used.
 * @param {String} [options.learnMoreMessage=null]
 *        The label of the learn more link. No link will be shown if this is null.
 * @param {String} [options.learnMoreUrl=null]
 *        The learn more URL to open when clicking on the learn more link. No learn more
 *        will be shown if this is an invalid URL.
 * @param {String} [options.surveyId]
 *        An ID for the survey, reflected in the Telemetry ping.
 * @param {Number} [options.surveyVersion]
 *        Survey's version number, reflected in the Telemetry ping.
 * @param {boolean} [options.testing]
 *        Whether this is a test survey, reflected in the Telemetry ping.
 * @param {String} [options.postAnswerURL=null]
 *        The url to visit after the user answers the question.
 */
export var Heartbeat = class {
  constructor(chromeWindow, options) {
    if (typeof options.flowId !== "string") {
      throw new Error(
        `flowId must be a string, but got ${JSON.stringify(
          options.flowId
        )}, a ${typeof options.flowId}`
      );
    }

    if (!options.flowId) {
      throw new Error("flowId must not be an empty string");
    }

    if (typeof options.message !== "string") {
      throw new Error(
        `message must be a string, but got ${JSON.stringify(
          options.message
        )}, a ${typeof options.message}`
      );
    }

    if (!options.message) {
      throw new Error("message must not be an empty string");
    }

    if (options.postAnswerUrl) {
      options.postAnswerUrl = new URL(options.postAnswerUrl);
    } else {
      options.postAnswerUrl = null;
    }

    if (options.learnMoreUrl) {
      try {
        options.learnMoreUrl = new URL(options.learnMoreUrl);
      } catch (e) {
        options.learnMoreUrl = null;
      }
    }

    this.chromeWindow = chromeWindow;
    this.eventEmitter = new EventEmitter();
    this.options = options;
    this.surveyResults = {};
    this.buttons = [];

    if (!windowsWithInjectedCss.has(chromeWindow)) {
      windowsWithInjectedCss.add(chromeWindow);
      const utils = chromeWindow.windowUtils;
      utils.loadSheet(HEARTBEAT_CSS_URI, chromeWindow.AGENT_SHEET);
      anyWindowsWithInjectedCss = true;
    }

    // so event handlers are consistent
    this.handleWindowClosed = this.handleWindowClosed.bind(this);
    this.close = this.close.bind(this);

    // Add Learn More Link
    if (this.options.learnMoreMessage && this.options.learnMoreUrl) {
      this.buttons.push({
        link: this.options.learnMoreUrl.toString(),
        label: this.options.learnMoreMessage,
        callback: () => {
          this.maybeNotifyHeartbeat("LearnMore");
          return true;
        },
      });
    }

    if (this.options.engagementButtonLabel) {
      this.buttons.push({
        label: this.options.engagementButtonLabel,
        callback: () => {
          // Let the consumer know user engaged.
          this.maybeNotifyHeartbeat("Engaged");

          this.userEngaged({
            type: "button",
            flowId: this.options.flowId,
          });

          // Return true so that the notification bar doesn't close itself since
          // we have a thank you message to show.
          return true;
        },
      });
    }

    this.notificationBox = this.chromeWindow.gNotificationBox;
    this.notice = this.notificationBox.appendNotification(
      "heartbeat-" + this.options.flowId,
      {
        label: this.options.message,
        image: "resource://normandy/skin/shared/heartbeat-icon.svg",
        priority: this.notificationBox.PRIORITY_SYSTEM,
        eventCallback: eventType => {
          if (eventType !== "removed") {
            return;
          }
          this.maybeNotifyHeartbeat("NotificationClosed");
        },
      },
      this.buttons
    );
    this.notice.classList.add("heartbeat");
    this.notice.messageText.classList.add("heartbeat");

    // Build the heartbeat stars
    if (!this.options.engagementButtonLabel) {
      const numStars = this.options.engagementButtonLabel ? 0 : 5;
      this.ratingContainer = this.chromeWindow.document.createElement("span");
      this.ratingContainer.id = "star-rating-container";

      for (let i = 0; i < numStars; i++) {
        // create a star rating element
        const ratingElement =
          this.chromeWindow.document.createXULElement("toolbarbutton");

        // style it
        const starIndex = numStars - i;
        ratingElement.className = "plain star-x";
        ratingElement.id = "star" + starIndex;
        ratingElement.setAttribute("data-score", starIndex);

        // Add the click handler
        ratingElement.addEventListener("click", ev => {
          const rating = parseInt(ev.target.getAttribute("data-score"));
          this.maybeNotifyHeartbeat("Voted", { score: rating });
          this.userEngaged({
            type: "stars",
            score: rating,
            flowId: this.options.flowId,
          });
        });

        this.ratingContainer.appendChild(ratingElement);
      }

      this.notice.buttonContainer.append(this.ratingContainer);
    }

    // Let the consumer know the notification was shown.
    this.maybeNotifyHeartbeat("NotificationOffered");
    this.chromeWindow.addEventListener(
      "SSWindowClosing",
      this.handleWindowClosed
    );

    const surveyDuration = Preferences.get(PREF_SURVEY_DURATION, 300) * 1000;
    this.surveyEndTimer = setTimeout(() => {
      this.maybeNotifyHeartbeat("SurveyExpired");
      this.close();
    }, surveyDuration);

    CleanupManager.addCleanupHandler(this.close);
  }

  maybeNotifyHeartbeat(name, data = {}) {
    if (this.pingSent) {
      log.warn(
        "Heartbeat event received after Telemetry ping sent. name:",
        name,
        "data:",
        data
      );
      return;
    }

    const timestamp = Date.now();
    let sendPing = false;
    let cleanup = false;

    const phases = {
      NotificationOffered: () => {
        this.surveyResults.flowId = this.options.flowId;
        this.surveyResults.offeredTS = timestamp;
      },
      LearnMore: () => {
        if (!this.surveyResults.learnMoreTS) {
          this.surveyResults.learnMoreTS = timestamp;
        }
      },
      Engaged: () => {
        this.surveyResults.engagedTS = timestamp;
      },
      Voted: () => {
        this.surveyResults.votedTS = timestamp;
        this.surveyResults.score = data.score;
      },
      SurveyExpired: () => {
        this.surveyResults.expiredTS = timestamp;
      },
      NotificationClosed: () => {
        this.surveyResults.closedTS = timestamp;
        cleanup = true;
        sendPing = true;
      },
      WindowClosed: () => {
        this.surveyResults.windowClosedTS = timestamp;
        cleanup = true;
        sendPing = true;
      },
      default: () => {
        log.error("Unrecognized Heartbeat event:", name);
      },
    };

    (phases[name] || phases.default)();

    data.timestamp = timestamp;
    data.flowId = this.options.flowId;
    this.eventEmitter.emit(name, data);

    if (sendPing) {
      // Send the ping to Telemetry
      const payload = Object.assign({ version: 1 }, this.surveyResults);
      for (const meta of ["surveyId", "surveyVersion", "testing"]) {
        if (this.options.hasOwnProperty(meta)) {
          payload[meta] = this.options[meta];
        }
      }

      log.debug("Sending telemetry");
      TelemetryController.submitExternalPing("heartbeat", payload, {
        addClientId: true,
        addEnvironment: true,
      });

      // only for testing
      this.eventEmitter.emit("TelemetrySent", payload);

      // Survey is complete, clear out the expiry timer & survey configuration
      this.endTimerIfPresent("surveyEndTimer");

      this.pingSent = true;
      this.surveyResults = null;
    }

    if (cleanup) {
      this.cleanup();
    }
  }

  userEngaged(engagementParams) {
    // Make the heartbeat icon pulse twice
    this.notice.label = this.options.thanksMessage;
    this.notice.messageImage.classList.remove("pulse-onshow");
    this.notice.messageImage.classList.add("pulse-twice");

    // Remove the custom contents of the notice and the buttons
    if (this.ratingContainer) {
      this.ratingContainer.remove();
    }
    for (let button of this.notice.buttonContainer.querySelectorAll("button")) {
      button.remove();
    }

    // Open the engagement tab if we have a valid engagement URL.
    if (this.options.postAnswerUrl) {
      for (const key in engagementParams) {
        this.options.postAnswerUrl.searchParams.append(
          key,
          engagementParams[key]
        );
      }
      // Open the engagement URL in a new tab.
      let { gBrowser } = this.chromeWindow;
      gBrowser.selectedTab = gBrowser.addWebTab(
        this.options.postAnswerUrl.toString(),
        {
          triggeringPrincipal:
            Services.scriptSecurityManager.createNullPrincipal({}),
        }
      );
    }

    this.endTimerIfPresent("surveyEndTimer");

    this.engagementCloseTimer = setTimeout(
      () => this.close(),
      NOTIFICATION_TIME
    );
  }

  endTimerIfPresent(timerName) {
    if (this[timerName]) {
      clearTimeout(this[timerName]);
      this[timerName] = null;
    }
  }

  handleWindowClosed() {
    this.maybeNotifyHeartbeat("WindowClosed");
  }

  close() {
    this.notificationBox.removeNotification(this.notice);
  }

  cleanup() {
    // Kill the timers which might call things after we've cleaned up:
    this.endTimerIfPresent("surveyEndTimer");
    this.endTimerIfPresent("engagementCloseTimer");
    // remove listeners
    this.chromeWindow.removeEventListener(
      "SSWindowClosing",
      this.handleWindowClosed
    );
    // remove references for garbage collection
    this.chromeWindow = null;
    this.notificationBox = null;
    this.notice = null;
    this.ratingContainer = null;
    this.eventEmitter = null;
    // Ensure we don't re-enter and release the CleanupManager's reference to us:
    CleanupManager.removeCleanupHandler(this.close);
  }
};