diff --git a/src/session.ts b/src/session.ts index c00cad2..e852583 100644 --- a/src/session.ts +++ b/src/session.ts @@ -96,7 +96,7 @@ export class MediaSession { private mediaSessionStartTimestamp = Date.now(); //Timestamp created on logMediaSessionStart event private mediaSessionEndTimestamp = Date.now(); //Timestamp updated when any event is loggged private mediaTimeSpent() { - return this.mediaSessionEndTimestamp - this.mediaSessionStartTimestamp; + return Date.now() - this.mediaSessionStartTimestamp; } private currentPlaybackStartTimestamp?: number; //Timestamp for beginning of current playback private storedPlaybackTime = 0; //On Pause calculate playback time and clear currentPlaybackTime diff --git a/test/session.test.ts b/test/session.test.ts index c2000d5..be3431c 100644 --- a/test/session.test.ts +++ b/test/session.test.ts @@ -1463,4 +1463,29 @@ describe('MediaSession', () => { }); }); }); + + describe('Media Session Attributes', () => { + it('should get mediaTimeSpent based on current time', async () => { + const options = { + customAttributes: { + content_rating: 'epic', + }, + currentPlayheadPosition: 0, + }; + + // logPlay is triggered to start media content time tracking. + mpMedia.logPlay(options); + // 100ms delay added to account for the time spent on media content. + await new Promise(f => setTimeout(f, 100)); + mpMedia.logPause(options); + // Another 100ms delay added after logPause is triggered to account for time spent on media session (total = +200ms). + await new Promise(f => setTimeout(f, 100)); + + const mpMediaTimeSpent = mpMedia['mediaTimeSpent'](); + // the mediaTimeSpent varies in value each test run by a millisecond or two (i,e value is could be 200ms, 201ms, 202ms) + // and we can't determine the exact value, hence the greaterThanOrEqual and lessThanOrEqual tests. + expect(mpMediaTimeSpent).to.greaterThanOrEqual(200); + expect(mpMediaTimeSpent).to.lessThanOrEqual(300); + }); + }); });