GleanMetricsService.kt 39.1 KB
Newer Older
1
2
3
/* 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/. */
4

5
6
7
package org.mozilla.fenix.components.metrics

import android.content.Context
8
9
10
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.feature.search.ext.legacy
import mozilla.components.feature.search.ext.waitForSelectedOrDefaultSearchEngine
11
import mozilla.components.service.fxa.manager.SyncEnginesStorage
12
import mozilla.components.service.glean.Glean
13
import mozilla.components.service.glean.private.NoExtraKeys
14
import mozilla.components.support.base.log.logger.Logger
15
import org.mozilla.fenix.Config
16
import org.mozilla.fenix.GleanMetrics.AboutPage
17
import org.mozilla.fenix.GleanMetrics.Addons
18
import org.mozilla.fenix.GleanMetrics.AppTheme
19
import org.mozilla.fenix.GleanMetrics.Autoplay
Colin Lee's avatar
Colin Lee committed
20
import org.mozilla.fenix.GleanMetrics.BookmarksManagement
21
import org.mozilla.fenix.GleanMetrics.BrowserSearch
22
import org.mozilla.fenix.GleanMetrics.Collections
Colin Lee's avatar
Colin Lee committed
23
import org.mozilla.fenix.GleanMetrics.ContextMenu
24
import org.mozilla.fenix.GleanMetrics.ContextualHintTrackingProtection
25
import org.mozilla.fenix.GleanMetrics.ContextualMenu
26
import org.mozilla.fenix.GleanMetrics.CrashReporter
Colin Lee's avatar
Colin Lee committed
27
import org.mozilla.fenix.GleanMetrics.CustomTab
28
import org.mozilla.fenix.GleanMetrics.DownloadNotification
29
import org.mozilla.fenix.GleanMetrics.DownloadsMisc
30
import org.mozilla.fenix.GleanMetrics.DownloadsManagement
31
import org.mozilla.fenix.GleanMetrics.ErrorPage
32
33
import org.mozilla.fenix.GleanMetrics.Events
import org.mozilla.fenix.GleanMetrics.FindInPage
34
import org.mozilla.fenix.GleanMetrics.History
35
import org.mozilla.fenix.GleanMetrics.LoginDialog
36
import org.mozilla.fenix.GleanMetrics.Logins
ekager's avatar
ekager committed
37
import org.mozilla.fenix.GleanMetrics.MasterPassword
38
import org.mozilla.fenix.GleanMetrics.MediaNotification
39
import org.mozilla.fenix.GleanMetrics.MediaState
40
import org.mozilla.fenix.GleanMetrics.Metrics
41
import org.mozilla.fenix.GleanMetrics.Onboarding
42
import org.mozilla.fenix.GleanMetrics.Pings
ekager's avatar
ekager committed
43
import org.mozilla.fenix.GleanMetrics.Pocket
44
import org.mozilla.fenix.GleanMetrics.Preferences
45
import org.mozilla.fenix.GleanMetrics.PrivateBrowsingMode
46
import org.mozilla.fenix.GleanMetrics.PrivateBrowsingShortcut
47
import org.mozilla.fenix.GleanMetrics.ProgressiveWebApp
48
import org.mozilla.fenix.GleanMetrics.ReaderMode
49
import org.mozilla.fenix.GleanMetrics.SearchDefaultEngine
50
import org.mozilla.fenix.GleanMetrics.SearchShortcuts
51
import org.mozilla.fenix.GleanMetrics.SearchSuggestions
52
import org.mozilla.fenix.GleanMetrics.SearchWidget
53
54
import org.mozilla.fenix.GleanMetrics.SyncAccount
import org.mozilla.fenix.GleanMetrics.SyncAuth
55
import org.mozilla.fenix.GleanMetrics.Tab
56
import org.mozilla.fenix.GleanMetrics.Tabs
57
import org.mozilla.fenix.GleanMetrics.TabsTray
58
import org.mozilla.fenix.GleanMetrics.TabsTrayCfr
59
import org.mozilla.fenix.GleanMetrics.Tip
60
import org.mozilla.fenix.GleanMetrics.ToolbarSettings
61
import org.mozilla.fenix.GleanMetrics.TopSites
62
import org.mozilla.fenix.GleanMetrics.TrackingProtection
63
import org.mozilla.fenix.GleanMetrics.UserSpecifiedSearchEngines
64
import org.mozilla.fenix.GleanMetrics.VoiceSearch
65
import org.mozilla.fenix.components.toolbar.ToolbarPosition
66
import org.mozilla.fenix.ext.components
67
import org.mozilla.fenix.ext.settings
68
import org.mozilla.fenix.utils.BrowsersCache
69

Jeff Boek's avatar
Jeff Boek committed
70
private class EventWrapper<T : Enum<T>>(
71
    private val recorder: ((Map<T, String>?) -> Unit),
72
    private val keyMapper: ((String) -> T)? = null
Jeff Boek's avatar
Jeff Boek committed
73
) {
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

    /**
     * Converts snake_case string to camelCase.
     */
    private fun String.asCamelCase(): String {
        val parts = split("_")
        val builder = StringBuilder()

        for ((index, part) in parts.withIndex()) {
            if (index == 0) {
                builder.append(part)
            } else {
                builder.append(part[0].toUpperCase())
                builder.append(part.substring(1))
            }
89
90
        }

91
92
93
        return builder.toString()
    }

Jeff Boek's avatar
Jeff Boek committed
94
95
    fun track(event: Event) {
        val extras = if (keyMapper != null) {
96
97
98
            event.extras?.mapKeys { (key) ->
                keyMapper.invoke(key.toString().asCamelCase())
            }
Jeff Boek's avatar
Jeff Boek committed
99
100
101
102
        } else {
            null
        }

103
        this.recorder(extras)
Jeff Boek's avatar
Jeff Boek committed
104
105
106
    }
}

107
private val Event.wrapper: EventWrapper<*>?
108
    get() = when (this) {
109
110
111
112
        is Event.OpenedApp -> EventWrapper(
            { Events.appOpened.record(it) },
            { Events.appOpenedKeys.valueOf(it) }
        )
113
        is Event.AppReceivedIntent -> EventWrapper(
114
115
116
            { Events.appReceivedIntent.record(it) },
            { Events.appReceivedIntentKeys.valueOf(it) }
        )
117
        is Event.AppAllStartup -> EventWrapper(
118
119
120
            { Events.appOpenedAllStartup.record(it) },
            { Events.appOpenedAllStartupKeys.valueOf(it) }
        )
121
122
123
124
125
126
127
128
129
        is Event.SearchBarTapped -> EventWrapper(
            { Events.searchBarTapped.record(it) },
            { Events.searchBarTappedKeys.valueOf(it) }
        )
        is Event.EnteredUrl -> EventWrapper(
            { Events.enteredUrl.record(it) },
            { Events.enteredUrlKeys.valueOf(it) }
        )
        is Event.PerformedSearch -> EventWrapper(
Jeff Boek's avatar
Jeff Boek committed
130
131
132
133
            {
                Metrics.searchCount[this.eventSource.countLabel].add(1)
                Events.performedSearch.record(it)
            },
134
135
            { Events.performedSearchKeys.valueOf(it) }
        )
136
137
138
139
140
141
142
143
144
145
        is Event.SearchWithAds -> EventWrapper<NoExtraKeys>(
            {
                BrowserSearch.withAds[label].add(1)
            }
        )
        is Event.SearchAdClicked -> EventWrapper<NoExtraKeys>(
            {
                BrowserSearch.adClicks[label].add(1)
            }
        )
146
147
148
149
150
        is Event.SearchInContent -> EventWrapper<NoExtraKeys>(
            {
                BrowserSearch.inContent[label].add(1)
            }
        )
151
152
153
154
        is Event.SearchShortcutSelected -> EventWrapper(
            { SearchShortcuts.selected.record(it) },
            { SearchShortcuts.selectedKeys.valueOf(it) }
        )
155
156
157
158
159
160
161
162
163
164
165
166
        is Event.LoginDialogPromptDisplayed -> EventWrapper<NoExtraKeys>(
            { LoginDialog.displayed.record(it) }
        )
        is Event.LoginDialogPromptCancelled -> EventWrapper<NoExtraKeys>(
            { LoginDialog.cancelled.record(it) }
        )
        is Event.LoginDialogPromptSave -> EventWrapper<NoExtraKeys>(
            { LoginDialog.saved.record(it) }
        )
        is Event.LoginDialogPromptNeverSave -> EventWrapper<NoExtraKeys>(
            { LoginDialog.neverSave.record(it) }
        )
167
168
169
170
171
172
173
174
175
        is Event.FindInPageOpened -> EventWrapper<NoExtraKeys>(
            { FindInPage.opened.record(it) }
        )
        is Event.FindInPageClosed -> EventWrapper<NoExtraKeys>(
            { FindInPage.closed.record(it) }
        )
        is Event.FindInPageSearchCommitted -> EventWrapper<NoExtraKeys>(
            { FindInPage.searchedPage.record(it) }
        )
176
177
178
179
        is Event.ContextMenuItemTapped -> EventWrapper(
            { ContextMenu.itemTapped.record(it) },
            { ContextMenu.itemTappedKeys.valueOf(it) }
        )
180
        is Event.CrashReporterOpened -> EventWrapper<NoExtraKeys>(
181
            { CrashReporter.opened.record(it) }
182
183
        )
        is Event.CrashReporterClosed -> EventWrapper(
184
            { CrashReporter.closed.record(it) },
185
186
            { CrashReporter.closedKeys.valueOf(it) }
        )
187
        is Event.BrowserMenuItemTapped -> EventWrapper(
188
            { Events.browserMenuAction.record(it) },
189
190
            { Events.browserMenuActionKeys.valueOf(it) }
        )
Colin Lee's avatar
Colin Lee committed
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
        is Event.OpenedBookmarkInNewTab -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.openInNewTab.record(it) }
        )
        is Event.OpenedBookmarksInNewTabs -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.openInNewTabs.record(it) }
        )
        is Event.OpenedBookmarkInPrivateTab -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.openInPrivateTab.record(it) }
        )
        is Event.OpenedBookmarksInPrivateTabs -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.openInPrivateTabs.record(it) }
        )
        is Event.EditedBookmark -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.edited.record(it) }
        )
        is Event.MovedBookmark -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.moved.record(it) }
        )
        is Event.RemoveBookmark -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.removed.record(it) }
        )
        is Event.RemoveBookmarks -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.multiRemoved.record(it) }
        )
        is Event.ShareBookmark -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.shared.record(it) }
        )
        is Event.CopyBookmark -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.copied.record(it) }
        )
        is Event.AddBookmarkFolder -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.folderAdd.record(it) }
        )
224
225
226
        is Event.RemoveBookmarkFolder -> EventWrapper<NoExtraKeys>(
            { BookmarksManagement.folderRemove.record(it) }
        )
227
228
229
230
231
232
233
234
235
        is Event.CustomTabsMenuOpened -> EventWrapper<NoExtraKeys>(
            { CustomTab.menu.record(it) }
        )
        is Event.CustomTabsActionTapped -> EventWrapper<NoExtraKeys>(
            { CustomTab.actionButton.record(it) }
        )
        is Event.CustomTabsClosed -> EventWrapper<NoExtraKeys>(
            { CustomTab.closed.record(it) }
        )
236
237
238
        is Event.UriOpened -> EventWrapper<NoExtraKeys>(
            { Events.totalUriCount.add(1) }
        )
239
        is Event.ErrorPageVisited -> EventWrapper(
240
            { ErrorPage.visitedError.record(it) },
241
242
            { ErrorPage.visitedErrorKeys.valueOf(it) }
        )
243
244
        is Event.SyncAuthOpened -> EventWrapper<NoExtraKeys>(
            { SyncAuth.opened.record(it) }
245
        )
246
247
        is Event.SyncAuthClosed -> EventWrapper<NoExtraKeys>(
            { SyncAuth.closed.record(it) }
248
        )
249
250
251
252
253
254
        is Event.SyncAuthUseEmail -> EventWrapper<NoExtraKeys>(
            { SyncAuth.useEmail.record(it) }
        )
        is Event.SyncAuthUseEmailProblem -> EventWrapper<NoExtraKeys>(
            { SyncAuth.useEmailProblem.record(it) }
        )
255
256
        is Event.SyncAuthSignIn -> EventWrapper<NoExtraKeys>(
            { SyncAuth.signIn.record(it) }
257
        )
Grisha Kruglov's avatar
Grisha Kruglov committed
258
259
260
261
262
263
264
265
266
267
268
269
        is Event.SyncAuthSignUp -> EventWrapper<NoExtraKeys>(
            { SyncAuth.signUp.record(it) }
        )
        is Event.SyncAuthPaired -> EventWrapper<NoExtraKeys>(
            { SyncAuth.paired.record(it) }
        )
        is Event.SyncAuthOtherExternal -> EventWrapper<NoExtraKeys>(
            { SyncAuth.otherExternal.record(it) }
        )
        is Event.SyncAuthRecovered -> EventWrapper<NoExtraKeys>(
            { SyncAuth.recovered.record(it) }
        )
270
271
272
        is Event.SyncAuthSignOut -> EventWrapper<NoExtraKeys>(
            { SyncAuth.signOut.record(it) }
        )
273
274
        is Event.SyncAuthScanPairing -> EventWrapper<NoExtraKeys>(
            { SyncAuth.scanPairing.record(it) }
275
        )
276
277
        is Event.SyncAccountOpened -> EventWrapper<NoExtraKeys>(
            { SyncAccount.opened.record(it) }
278
        )
279
280
281
        is Event.SyncAccountSyncNow -> EventWrapper<NoExtraKeys>(
            { SyncAccount.syncNow.record(it) }
        )
282
283
284
285
286
287
        is Event.SignInToSendTab -> EventWrapper<NoExtraKeys>(
            { SyncAccount.signInToSendTab.record(it) }
        )
        is Event.SendTab -> EventWrapper<NoExtraKeys>(
            { SyncAccount.sendTab.record(it) }
        )
288
289
290
291
        is Event.PreferenceToggled -> EventWrapper(
            { Events.preferenceToggled.record(it) },
            { Events.preferenceToggledKeys.valueOf(it) }
        )
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        is Event.HistoryOpened -> EventWrapper<NoExtraKeys>(
            { History.opened.record(it) }
        )
        is Event.HistoryItemShared -> EventWrapper<NoExtraKeys>(
            { History.shared.record(it) }
        )
        is Event.HistoryItemOpened -> EventWrapper<NoExtraKeys>(
            { History.openedItem.record(it) }
        )
        is Event.HistoryItemRemoved -> EventWrapper<NoExtraKeys>(
            { History.removed.record(it) }
        )
        is Event.HistoryAllItemsRemoved -> EventWrapper<NoExtraKeys>(
            { History.removedAll.record(it) }
        )
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        is Event.CollectionRenamed -> EventWrapper<NoExtraKeys>(
            { Collections.renamed.record(it) }
        )
        is Event.CollectionTabRestored -> EventWrapper<NoExtraKeys>(
            { Collections.tabRestored.record(it) }
        )
        is Event.CollectionAllTabsRestored -> EventWrapper<NoExtraKeys>(
            { Collections.allTabsRestored.record(it) }
        )
        is Event.CollectionTabRemoved -> EventWrapper<NoExtraKeys>(
            { Collections.tabRemoved.record(it) }
        )
        is Event.CollectionShared -> EventWrapper<NoExtraKeys>(
            { Collections.shared.record(it) }
        )
        is Event.CollectionRemoved -> EventWrapper<NoExtraKeys>(
            { Collections.removed.record(it) }
        )
        is Event.CollectionTabSelectOpened -> EventWrapper<NoExtraKeys>(
            { Collections.tabSelectOpened.record(it) }
        )
328
329
330
        is Event.ReaderModeAvailable -> EventWrapper<NoExtraKeys>(
            { ReaderMode.available.record(it) }
        )
331
332
333
        is Event.ReaderModeOpened -> EventWrapper<NoExtraKeys>(
            { ReaderMode.opened.record(it) }
        )
334
335
336
        is Event.ReaderModeClosed -> EventWrapper<NoExtraKeys>(
            { ReaderMode.closed.record(it) }
        )
337
338
339
        is Event.ReaderModeAppearanceOpened -> EventWrapper<NoExtraKeys>(
            { ReaderMode.appearance.record(it) }
        )
340
341
342
343
344
345
346
347
348
349
        is Event.CollectionTabLongPressed -> EventWrapper<NoExtraKeys>(
            { Collections.longPress.record(it) }
        )
        is Event.CollectionSaveButtonPressed -> EventWrapper(
            { Collections.saveButton.record(it) },
            { Collections.saveButtonKeys.valueOf(it) }
        )
        is Event.CollectionAddTabPressed -> EventWrapper<NoExtraKeys>(
            { Collections.addTabButton.record(it) }
        )
350
351
352
        is Event.CollectionRenamePressed -> EventWrapper<NoExtraKeys>(
            { Collections.renameButton.record(it) }
        )
353
354
355
356
357
358
359
360
        is Event.CollectionSaved -> EventWrapper(
            { Collections.saved.record(it) },
            { Collections.savedKeys.valueOf(it) }
        )
        is Event.CollectionTabsAdded -> EventWrapper(
            { Collections.tabsAdded.record(it) },
            { Collections.tabsAddedKeys.valueOf(it) }
        )
361
362
363
364
365
366
        is Event.SearchWidgetNewTabPressed -> EventWrapper<NoExtraKeys>(
            { SearchWidget.newTabButton.record(it) }
        )
        is Event.SearchWidgetVoiceSearchPressed -> EventWrapper<NoExtraKeys>(
            { SearchWidget.voiceButton.record(it) }
        )
367
368
369
370
371
372
        is Event.PrivateBrowsingSnackbarUndoTapped -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingMode.snackbarUndo.record(it) }
        )
        is Event.PrivateBrowsingNotificationTapped -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingMode.notificationTapped.record(it) }
        )
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        is Event.PrivateBrowsingCreateShortcut -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.createShortcut.record(it) }
        )
        is Event.PrivateBrowsingAddShortcutCFR -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.cfrAddShortcut.record(it) }
        )
        is Event.PrivateBrowsingCancelCFR -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.cfrCancel.record(it) }
        )
        is Event.PrivateBrowsingPinnedShortcutPrivateTab -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.pinnedShortcutPriv.record(it) }
        )
        is Event.PrivateBrowsingStaticShortcutTab -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.staticShortcutTab.record(it) }
        )
        is Event.PrivateBrowsingStaticShortcutPrivateTab -> EventWrapper<NoExtraKeys>(
            { PrivateBrowsingShortcut.staticShortcutPriv.record(it) }
        )
391
392
        is Event.WhatsNewTapped -> EventWrapper<NoExtraKeys>(
            { Events.whatsNewTapped.record(it) }
393
        )
394
395
396
397
398
399
        is Event.TabMediaPlay -> EventWrapper<NoExtraKeys>(
            { Tab.mediaPlay.record(it) }
        )
        is Event.TabMediaPause -> EventWrapper<NoExtraKeys>(
            { Tab.mediaPause.record(it) }
        )
400
401
402
403
404
405
406
407
408
        is Event.MediaPlayState -> EventWrapper<NoExtraKeys>(
            { MediaState.play.record(it) }
        )
        is Event.MediaPauseState -> EventWrapper<NoExtraKeys>(
            { MediaState.pause.record(it) }
        )
        is Event.MediaStopState -> EventWrapper<NoExtraKeys>(
            { MediaState.stop.record(it) }
        )
409
410
411
412
413
414
        is Event.MediaFullscreenState -> EventWrapper<NoExtraKeys>(
            { MediaState.fullscreen.record(it) }
        )
        is Event.MediaPictureInPictureState -> EventWrapper<NoExtraKeys>(
            { MediaState.pictureInPicture.record(it) }
        )
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        is Event.InAppNotificationDownloadOpen -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.inAppOpen.record(it) }
        )
        is Event.InAppNotificationDownloadTryAgain -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.inAppTryAgain.record(it) }
        )
        is Event.NotificationDownloadCancel -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.cancel.record(it) }
        )
        is Event.NotificationDownloadOpen -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.open.record(it) }
        )
        is Event.NotificationDownloadPause -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.pause.record(it) }
        )
        is Event.NotificationDownloadResume -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.resume.record(it) }
        )
        is Event.NotificationDownloadTryAgain -> EventWrapper<NoExtraKeys>(
            { DownloadNotification.tryAgain.record(it) }
        )
436
437
438
        is Event.DownloadAdded -> EventWrapper<NoExtraKeys>(
            { DownloadsMisc.downloadAdded.record(it) }
        )
439
440
441
442
443
444
445
446
447
        is Event.DownloadsScreenOpened -> EventWrapper<NoExtraKeys>(
            { DownloadsManagement.downloadsScreenOpened.record(it) }
        )
        is Event.DownloadsItemOpened -> EventWrapper<NoExtraKeys>(
            { DownloadsManagement.itemOpened.record(it) }
        )
        is Event.DownloadsItemDeleted -> EventWrapper<NoExtraKeys>(
            { DownloadsManagement.itemDeleted.record(it) }
        )
448
449
450
451
452
453
        is Event.NotificationMediaPlay -> EventWrapper<NoExtraKeys>(
            { MediaNotification.play.record(it) }
        )
        is Event.NotificationMediaPause -> EventWrapper<NoExtraKeys>(
            { MediaNotification.pause.record(it) }
        )
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
        is Event.TrackingProtectionTrackerList -> EventWrapper<NoExtraKeys>(
            { TrackingProtection.etpTrackerList.record(it) }
        )
        is Event.TrackingProtectionIconPressed -> EventWrapper<NoExtraKeys>(
            { TrackingProtection.etpShield.record(it) }
        )
        is Event.TrackingProtectionSettingsPanel -> EventWrapper<NoExtraKeys>(
            { TrackingProtection.panelSettings.record(it) }
        )
        is Event.TrackingProtectionSettings -> EventWrapper<NoExtraKeys>(
            { TrackingProtection.etpSettings.record(it) }
        )
        is Event.TrackingProtectionException -> EventWrapper<NoExtraKeys>(
            { TrackingProtection.exceptionAdded.record(it) }
        )
        is Event.TrackingProtectionSettingChanged -> EventWrapper(
            { TrackingProtection.etpSettingChanged.record(it) },
            { TrackingProtection.etpSettingChangedKeys.valueOf(it) }
        )
473
474
475
476
        is Event.OpenedLink -> EventWrapper(
            { Events.openedLink.record(it) },
            { Events.openedLinkKeys.valueOf(it) }
        )
477
478
479
480
481
482
483
484
485
486
487
488
        is Event.OpenLogins -> EventWrapper<NoExtraKeys>(
            { Logins.openLogins.record(it) }
        )
        is Event.OpenOneLogin -> EventWrapper<NoExtraKeys>(
            { Logins.openIndividualLogin.record(it) }
        )
        is Event.CopyLogin -> EventWrapper<NoExtraKeys>(
            { Logins.copyLogin.record(it) }
        )
        is Event.ViewLoginPassword -> EventWrapper<NoExtraKeys>(
            { Logins.viewPasswordLogin.record(it) }
        )
489
490
491
492
493
494
495
496
497
        is Event.DeleteLogin -> EventWrapper<NoExtraKeys>(
            { Logins.deleteSavedLogin.record(it) }
        )
        is Event.EditLogin -> EventWrapper<NoExtraKeys>(
            { Logins.openLoginEditor.record(it) }
        )
        is Event.EditLoginSave -> EventWrapper<NoExtraKeys>(
            { Logins.saveEditedLogin.record(it) }
        )
498
499
500
        is Event.PrivateBrowsingShowSearchSuggestions -> EventWrapper<NoExtraKeys>(
            { SearchSuggestions.enableInPrivate.record(it) }
        )
501
502
503
504
        is Event.ToolbarPositionChanged -> EventWrapper(
            { ToolbarSettings.changedPosition.record(it) },
            { ToolbarSettings.changedPositionKeys.valueOf(it) }
        )
505
506
507
508
509
510
        is Event.CustomEngineAdded -> EventWrapper<NoExtraKeys>(
            { UserSpecifiedSearchEngines.customEngineAdded.record(it) }
        )
        is Event.CustomEngineDeleted -> EventWrapper<NoExtraKeys>(
            { UserSpecifiedSearchEngines.customEngineDeleted.record(it) }
        )
511
512
513
514
        is Event.SaveLoginsSettingChanged -> EventWrapper(
            { Logins.saveLoginsSettingChanged.record(it) },
            { Logins.saveLoginsSettingChangedKeys.valueOf(it) }
        )
515
516
517
        is Event.TopSiteOpenDefault -> EventWrapper<NoExtraKeys>(
            { TopSites.openDefault.record(it) }
        )
518
519
520
        is Event.TopSiteOpenGoogle -> EventWrapper<NoExtraKeys>(
            { TopSites.openGoogleSearchAttribution.record(it) }
        )
521
522
523
524
525
526
        is Event.TopSiteOpenFrecent -> EventWrapper<NoExtraKeys>(
            { TopSites.openFrecency.record(it) }
        )
        is Event.TopSiteOpenPinned -> EventWrapper<NoExtraKeys>(
            { TopSites.openPinned.record(it) }
        )
527
528
529
530
531
532
533
534
535
        is Event.TopSiteOpenInNewTab -> EventWrapper<NoExtraKeys>(
            { TopSites.openInNewTab.record(it) }
        )
        is Event.TopSiteOpenInPrivateTab -> EventWrapper<NoExtraKeys>(
            { TopSites.openInPrivateTab.record(it) }
        )
        is Event.TopSiteRemoved -> EventWrapper<NoExtraKeys>(
            { TopSites.remove.record(it) }
        )
536
537
538
539
540
541
542
543
        is Event.TopSiteLongPress -> EventWrapper(
            { TopSites.longPress.record(it) },
            { TopSites.longPressKeys.valueOf(it) }
        )
        is Event.TopSiteSwipeCarousel -> EventWrapper(
            { TopSites.swipeCarousel.record(it) },
            { TopSites.swipeCarouselKeys.valueOf(it) }
        )
544
545
546
547
548
549
        is Event.SupportTapped -> EventWrapper<NoExtraKeys>(
            { AboutPage.supportTapped.record(it) }
        )
        is Event.PrivacyNoticeTapped -> EventWrapper<NoExtraKeys>(
            { AboutPage.privacyNoticeTapped.record(it) }
        )
ekager's avatar
ekager committed
550
551
552
553
554
555
        is Event.PocketTopSiteClicked -> EventWrapper<NoExtraKeys>(
            { Pocket.pocketTopSiteClicked.record(it) }
        )
        is Event.PocketTopSiteRemoved -> EventWrapper<NoExtraKeys>(
            { Pocket.pocketTopSiteRemoved.record(it) }
        )
556
557
558
559
        is Event.DarkThemeSelected -> EventWrapper(
            { AppTheme.darkThemeSelected.record(it) },
            { AppTheme.darkThemeSelectedKeys.valueOf(it) }
        )
560
561
562
        is Event.AddonsOpenInSettings -> EventWrapper<NoExtraKeys>(
            { Addons.openAddonsInSettings.record(it) }
        )
563
564
565
        is Event.AddonsOpenInToolbarMenu -> EventWrapper(
            { Addons.openAddonInToolbarMenu.record(it) },
            { Addons.openAddonInToolbarMenuKeys.valueOf(it) }
566
        )
567
568
569
570
571
572
573
574
575
576
577
578
        is Event.TipDisplayed -> EventWrapper(
            { Tip.displayed.record(it) },
            { Tip.displayedKeys.valueOf(it) }
        )
        is Event.TipPressed -> EventWrapper(
            { Tip.pressed.record(it) },
            { Tip.pressedKeys.valueOf(it) }
        )
        is Event.TipClosed -> EventWrapper(
            { Tip.closed.record(it) },
            { Tip.closedKeys.valueOf(it) }
        )
579
580
581
        is Event.VoiceSearchTapped -> EventWrapper<NoExtraKeys>(
            { VoiceSearch.tapped.record(it) }
        )
582
583
584
585
        is Event.TabCounterMenuItemTapped -> EventWrapper(
            { Events.tabCounterMenuAction.record(it) },
            { Events.tabCounterMenuActionKeys.valueOf(it) }
        )
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        is Event.OnboardingPrivateBrowsing -> EventWrapper<NoExtraKeys>(
            { Onboarding.prefToggledPrivateBrowsing.record(it) }
        )
        is Event.OnboardingPrivacyNotice -> EventWrapper<NoExtraKeys>(
            { Onboarding.privacyNotice.record(it) }
        )
        is Event.OnboardingManualSignIn -> EventWrapper<NoExtraKeys>(
            { Onboarding.fxaManualSignin.record(it) }
        )
        is Event.OnboardingAutoSignIn -> EventWrapper<NoExtraKeys>(
            { Onboarding.fxaAutoSignin.record(it) }
        )
        is Event.OnboardingFinish -> EventWrapper<NoExtraKeys>(
            { Onboarding.finish.record(it) }
        )
        is Event.OnboardingTrackingProtection -> EventWrapper(
            { Onboarding.prefToggledTrackingProt.record(it) },
            { Onboarding.prefToggledTrackingProtKeys.valueOf(it) }
        )
        is Event.OnboardingThemePicker -> EventWrapper(
            { Onboarding.prefToggledThemePicker.record(it) },
            { Onboarding.prefToggledThemePickerKeys.valueOf(it) }
        )
        is Event.OnboardingToolbarPosition -> EventWrapper(
            { Onboarding.prefToggledToolbarPosition.record(it) },
            { Onboarding.prefToggledToolbarPositionKeys.valueOf(it) }
        )
613

614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        is Event.ContextualHintETPDisplayed -> EventWrapper<NoExtraKeys>(
            { ContextualHintTrackingProtection.display.record(it) }
        )

        is Event.ContextualHintETPDismissed -> EventWrapper<NoExtraKeys>(
            { ContextualHintTrackingProtection.dismiss.record(it) }
        )

        is Event.ContextualHintETPInsideTap -> EventWrapper<NoExtraKeys>(
            { ContextualHintTrackingProtection.insideTap.record(it) }
        )

        is Event.ContextualHintETPOutsideTap -> EventWrapper<NoExtraKeys>(
            { ContextualHintTrackingProtection.outsideTap.record(it) }
        )

630
        is Event.TabsTrayOpened -> EventWrapper<NoExtraKeys>(
631
            { TabsTray.opened.record(it) }
632
633
        )
        is Event.TabsTrayClosed -> EventWrapper<NoExtraKeys>(
634
            { TabsTray.closed.record(it) }
635
636
        )
        is Event.OpenedExistingTab -> EventWrapper<NoExtraKeys>(
637
            { TabsTray.openedExistingTab.record(it) }
638
639
        )
        is Event.ClosedExistingTab -> EventWrapper<NoExtraKeys>(
640
            { TabsTray.closedExistingTab.record(it) }
641
642
        )
        is Event.TabsTrayPrivateModeTapped -> EventWrapper<NoExtraKeys>(
643
            { TabsTray.privateModeTapped.record(it) }
644
645
        )
        is Event.TabsTrayNormalModeTapped -> EventWrapper<NoExtraKeys>(
646
            { TabsTray.normalModeTapped.record(it) }
647
648
        )
        is Event.NewTabTapped -> EventWrapper<NoExtraKeys>(
649
            { TabsTray.newTabTapped.record(it) }
650
651
        )
        is Event.NewPrivateTabTapped -> EventWrapper<NoExtraKeys>(
652
            { TabsTray.newPrivateTabTapped.record(it) }
653
654
        )
        is Event.TabsTrayMenuOpened -> EventWrapper<NoExtraKeys>(
655
            { TabsTray.menuOpened.record(it) }
656
657
        )
        is Event.TabsTraySaveToCollectionPressed -> EventWrapper<NoExtraKeys>(
658
            { TabsTray.saveToCollection.record(it) }
659
660
        )
        is Event.TabsTrayShareAllTabsPressed -> EventWrapper<NoExtraKeys>(
661
            { TabsTray.shareAllTabs.record(it) }
662
663
        )
        is Event.TabsTrayCloseAllTabsPressed -> EventWrapper<NoExtraKeys>(
664
665
            { TabsTray.closeAllTabs.record(it) }
        )
666
667
668
669
670
671
672
        is Event.TabsTrayCfrDismissed -> EventWrapper<NoExtraKeys>(
            { TabsTrayCfr.dismiss.record(it) }
        )
        is Event.TabsTrayCfrTapped -> EventWrapper<NoExtraKeys>(
            { TabsTrayCfr.goToSettings.record(it) }
        )
        is Event.AutoPlaySettingVisited -> EventWrapper<NoExtraKeys>(
673
674
675
676
677
            { Autoplay.visitedSetting.record(it) }
        )
        is Event.AutoPlaySettingChanged -> EventWrapper(
            { Autoplay.settingChanged.record(it) },
            { Autoplay.settingChangedKeys.valueOf(it) }
678
        )
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        is Event.ProgressiveWebAppOpenFromHomescreenTap -> EventWrapper<NoExtraKeys>(
            { ProgressiveWebApp.homescreenTap.record(it) }
        )
        is Event.ProgressiveWebAppInstallAsShortcut -> EventWrapper<NoExtraKeys>(
            { ProgressiveWebApp.installTap.record(it) }
        )
        is Event.ProgressiveWebAppForeground -> EventWrapper(
            { ProgressiveWebApp.foreground.record(it) },
            { ProgressiveWebApp.foregroundKeys.valueOf(it) }
        )
        is Event.ProgressiveWebAppBackground -> EventWrapper(
            { ProgressiveWebApp.background.record(it) },
            { ProgressiveWebApp.backgroundKeys.valueOf(it) }
        )
693
694
695
        is Event.CopyUrlUsed -> EventWrapper<NoExtraKeys>(
            { Events.copyUrlTapped.record(it) }
        )
696

697
698
699
700
        is Event.SyncedTabOpened -> EventWrapper<NoExtraKeys>(
            { Events.syncedTabOpened.record(it) }
        )

701
702
703
704
        is Event.RecentlyClosedTabsOpened -> EventWrapper<NoExtraKeys>(
            { Events.recentlyClosedTabsOpened.record(it) }
        )

705
        is Event.MasterPasswordMigrationDisplayed -> EventWrapper<NoExtraKeys>(
ekager's avatar
ekager committed
706
707
            { MasterPassword.displayed.record(it) }
        )
708
        is Event.MasterPasswordMigrationSuccess -> EventWrapper<NoExtraKeys>(
ekager's avatar
ekager committed
709
710
            { MasterPassword.migration.record(it) }
        )
711
        is Event.TabSettingsOpened -> EventWrapper<NoExtraKeys>(
712
713
            { Tabs.settingOpened.record(it) }
        )
714
715
716
        Event.ContextMenuCopyTapped -> EventWrapper<NoExtraKeys>(
            { ContextualMenu.copyTapped.record(it) }
        )
717
        is Event.ContextMenuSearchTapped -> EventWrapper<NoExtraKeys>(
718
719
            { ContextualMenu.searchTapped.record(it) }
        )
720
        is Event.ContextMenuSelectAllTapped -> EventWrapper<NoExtraKeys>(
721
722
            { ContextualMenu.selectAllTapped.record(it) }
        )
723
        is Event.ContextMenuShareTapped -> EventWrapper<NoExtraKeys>(
724
725
            { ContextualMenu.shareTapped.record(it) }
        )
ekager's avatar
ekager committed
726

727
728
729
730
731
732
733
        // Don't record other events in Glean:
        is Event.AddBookmark -> null
        is Event.OpenedBookmark -> null
        is Event.OpenedAppFirstRun -> null
        is Event.InteractWithSearchURLArea -> null
        is Event.ClearedPrivateData -> null
        is Event.DismissedOnboarding -> null
734
        is Event.FennecToFenixMigrated -> null
735
        is Event.AddonInstalled -> null
736
        is Event.SearchWidgetInstalled -> null
737
        is Event.ChangedToDefaultBrowser -> null
738
        is Event.SyncAuthFromSharedReuse, Event.SyncAuthFromSharedCopy -> null
739
740
    }

741
742
class GleanMetricsService(
    private val context: Context,
743
    private val store: Lazy<BrowserStore>,
744
745
746
    private val browsersCache: BrowsersCache = BrowsersCache,
    private val mozillaProductDetector: MozillaProductDetector = MozillaProductDetector
) : MetricsService {
747
748
    override val type = MetricServiceType.Data

749
    private val logger = Logger("GleanMetricsService")
750
751
    private var initialized = false

752
    private val activationPing = ActivationPing(context)
753
    private val installationPing = FirstSessionPing(context)
754

755
    override fun start() {
756
757
        logger.debug("Enabling Glean.")
        // Initialization of Glean already happened in FenixApplication.
758
        Glean.setUploadEnabled(true)
759

760
        if (initialized) return
761
        initialized = true
762

763
764
        // The code below doesn't need to execute immediately, so we'll add them to the visual
        // completeness task queue to be run later.
765
        context.components.performance.visualCompletenessQueue.queue.runIfReadyOrQueue {
766
767
768
769
770
            // We have to initialize Glean *on* the main thread, because it registers lifecycle
            // observers. However, the activation ping must be sent *off* of the main thread,
            // because it calls Google ad APIs that must be called *off* of the main thread.
            // These two things actually happen in parallel, but that should be ok because Glean
            // can handle events being recorded before it's initialized.
771
            Glean.registerPings(Pings)
772

773
774
            // setStartupMetrics is not a fast function. It does not need to be done before we can consider
            // ourselves initialized. So, let's do it, well, later.
775
776
            setStartupMetrics()
        }
777
    }
778

779
    internal fun setStartupMetrics() {
780
        setPreferenceMetrics()
781
        with(Metrics) {
782
783
            defaultBrowser.set(browsersCache.all(context).isDefaultBrowser)
            mozillaProductDetector.getMozillaBrowserDefault(context)?.also {
784
785
                defaultMozBrowser.set(it)
            }
786
787
788
789
790
791
792
793

            distributionId.set(
                when (Config.channel.isMozillaOnline) {
                    true -> "MozillaOnline"
                    false -> "Mozilla"
                }
            )

794
            mozillaProducts.set(mozillaProductDetector.getInstalledMozillaProducts(context))
795

796
797
798
799
800
801
802
            adjustCampaign.set(context.settings().adjustCampaignId)
            adjustAdGroup.set(context.settings().adjustAdGroup)
            adjustCreative.set(context.settings().adjustCreative)
            adjustNetwork.set(context.settings().adjustNetwork)

            searchWidgetInstalled.set(context.settings().searchWidgetInstalled)

803
804
805
806
807
808
            val openTabsCount = context.settings().openTabsCount
            hasOpenTabs.set(openTabsCount > 0)
            if (openTabsCount > 0) {
                tabsOpenCount.add(openTabsCount)
            }

809
810
811
812
813
814
            val topSitesSize = context.settings().topSitesSize
            hasTopSites.set(topSitesSize > 0)
            if (topSitesSize > 0) {
                topSitesCount.add(topSitesSize)
            }

815
816
817
818
819
820
821
822
823
824
825
826
            val desktopBookmarksSize = context.settings().desktopBookmarksSize
            hasDesktopBookmarks.set(desktopBookmarksSize > 0)
            if (desktopBookmarksSize > 0) {
                desktopBookmarksCount.add(desktopBookmarksSize)
            }

            val mobileBookmarksSize = context.settings().mobileBookmarksSize
            hasMobileBookmarks.set(mobileBookmarksSize > 0)
            if (mobileBookmarksSize > 0) {
                mobileBookmarksCount.add(mobileBookmarksSize)
            }

827
            toolbarPosition.set(
828
829
830
                when (context.settings().toolbarPosition) {
                    ToolbarPosition.BOTTOM -> Event.ToolbarPositionChanged.Position.BOTTOM.name
                    ToolbarPosition.TOP -> Event.ToolbarPositionChanged.Position.TOP.name
831
832
                }
            )
833
834
835

            tabViewSetting.set(context.settings().getTabViewPingString())
            closeTabSetting.set(context.settings().getTabTimeoutPingString())
836
837
        }

838
839
840
841
842
843
844
845
        store.value.waitForSelectedOrDefaultSearchEngine { searchEngine ->
            if (searchEngine != null) {
                SearchDefaultEngine.apply {
                    code.set(searchEngine.id)
                    name.set(searchEngine.name)
                    submissionUrl.set(searchEngine.legacy().buildSearchUrl(""))
                }
            }
846

847
848
            activationPing.checkAndSend()
            installationPing.checkAndSend()
849
850
851
852
        }
    }

    private fun setPreferenceMetrics() {
853
854
855
        // We purposefully make all of our preferences the string_list format to make data analysis
        // simpler. While it makes things like booleans a bit more complicated, it means all our
        // preferences can be analyzed with the same dashboard and compared.
856
        with(Preferences) {
857
858
859
            showSearchSuggestions.set(context.settings().shouldShowSearchSuggestions.toStringList())
            remoteDebugging.set(context.settings().isRemoteDebuggingEnabled.toStringList())
            telemetry.set(context.settings().isTelemetryEnabled.toStringList())
860
            searchBrowsingHistory.set(context.settings().shouldShowHistorySuggestions.toStringList())
861
862
863
864
865
            searchBookmarks.set(context.settings().shouldShowBookmarkSuggestions.toStringList())
            showClipboardSuggestions.set(context.settings().shouldShowClipboardSuggestions.toStringList())
            showSearchShortcuts.set(context.settings().shouldShowSearchShortcuts.toStringList())
            openLinksInAPrivateTab.set(context.settings().openLinksInAPrivateTab.toStringList())
            searchSuggestionsPrivate.set(context.settings().shouldShowSearchSuggestionsInPrivate.toStringList())
866
867
            showVoiceSearch.set(context.settings().shouldShowVoiceSearch.toStringList())
            openLinksInApp.set(context.settings().openLinksInExternalApp.toStringList())
868
869
870
871
872
873
874
875
876
877
878

            val isLoggedIn =
                context.components.backgroundServices.accountManager.accountProfile() != null
            sync.set(isLoggedIn.toStringList())

            val syncedItems = SyncEnginesStorage(context).getStatus().entries.filter {
                it.value
            }.map { it.key.nativeName }

            syncItems.set(syncedItems)

879
880
881
882
883
884
885
886
887
888
889
            val toolbarPositionSelection =
                if (context.settings().shouldUseFixedTopToolbar) {
                    "fixed_top"
                } else if (context.settings().shouldUseBottomToolbar) {
                    "bottom"
                } else {
                    "top"
                }

            toolbarPosition.set(listOf(toolbarPositionSelection))

890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
            val etpSelection =
                if (!context.settings().shouldUseTrackingProtection) {
                    ""
                } else if (context.settings().useStandardTrackingProtection) {
                    "standard"
                } else if (context.settings().useStrictTrackingProtection) {
                    "strict"
                } else if (context.settings().useCustomTrackingProtection) {
                    "custom"
                } else {
                    ""
                }

            trackingProtection.set(listOf(etpSelection))

            val accessibilitySelection = mutableListOf<String>()

907
908
909
            if (context.settings().switchServiceIsEnabled) {
                accessibilitySelection.add("switch")
            }
910
911
912
913
914
915

            if (context.settings().touchExplorationIsEnabled) {
                accessibilitySelection.add("touch exploration")
            }

            accessibilityServices.set(accessibilitySelection.toList())
916

917
918
919
920
921
922
923
924
925
            val themeSelection =
                if (context.settings().shouldUseLightTheme) {
                    "light"
                } else if (context.settings().shouldUseDarkTheme) {
                    "dark"
                } else if (context.settings().shouldFollowDeviceTheme) {
                    "system"
                } else if (context.settings().shouldUseAutoBatteryTheme) {
                    "battery"
926
                } else {
927
                    ""
928
                }
929

930
            theme.set(listOf(themeSelection))
931
        }
932
933
    }

934
935
936
937
    override fun stop() {
        Glean.setUploadEnabled(false)
    }

938
    override fun track(event: Event) {
Jeff Boek's avatar
Jeff Boek committed
939
        event.wrapper?.track(event)
940
    }
941

942
    override fun shouldTrack(event: Event): Boolean {
943
        return event.wrapper != null
944
945
    }
}
946
947
948
949
950

// Helper function for making our booleans fit into the string list formatting
fun Boolean.toStringList(): List<String> {
    return listOf(this.toString())
}