Skip to content

Commit 9dfc0d9

Browse files
rmi22186alexs-mparticle
authored andcommitted
feat: Add time on site (#975)
1 parent 298b956 commit 9dfc0d9

17 files changed

+2305
-19617
lines changed

package-lock.json

Lines changed: 1661 additions & 19605 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@
8787
"@babel/preset-env": "^7.6.0",
8888
"@babel/preset-typescript": "^7.6.0",
8989
"@mparticle/data-planning-models": "^0.1.0",
90-
"@mparticle/event-models": "^1.1.8",
90+
"@mparticle/event-models": "^1.1.9",
9191
"@rollup/plugin-babel": "6.0.3",
9292
"@rollup/plugin-commonjs": "25.0.4",
9393
"@rollup/plugin-json": "^5.0.2",

src/foregroundTimeTracker.ts

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { isNumber } from './utils';
2+
import { LocalStorageVault } from './vault';
3+
4+
export default class ForegroundTimeTracker {
5+
private isTrackerActive: boolean = false;
6+
private localStorageName: string = '';
7+
private timerVault: LocalStorageVault<number>;
8+
public startTime: number = 0;
9+
public totalTime: number = 0;
10+
11+
constructor(timerKey: string) {
12+
this.localStorageName = `mp-time-${timerKey}`;
13+
this.timerVault = new LocalStorageVault<number>(this.localStorageName);
14+
this.loadTimeFromStorage();
15+
this.addHandlers();
16+
if (document.hidden === false) {
17+
this.startTracking();
18+
}
19+
}
20+
21+
private addHandlers(): void {
22+
// when user switches tabs or minimizes the window
23+
document.addEventListener('visibilitychange', () =>
24+
this.handleVisibilityChange()
25+
);
26+
// when user switches to another application
27+
window.addEventListener('blur', () => this.handleWindowBlur());
28+
// when window gains focus
29+
window.addEventListener('focus', () => this.handleWindowFocus());
30+
// this ensures that timers between tabs are in sync
31+
window.addEventListener('storage', event => this.syncAcrossTabs(event));
32+
// when user closes tab, refreshes, or navigates to another page via link
33+
window.addEventListener('beforeunload', () =>
34+
this.updateTimeInPersistence()
35+
);
36+
}
37+
38+
private handleVisibilityChange(): void {
39+
if (document.hidden) {
40+
this.stopTracking();
41+
} else {
42+
this.startTracking();
43+
}
44+
}
45+
46+
private handleWindowBlur(): void {
47+
if (this.isTrackerActive) {
48+
this.stopTracking();
49+
}
50+
}
51+
52+
private handleWindowFocus(): void {
53+
if (!this.isTrackerActive) {
54+
this.startTracking();
55+
}
56+
}
57+
58+
private syncAcrossTabs(event: StorageEvent): void {
59+
if (event.key === this.localStorageName && event.newValue !== null) {
60+
const newTime = parseFloat(event.newValue) || 0;
61+
this.totalTime = newTime;
62+
}
63+
}
64+
65+
public updateTimeInPersistence(): void {
66+
if (this.isTrackerActive) {
67+
this.timerVault.store(Math.round(this.totalTime));
68+
}
69+
}
70+
71+
private loadTimeFromStorage(): void {
72+
const storedTime = this.timerVault.retrieve();
73+
if (isNumber(storedTime) && storedTime !== null) {
74+
this.totalTime = storedTime;
75+
}
76+
}
77+
78+
79+
private startTracking(): void {
80+
if (!document.hidden) {
81+
this.startTime = Math.floor(performance.now());
82+
this.isTrackerActive = true;
83+
}
84+
}
85+
86+
private stopTracking(): void {
87+
if (this.isTrackerActive) {
88+
this.setTotalTime();
89+
this.updateTimeInPersistence();
90+
this.isTrackerActive = false;
91+
}
92+
}
93+
94+
private setTotalTime(): void {
95+
if (this.isTrackerActive) {
96+
const now = Math.floor(performance.now());
97+
this.totalTime += now - this.startTime;
98+
this.startTime = now;
99+
100+
}
101+
}
102+
103+
public getTimeInForeground(): number {
104+
this.setTotalTime();
105+
this.updateTimeInPersistence();
106+
return this.totalTime;
107+
}
108+
109+
public resetTimer(): void {
110+
this.totalTime = 0;
111+
this.updateTimeInPersistence();
112+
}
113+
}

src/mockBatchCreator.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ export default class _BatchValidator {
3030
},
3131
_resetForTests: mockFunction,
3232
_APIClient: null,
33+
_timeOnSiteTimer: {
34+
getTimeInForeground: mockFunction
35+
},
3336
MPSideloadedKit: null,
3437
_Consent: null,
3538
_Events: null,

src/mp-instance.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import { IEvents } from './events.interfaces';
4848
import { IECommerce } from './ecommerce.interfaces';
4949
import { INativeSdkHelpers } from './nativeSdkHelpers.interfaces';
5050
import { IPersistence } from './persistence.interfaces';
51+
import ForegroundTimer from './foregroundTimeTracker';
5152

5253
export interface IErrorLogMessage {
5354
message?: string;
@@ -84,6 +85,7 @@ export interface IMParticleWebSDKInstance extends MParticleWebSDK {
8485
_Store: IStore;
8586
_instanceName: string;
8687
_preInit: IPreInit;
88+
_timeOnSiteTimer: ForegroundTimer;
8789
}
8890

8991
const { Messages, HTTPCodes, FeatureFlags } = Constants;

src/sdkRuntimeModels.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ export interface SDKEvent {
7979
DataPlan?: SDKDataPlan;
8080
LaunchReferral?: string;
8181
ExpandedEventCount: number;
82+
ActiveTimeOnSite: number;
8283
}
84+
8385
export interface SDKGeoLocation {
8486
lat: number | string;
8587
lng: number | string;

src/sdkToEventsApiConverter.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,7 @@ export function convertBaseEventData(
658658
custom_attributes: sdkEvent.EventAttributes,
659659
location: convertSDKLocation(sdkEvent.Location),
660660
source_message_id: sdkEvent.SourceMessageId,
661+
active_time_on_site_ms: sdkEvent.ActiveTimeOnSite
661662
};
662663

663664
return commonEventData;

src/serverModel.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ export default function ServerModel(
345345
event.data,
346346
event.name
347347
),
348+
ActiveTimeOnSite: mpInstance._timeOnSiteTimer?.getTimeInForeground(),
348349
SourceMessageId:
349350
event.sourceMessageId ||
350351
mpInstance._Helpers.generateUniqueId(),

src/sessionManager.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,17 +132,20 @@ export default function SessionManager(
132132
});
133133

134134
mpInstance._Store.nullifySession();
135+
mpInstance._timeOnSiteTimer?.resetTimer();
135136
return;
136137
}
137138

138139
if (!mpInstance._Helpers.canLog()) {
139-
// At this moment, an AbandonedEndSession is defined when on of three things occurs:
140+
// At this moment, an AbandonedEndSession is defined when one of three things occurs:
140141
// - the SDK's store is not enabled because mParticle.setOptOut was called
141142
// - the devToken is undefined
142143
// - webviewBridgeEnabled is set to false
143144
mpInstance.Logger.verbose(
144145
Messages.InformationMessages.AbandonEndSession
145146
);
147+
mpInstance._timeOnSiteTimer?.resetTimer();
148+
146149
return;
147150
}
148151

@@ -155,6 +158,8 @@ export default function SessionManager(
155158
mpInstance.Logger.verbose(
156159
Messages.InformationMessages.NoSessionToEnd
157160
);
161+
mpInstance._timeOnSiteTimer?.resetTimer();
162+
158163
return;
159164
}
160165

@@ -180,6 +185,8 @@ export default function SessionManager(
180185
mpInstance._Store.nullifySession();
181186
}
182187
}
188+
189+
mpInstance._timeOnSiteTimer?.resetTimer();
183190
};
184191

185192
this.setSessionTimer = function(): void {

src/store.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
} from './persistence.interfaces';
3939
import { CookieSyncDates, IPixelConfiguration } from './cookieSyncManager';
4040
import { IMParticleWebSDKInstance } from './mp-instance';
41+
import ForegroundTimer from './foregroundTimeTracker';
4142

4243
// This represents the runtime configuration of the SDK AFTER
4344
// initialization has been complete and all settings and
@@ -680,6 +681,7 @@ export default function Store(
680681

681682
if (workspaceToken) {
682683
this.SDKConfig.workspaceToken = workspaceToken;
684+
mpInstance._timeOnSiteTimer = new ForegroundTimer(workspaceToken);
683685
} else {
684686
mpInstance.Logger.warning(
685687
'You should have a workspaceToken on your config object for security purposes.'

0 commit comments

Comments
 (0)