Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding AngularFireAnalytics, AngularFireRemoteConfig, and refactoring DI Tokens #2187

Merged
merged 41 commits into from
Jan 7, 2020
Merged
Changes from 5 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
e5be927
Firebase v7, analytics and remote-config
jamesdaniels Oct 2, 2019
1cf961b
Cleaning up the DI tokens
jamesdaniels Oct 2, 2019
f5f67ad
Cleaning things up
jamesdaniels Oct 4, 2019
73413e8
DI and jazz
jamesdaniels Oct 4, 2019
dd0efb1
Bumping the tests
jamesdaniels Nov 8, 2019
dffca53
Adding to the root-spec
jamesdaniels Nov 9, 2019
9731e3c
Spelling is good.
jamesdaniels Nov 9, 2019
7308f9c
Merge branch 'master' into firebase-v7
jamesdaniels Nov 9, 2019
dcdf8bc
Have to include UMDs in the karma.conf
jamesdaniels Nov 9, 2019
6f71d46
Just importing performance is destablizing the app
jamesdaniels Nov 11, 2019
6638b9d
Merge branch 'master' into firebase-v7
jamesdaniels Nov 12, 2019
d7d52c8
Adding the zone arg to the app factory
jamesdaniels Nov 12, 2019
eb4bc00
First pass on the new RC API and the start of the AngularFireLazy effort
jamesdaniels Nov 13, 2019
89344cc
Update src/remote-config/tsconfig-test.json
jamesdaniels Nov 14, 2019
075afe6
Reworking things a bit
jamesdaniels Nov 20, 2019
b8b351a
Router as optional, drop this/private from screen tracking
jamesdaniels Nov 20, 2019
1e39052
Minor changes to RC
jamesdaniels Nov 20, 2019
768c21b
It's firebase_screen_class
jamesdaniels Nov 21, 2019
60c0cad
Reworking analytics
jamesdaniels Nov 22, 2019
9b2e920
current!
jamesdaniels Nov 22, 2019
916e069
Use _loadedConfig if available and scope screen_id on outlet
jamesdaniels Nov 22, 2019
5955925
Fixing the types to handle older Firebase SDKs
jamesdaniels Nov 22, 2019
659165e
SEMVER notes on the DI tokens
jamesdaniels Nov 22, 2019
62d90b9
Starting on the docs
jamesdaniels Nov 22, 2019
1a43ad1
Merge branch 'firebase-v7' of github.com:angular/angularfire2 into fi…
jamesdaniels Nov 22, 2019
67e1b55
Monitoring...
jamesdaniels Dec 9, 2019
91778ff
More work on analytics
jamesdaniels Dec 11, 2019
460170c
more expirimentation
jamesdaniels Dec 12, 2019
3c1ad1f
Flushing out RC more and fixing SSR issues
jamesdaniels Dec 14, 2019
e2d83c8
New RC API
jamesdaniels Dec 16, 2019
4601932
Mapping to objects and templates, budget pipe
jamesdaniels Dec 17, 2019
7fe92ed
More strict types
jamesdaniels Dec 17, 2019
d47dc3f
Fix proxy in Node, get component name for analytics in both JIT and AOT
jamesdaniels Dec 21, 2019
05c840b
Cleaning things up, beyond docs ready for release
jamesdaniels Jan 7, 2020
b46b382
Docs and cleanup
jamesdaniels Jan 7, 2020
ff65db8
Fixing analytics spec
jamesdaniels Jan 7, 2020
baaeccf
Adding more API to the docs
jamesdaniels Jan 7, 2020
04a3bb1
Further simplifications to the DI tokens
jamesdaniels Jan 7, 2020
c37fcb7
Add Analytics and RemoteConfig to install-and-setup
jamesdaniels Jan 7, 2020
6753a67
Merge branch 'master' into firebase-v7
jamesdaniels Jan 7, 2020
6f114c6
Our RC Value implements a Partial, so minors dont break
jamesdaniels Jan 7, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 87 additions & 44 deletions src/analytics/analytics.service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import { Injectable, Inject, Optional, NgZone, OnDestroy, InjectionToken } from '@angular/core';
import { Subscription, from, Observable, empty } from 'rxjs';
import { filter, withLatestFrom, switchMap, map, tap } from 'rxjs/operators';
import { Subscription, from, Observable, empty, of } from 'rxjs';
import { filter, withLatestFrom, switchMap, map, tap, pairwise, startWith, groupBy, mergeMap } from 'rxjs/operators';
import { Router, NavigationEnd, ActivationEnd } from '@angular/router';
import { runOutsideAngular, _lazySDKProxy, _firebaseAppFactory } from '@angular/fire';
import { AngularFireAnalytics } from './analytics';
import { User } from 'firebase/app';

export const AUTOMATICALLY_SET_CURRENT_SCREEN = new InjectionToken<boolean>('angularfire2.analytics.setCurrentScreen');
export const AUTOMATICALLY_LOG_SCREEN_VIEWS = new InjectionToken<boolean>('angularfire2.analytics.logScreenViews');
export const APP_VERSION = new InjectionToken<string>('angularfire2.analytics.appVersion');
export const APP_NAME = new InjectionToken<string>('angularfire2.analytics.appName');

const DEFAULT_APP_VERSION = '?';
const DEFAULT_APP_NAME = 'Angular App';

type AngularFireAnalyticsEventParams = {
app_name: string;
firebase_screen_class: string | undefined;
firebase_screen: string;
app_version: string;
screen_name: string;
outlet: string;
url: string;
};

@Injectable({
providedIn: 'root'
})
Expand All @@ -24,49 +32,66 @@ export class ScreenTrackingService implements OnDestroy {
constructor(
analytics: AngularFireAnalytics,
@Optional() router:Router,
@Optional() @Inject(AUTOMATICALLY_SET_CURRENT_SCREEN) automaticallySetCurrentScreen:boolean|null,
@Optional() @Inject(AUTOMATICALLY_LOG_SCREEN_VIEWS) automaticallyLogScreenViews:boolean|null,
@Optional() @Inject(APP_VERSION) providedAppVersion:string|null,
@Optional() @Inject(APP_NAME) providedAppName:string|null,
zone: NgZone
) {
if (!router) {
// TODO warning about Router
} else if (automaticallySetCurrentScreen !== false || automaticallyLogScreenViews !== false) {
const app_name = providedAppName || DEFAULT_APP_NAME;
const app_version = providedAppVersion || DEFAULT_APP_VERSION;
const activationEndEvents = router.events.pipe(filter<ActivationEnd>(e => e instanceof ActivationEnd));
const navigationEndEvents = router.events.pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd));
this.disposable = navigationEndEvents.pipe(
withLatestFrom(activationEndEvents),
switchMap(([navigationEnd, activationEnd]) => {
const url = navigationEnd.url;
const screen_name = activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.path || url;
const outlet = activationEnd.snapshot.outlet;
const component = activationEnd.snapshot.component;
const ret = new Array<Promise<void>>();
if (automaticallyLogScreenViews !== false) {
if (component) {
const screen_class = component.hasOwnProperty('name') && (component as any).name || component.toString();
ret.push(analytics.logEvent("screen_view", { app_name, screen_class, app_version, screen_name, outlet, url }));
} else if (activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.loadChildren) {
ret.push((activationEnd.snapshot.routeConfig.loadChildren as any)().then((child:any) => {
const screen_class = child.name;
console.log("logEvent", "screen_view", { app_name, screen_class, app_version, screen_name, outlet, url });
return analytics.logEvent("screen_view", { app_name, screen_class, app_version, screen_name, outlet, url });
}));
} else {
ret.push(analytics.logEvent("screen_view", { app_name, app_version, screen_name, outlet, url }));
}
}
if (automaticallySetCurrentScreen !== false) {
ret.push(analytics.setCurrentScreen(screen_name || url, { global: outlet == "primary" }));
}
return Promise.all(ret);
}),
runOutsideAngular(zone)
).subscribe();
}
if (!router) { return this }
const app_name = providedAppName || DEFAULT_APP_NAME;
const app_version = providedAppVersion || DEFAULT_APP_VERSION;
const activationEndEvents = router.events.pipe(filter<ActivationEnd>(e => e instanceof ActivationEnd));
const navigationEndEvents = router.events.pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd));
this.disposable = navigationEndEvents.pipe(
withLatestFrom(activationEndEvents),
switchMap(([navigationEnd, activationEnd]) => {
const url = navigationEnd.url;
const screen_name = activationEnd.snapshot.routeConfig && activationEnd.snapshot.routeConfig.path || url;
const params: AngularFireAnalyticsEventParams = {
app_name, app_version, screen_name, url,
firebase_screen_class: undefined,
firebase_screen: screen_name,
outlet: activationEnd.snapshot.outlet
};
const component = activationEnd.snapshot.component;
const routeConfig = activationEnd.snapshot.routeConfig;
const loadedConfig = routeConfig && (routeConfig as any)._loadedConfig;
const loadChildren = routeConfig && routeConfig.loadChildren;
if (component) {
return of({...params, firebase_screen_class: nameOrToString(component) });
} else if (loadedConfig && loadedConfig.module && loadedConfig.module._moduleType) {
return of({...params, firebase_screen_class: nameOrToString(loadedConfig.module._moduleType)});
} else if (typeof loadChildren === "string") {
// TODO is this an older lazy loading style parse
return of({...params, firebase_screen_class: loadChildren });
} else if (loadChildren) {
// TODO look into the other return types here
return from(loadChildren() as Promise<any>).pipe(map(child => ({...params, firebase_screen_class: nameOrToString(child) })));
} else {
// TODO figure out what forms of router events I might be missing
return of(params);
}
}),
tap(params => {
// TODO perhaps I can be smarter about this, bubble events up to the nearest outlet?
if (params.outlet == "primary") {
// TODO do I need to add gtag config for firebase_screen, firebase_screen_class, firebase_screen_id?
// also shouldn't these be computed in the setCurrentScreen function? prior too?
// do we want to be logging screen name or class?
analytics.setCurrentScreen(params.screen_name, { global: true })
}
}),
map(params => ({ firebase_screen_id: nextScreenId(params), ...params})),
Copy link
Member Author

@jamesdaniels jamesdaniels Nov 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Feiyang1 @hsubox76 what would be the interest level in our adding firebase_* parameter handling (firebase_screen_id, firebase_previous_id, firebase_screen_class, etc.) into the JS SDK?

I know it breaks the separation of concerns a bit but was non-trivial to get working correctly. It's needed to be able to track user flows in the Firebase Console and BigQuery. The iOS and Android SDKs do this automatically for the developer and their behavior is what I modeled here for Angular. I'll be doing the same treatment for React and Ember routers. I suspect other 3p SDKs will been keen on implementing too.

At the very least we should add information on how to implement in the Firebase docs and add types. FYI @gkaldev @schandel @davideast

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a lot of Angular experience so maybe wait for @Feiyang1 to take a look but a lot of this looks very Angular-router-specific. What part/params would be passed to the JS SDK to work with? Do we derive screen_class and previous_id from something or would that be passed in?

Copy link
Member Author

@jamesdaniels jamesdaniels Nov 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hooking into the router will be framework specific of course, my thought would be to add a logScreenView(this, name: string, additionalParams?: {}) function which would do all the firebase specific event param computation: firebase_screen_id, firebase_previous_screen, firebase_screen_class, firebase_screen, firebase_previous_class, firebase_previous_screen, and firebase_previous_id. They're are all undocumented and having to do these on my own to get the most out of Firebase was unexpected.

For instance firebase_screen_id was challenging to understand, I couldn't find any resources externally and had to "cheat" and look it up on g3 to find out it's a random INT64 (rather than a hashCode of some kind). I'm not 100% confident I got it right either, hence looping in more DelRel folk.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, if these are standard for other Firebase platforms and we can come up with a sort of general interface I think it would make sense for us to bake some of this handling into the JS SDK. Let us know if you want to set up a meeting to talk about what we can do with these and pass along your hard-earned research about these params, maybe after you get some more input from other devrels confirming how they work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, you are asking the JS SDK to keep the state of the previous screen_view parameters and attach them to the next screen_view request?
Can you share a pointer to how iOS SDK and Android SDK handles it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, basically I'm thinking all the undocumented firebase_* attributes that make the console work should be something we take care of.

I'll send over email now that I'm back from the holiday and we can hop on GVC if additional clarity is needed. That probably would've been a better place for the discussion anyway. 😛

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My Firebase console is still not showing the information I expect, meaning I did not get this 100% correct yet.

groupBy(params => params.outlet),
mergeMap(group => group.pipe(startWith(undefined), pairwise())),
map(([prior, current]) => prior ? {
firebase_previous_class: prior.firebase_screen_class,
firebase_previous_screen: prior.firebase_screen,
firebase_previous_id: prior.firebase_screen_id,
...current!
} : current!),
tap(params => analytics.logEvent('screen_view', params)),
runOutsideAngular(zone)
).subscribe();
}

ngOnDestroy() {
Expand Down Expand Up @@ -99,4 +124,22 @@ export class UserTrackingService implements OnDestroy {
ngOnDestroy() {
if (this.disposable) { this.disposable.unsubscribe(); }
}
}
}

// firebase_screen_id is an INT64 but use INT32 cause javascript
const randomInt32 = () => Math.floor(Math.random() * (2**32 - 1)) - 2**31;

const currentScreenIds: {[key:string]: number} = {};

const nextScreenId = (params:AngularFireAnalyticsEventParams) => {
const scope = params.outlet;
if (currentScreenIds.hasOwnProperty(scope)) {
return ++currentScreenIds[scope];
} else {
const ret = randomInt32();
currentScreenIds[scope] = ret;
return ret;
}
}

const nameOrToString = (it:any): string => it.name || it.toString();