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
|
/* 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/. */
/* globals main, auth, browser, catcher, deviceInfo, communication, log */
"use strict";
this.analytics = (function() {
const exports = {};
const GA_PORTION = 0.1; // 10% of users will send to the server/GA
// This is set from storage, or randomly; if it is less that GA_PORTION then we send analytics:
let myGaSegment = 1;
let telemetryPrefKnown = false;
let telemetryEnabled;
// If we ever get a 410 Gone response (or 404) from the server, we'll stop trying to send events for the rest
// of the session
let hasReturnedGone = false;
// If there's this many entirely failed responses (e.g., server can't be contacted), then stop sending events
// for the rest of the session:
let serverFailedResponses = 3;
const EVENT_BATCH_DURATION = 1000; // ms for setTimeout
let pendingEvents = [];
let pendingTimings = [];
let eventsTimeoutHandle, timingsTimeoutHandle;
const fetchOptions = {
method: "POST",
mode: "cors",
headers: { "content-type": "application/json" },
credentials: "include",
};
function shouldSendEvents() {
return !hasReturnedGone && serverFailedResponses > 0 && myGaSegment < GA_PORTION;
}
function flushEvents() {
if (pendingEvents.length === 0) {
return;
}
const eventsUrl = `${main.getBackend()}/event`;
const deviceId = auth.getDeviceId();
const sendTime = Date.now();
pendingEvents.forEach(event => {
event.queueTime = sendTime - event.eventTime;
log.info(`sendEvent ${event.event}/${event.action}/${event.label || "none"} ${JSON.stringify(event.options)}`);
});
const body = JSON.stringify({deviceId, events: pendingEvents});
const fetchRequest = fetch(eventsUrl, Object.assign({body}, fetchOptions));
fetchWatcher(fetchRequest);
pendingEvents = [];
}
function flushTimings() {
if (pendingTimings.length === 0) {
return;
}
const timingsUrl = `${main.getBackend()}/timing`;
const deviceId = auth.getDeviceId();
const body = JSON.stringify({deviceId, timings: pendingTimings});
const fetchRequest = fetch(timingsUrl, Object.assign({body}, fetchOptions));
fetchWatcher(fetchRequest);
pendingTimings.forEach(t => {
log.info(`sendTiming ${t.timingCategory}/${t.timingLabel}/${t.timingVar}: ${t.timingValue}`);
});
pendingTimings = [];
}
function sendTiming(timingLabel, timingVar, timingValue) {
// sendTiming is only called in response to sendEvent, so no need to check
// the telemetry pref again here.
if (!shouldSendEvents()) {
return;
}
const timingCategory = "addon";
pendingTimings.push({
timingCategory,
timingLabel,
timingVar,
timingValue,
});
if (!timingsTimeoutHandle) {
timingsTimeoutHandle = setTimeout(() => {
timingsTimeoutHandle = null;
flushTimings();
}, EVENT_BATCH_DURATION);
}
}
exports.sendEvent = function(action, label, options) {
const eventCategory = "addon";
if (!telemetryPrefKnown) {
log.warn("sendEvent called before we were able to refresh");
return Promise.resolve();
}
if (!telemetryEnabled) {
log.info(`Cancelled sendEvent ${eventCategory}/${action}/${label || "none"} ${JSON.stringify(options)}`);
return Promise.resolve();
}
measureTiming(action, label);
// Internal-only events are used for measuring time between events,
// but aren't submitted to GA.
if (action === "internal") {
return Promise.resolve();
}
if (typeof label === "object" && (!options)) {
options = label;
label = undefined;
}
options = options || {};
// Don't send events if in private browsing.
if (options.incognito) {
return Promise.resolve();
}
// Don't include in event data.
delete options.incognito;
const di = deviceInfo();
options.applicationName = di.appName;
options.applicationVersion = di.addonVersion;
const abTests = auth.getAbTests();
for (const [gaField, value] of Object.entries(abTests)) {
options[gaField] = value;
}
if (!shouldSendEvents()) {
// We don't want to save or send the events anymore
return Promise.resolve();
}
pendingEvents.push({
eventTime: Date.now(),
event: eventCategory,
action,
label,
options,
});
if (!eventsTimeoutHandle) {
eventsTimeoutHandle = setTimeout(() => {
eventsTimeoutHandle = null;
flushEvents();
}, EVENT_BATCH_DURATION);
}
// This function used to return a Promise that was not used at any of the
// call sites; doing this simply maintains that interface.
return Promise.resolve();
};
exports.incrementCount = function(scalar) {
const allowedScalars = ["download", "upload", "copy"];
if (!allowedScalars.includes(scalar)) {
const err = `incrementCount passed an unrecognized scalar ${scalar}`;
log.warn(err);
return Promise.resolve();
}
return browser.telemetry.scalarAdd(`screenshots.${scalar}`, 1).catch(err => {
log.warn(`incrementCount failed with error: ${err}`);
});
};
exports.refreshTelemetryPref = function() {
return browser.telemetry.canUpload().then((result) => {
telemetryPrefKnown = true;
telemetryEnabled = result;
}, (error) => {
// If there's an error reading the pref, we should assume that we shouldn't send data
telemetryPrefKnown = true;
telemetryEnabled = false;
throw error;
});
};
exports.isTelemetryEnabled = function() {
catcher.watchPromise(exports.refreshTelemetryPref());
return telemetryEnabled;
};
const timingData = new Map();
// Configuration for filtering the sendEvent stream on start/end events.
// When start or end events occur, the time is recorded.
// When end events occur, the elapsed time is calculated and submitted
// via `sendEvent`, where action = "perf-response-time", label = name of rule,
// and cd1 value is the elapsed time in milliseconds.
// If a cancel event happens between the start and end events, the start time
// is deleted.
const rules = [{
name: "page-action",
start: { action: "start-shot", label: "toolbar-button" },
end: { action: "internal", label: "unhide-preselection-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
{ action: "internal", label: "unhide-onboarding-frame" },
],
}, {
name: "context-menu",
start: { action: "start-shot", label: "context-menu" },
end: { action: "internal", label: "unhide-preselection-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
{ action: "internal", label: "unhide-onboarding-frame" },
],
}, {
name: "page-action-onboarding",
start: { action: "start-shot", label: "toolbar-button" },
end: { action: "internal", label: "unhide-onboarding-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
{ action: "internal", label: "unhide-preselection-frame" },
],
}, {
name: "context-menu-onboarding",
start: { action: "start-shot", label: "context-menu" },
end: { action: "internal", label: "unhide-onboarding-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
{ action: "internal", label: "unhide-preselection-frame" },
],
}, {
name: "capture-full-page",
start: { action: "capture-full-page" },
end: { action: "internal", label: "unhide-preview-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "capture-visible",
start: { action: "capture-visible" },
end: { action: "internal", label: "unhide-preview-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "make-selection",
start: { action: "make-selection" },
end: { action: "internal", label: "unhide-selection-frame" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "save-shot",
start: { action: "save-shot" },
end: { action: "internal", label: "open-shot-tab" },
cancel: [{ action: "cancel-shot" }, { action: "upload-failed" }],
}, {
name: "save-visible",
start: { action: "save-visible" },
end: { action: "internal", label: "open-shot-tab" },
cancel: [{ action: "cancel-shot" }, { action: "upload-failed" }],
}, {
name: "save-full-page",
start: { action: "save-full-page" },
end: { action: "internal", label: "open-shot-tab" },
cancel: [{ action: "cancel-shot" }, { action: "upload-failed" }],
}, {
name: "save-full-page-truncated",
start: { action: "save-full-page-truncated" },
end: { action: "internal", label: "open-shot-tab" },
cancel: [{ action: "cancel-shot" }, { action: "upload-failed" }],
}, {
name: "download-shot",
start: { action: "download-shot" },
end: { action: "internal", label: "deactivate" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "download-full-page",
start: { action: "download-full-page" },
end: { action: "internal", label: "deactivate" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "download-full-page-truncated",
start: { action: "download-full-page-truncated" },
end: { action: "internal", label: "deactivate" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}, {
name: "download-visible",
start: { action: "download-visible" },
end: { action: "internal", label: "deactivate" },
cancel: [
{ action: "cancel-shot" },
{ action: "internal", label: "document-hidden" },
],
}];
// Match a filter (action and optional label) against an action and label.
function match(filter, action, label) {
return filter.label ?
filter.action === action && filter.label === label :
filter.action === action;
}
function anyMatches(filters, action, label) {
return filters.some(filter => match(filter, action, label));
}
function measureTiming(action, label) {
rules.forEach(r => {
if (anyMatches(r.cancel, action, label)) {
delete timingData[r.name];
} else if (match(r.start, action, label)) {
timingData[r.name] = Math.round(performance.now());
} else if (timingData[r.name] && match(r.end, action, label)) {
const endTime = Math.round(performance.now());
const elapsed = endTime - timingData[r.name];
sendTiming("perf-response-time", r.name, elapsed);
delete timingData[r.name];
}
});
}
function fetchWatcher(request) {
request.then(response => {
if (response.status === 410 || response.status === 404) { // Gone
hasReturnedGone = true;
pendingEvents = [];
pendingTimings = [];
}
if (!response.ok) {
log.debug(`Error code in event response: ${response.status} ${response.statusText}`);
}
}).catch(error => {
serverFailedResponses--;
if (serverFailedResponses <= 0) {
log.info(`Server is not responding, no more events will be sent`);
pendingEvents = [];
pendingTimings = [];
}
log.debug(`Error event in response: ${error}`);
});
}
async function init() {
const result = await browser.storage.local.get(["myGaSegment"]);
if (!result.myGaSegment) {
myGaSegment = Math.random();
await browser.storage.local.set({myGaSegment});
} else {
myGaSegment = result.myGaSegment;
}
}
init();
return exports;
})();
|