summaryrefslogtreecommitdiffstats
path: root/comm/mail/modules/MailUsageTelemetry.jsm
blob: 5fe99bee02c427fb6b43c22d8b3e936fb0dd8693 (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
/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
/* 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 EXPORTED_SYMBOLS = ["MailUsageTelemetry"];

// Observed topic names.
const DOMWINDOW_OPENED_TOPIC = "domwindowopened";

// Window types we're interested in.
const WINDOW_TYPES = ["mail:3pane", "mail:messageWindow"];

// Window URLs we're interested in.
const WINDOW_URLS = [
  "chrome://messenger/content/messenger.xhtml",
  "chrome://messenger/content/messageWindow.xhtml",
  "about:3pane",
  "about:message",
];

// The elements we consider to be interactive.
const UI_TARGET_ELEMENTS = [
  "menuitem",
  "toolbarbutton",
  "key",
  "command",
  "checkbox",
  "input",
  "button",
  "image",
  "radio",
  "richlistitem",
];

// The containers of interactive elements that we care about and their pretty
// names. These should be listed in order of most-specific to least-specific,
// when iterating JavaScript will guarantee that ordering and so we will find
// the most specific area first.
const MESSENGER_UI_CONTAINER_IDS = {
  // Calendar.
  "today-pane-panel": "calendar",
  calendarTabPanel: "calendar",
  "calendar-popupset": "calendar",

  // Chat.
  chatTabPanel: "chat",
  buddyListContextMenu: "chat",
  chatConversationContextMenu: "chat",
  "chat-toolbar-context-menu": "chat",
  chatContextMenu: "chat",
  participantListContextMenu: "chat",

  // Anything to do with the 3-pane tab or message window.
  folderPaneHeaderBar: "message-display",
  folderPaneGetMessagesContext: "message-display",
  folderPaneMoreContext: "message-display",
  folderPaneContext: "message-display",
  threadPaneHeaderBar: "message-display",
  threadPaneDisplayContext: "message-display",
  aboutPagesContext: "message-display",
  browserContext: "message-display",
  mailContext: "message-display",
  singleMessage: "message-display",
  emailAddressPopup: "message-display",
  copyPopup: "message-display",
  messageIdContext: "message-display",
  attachmentItemContext: "message-display",
  attachmentListContext: "message-display",
  "attachment-toolbar-context-menu": "message-display",
  copyUrlPopup: "message-display",
  newsgroupPopup: "message-display",

  // The tab bar and the toolbox.
  "navigation-toolbox": "toolbox",
  "mail-toolbox": "toolbox",
  "quick-filter-bar": "toolbox",
  "appMenu-popup": "toolbox",
  tabContextMenu: "toolbox",
  spacesToolbar: "toolbox",
};

const KNOWN_ADDONS = [];

function telemetryId(widgetId, obscureAddons = true) {
  // Add-on IDs need to be obscured.
  function addonId(id) {
    if (!obscureAddons) {
      return id;
    }

    let pos = KNOWN_ADDONS.indexOf(id);
    if (pos < 0) {
      pos = KNOWN_ADDONS.length;
      KNOWN_ADDONS.push(id);
    }
    return `addon${pos}`;
  }

  if (widgetId.endsWith("-browserAction-toolbarbutton")) {
    widgetId = addonId(
      widgetId.substring(
        0,
        widgetId.length - "-browserAction-toolbarbutton".length
      )
    );
  } else if (widgetId.endsWith("-messageDisplayAction-toolbarbutton")) {
    widgetId = addonId(
      widgetId.substring(
        0,
        widgetId.length - "-messageDisplayAction-toolbarbutton".length
      )
    );
  } else if (widgetId.startsWith("ext-keyset-id-")) {
    // Webextension command shortcuts don't have an id on their key element so
    // we see the id from the keyset that contains them.
    widgetId = addonId(widgetId.substring("ext-keyset-id-".length));
  } else if (widgetId.includes("-menuitem--")) {
    widgetId = addonId(widgetId.substring(0, widgetId.indexOf("-menuitem--")));
  } else if (/^qfb-tag-(?!\$label\d$)/.test(widgetId)) {
    // Only record the full ID of buttons for tags named label0...label9.
    // The data for other tags are of no use to us and could contain personal
    // information, so hide it behind this generic ID.
    widgetId = "qfb-tag-";
  }
  // Collapse these IDs as each element is given a unique ID.
  widgetId = widgetId.replace(/^folderPanelView\d+/, "folderPanelView");
  // Strip UUIDs in widget IDs.
  widgetId = widgetId.replace(
    /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
    ""
  );
  // Strip mail URLs as they could contain personal information.
  widgetId = widgetId.replace(/(imap|mailbox):\/\/.*/, "");
  return widgetId.replace(/_/g, "-");
}

let MailUsageTelemetry = {
  QueryInterface: ChromeUtils.generateQI([
    "nsIObserver",
    "nsISupportsWeakReference",
  ]),

  _inited: false,

  init() {
    // Make sure to catch new chrome windows and subsession splits.
    Services.obs.addObserver(this, DOMWINDOW_OPENED_TOPIC, true);

    // Attach the handlers to the existing Windows.
    for (let winType of WINDOW_TYPES) {
      for (let win of Services.wm.getEnumerator(winType)) {
        this._registerWindow(win);
      }
    }

    this._inited = true;
  },

  uninit() {
    if (!this._inited) {
      return;
    }
    Services.obs.removeObserver(this, DOMWINDOW_OPENED_TOPIC);
  },

  observe(subject, topic, data) {
    switch (topic) {
      case DOMWINDOW_OPENED_TOPIC:
        this._onWindowOpen(subject);
        break;
    }
  },

  handleEvent(event) {
    switch (event.type) {
      case "unload":
        this._unregisterWindow(event.target);
        break;
    }
  },

  _getWidgetID(node) {
    // We want to find a sensible ID for this element.
    if (!node) {
      return null;
    }

    if (node.id) {
      return node.id;
    }

    // Special case in the tabs.
    if (node.classList.contains("tab-close-button")) {
      return "tab-close-button";
    }

    // One of these will at least let us know what the widget is for.
    let possibleAttributes = [
      "preference",
      "command",
      "observes",
      "data-l10n-id",
    ];

    // The key attribute on key elements is the actual key to listen for.
    if (node.localName != "key") {
      possibleAttributes.unshift("key");
    }

    for (let idAttribute of possibleAttributes) {
      if (node.hasAttribute(idAttribute)) {
        return node.getAttribute(idAttribute);
      }
    }

    return this._getWidgetID(node.parentElement);
  },

  _getBrowserWidgetContainer(node) {
    // Find the container holding this element.
    for (let containerId of Object.keys(MESSENGER_UI_CONTAINER_IDS)) {
      let container = node.ownerDocument.getElementById(containerId);
      if (container && container.contains(node)) {
        return MESSENGER_UI_CONTAINER_IDS[containerId];
      }
    }
    return null;
  },

  _getWidgetContainer(node) {
    if (node.localName == "key") {
      return "keyboard";
    }

    const { URL } = node.ownerDocument;
    if (WINDOW_URLS.includes(URL)) {
      return this._getBrowserWidgetContainer(node);
    }
    return null;
  },

  lastClickTarget: null,

  _recordCommand(event) {
    let types = [event.type];
    let sourceEvent = event;
    while (sourceEvent.sourceEvent) {
      sourceEvent = sourceEvent.sourceEvent;
      types.push(sourceEvent.type);
    }

    let lastTarget = this.lastClickTarget?.get();
    if (
      lastTarget &&
      sourceEvent.type == "command" &&
      sourceEvent.target.contains(lastTarget)
    ) {
      // Ignore a command event triggered by a click.
      this.lastClickTarget = null;
      return;
    }

    this.lastClickTarget = null;

    if (sourceEvent.type == "click") {
      // Only care about main button clicks.
      if (sourceEvent.button != 0) {
        return;
      }

      // This click may trigger a command event so retain the target to be able
      // to dedupe that event.
      this.lastClickTarget = Cu.getWeakReference(sourceEvent.target);
    }

    // We should never see events from web content as they are fired in a
    // content process, but let's be safe.
    let url = sourceEvent.target.ownerDocument.documentURIObject;
    if (!url.schemeIs("chrome") && !url.schemeIs("about")) {
      return;
    }

    // This is what events targeted at content will actually look like.
    if (sourceEvent.target.localName == "browser") {
      return;
    }

    // Find the actual element we're interested in.
    let node = sourceEvent.target;
    while (!UI_TARGET_ELEMENTS.includes(node.localName)) {
      node = node.parentNode;
      if (!node) {
        // A click on a space or label or something we're not interested in.
        return;
      }
    }

    let item = this._getWidgetID(node);
    let source = this._getWidgetContainer(node);

    if (item && source) {
      let scalar = `tb.ui.interaction.${source.replace("-", "_")}`;
      Services.telemetry.keyedScalarAdd(scalar, telemetryId(item), 1);
    }
  },

  /**
   * Listens for UI interactions in the window.
   */
  _addUsageListeners(win) {
    // Listen for command events from the UI.
    win.addEventListener("command", event => this._recordCommand(event), true);
    win.addEventListener("click", event => this._recordCommand(event), true);
  },

  /**
   * Adds listeners to a single chrome window.
   */
  _registerWindow(win) {
    this._addUsageListeners(win);

    win.addEventListener("unload", this);
  },

  /**
   * Removes listeners from a single chrome window.
   */
  _unregisterWindow(win) {
    win.removeEventListener("unload", this);
  },

  /**
   * Tracks the window count and registers the listeners for the tab count.
   *
   * @param{Object} win The window object.
   */
  _onWindowOpen(win) {
    // Make sure to have a |nsIDOMWindow|.
    if (!(win instanceof Ci.nsIDOMWindow)) {
      return;
    }

    let onLoad = () => {
      win.removeEventListener("load", onLoad);

      // Ignore non browser windows.
      if (
        !WINDOW_TYPES.includes(
          win.document.documentElement.getAttribute("windowtype")
        )
      ) {
        return;
      }

      this._registerWindow(win);
    };
    win.addEventListener("load", onLoad);
  },
};