Skip to content

Commit a6c72b2

Browse files
mmustafa-tseMohammed Mustafa
andauthored
feat: Calculate mediaTimeSpent based on current time (#709)
Co-authored-by: Mohammed Mustafa <[email protected]>
1 parent 12e9c66 commit a6c72b2

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/session.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export class MediaSession {
9696
private mediaSessionStartTimestamp = Date.now(); //Timestamp created on logMediaSessionStart event
9797
private mediaSessionEndTimestamp = Date.now(); //Timestamp updated when any event is loggged
9898
private mediaTimeSpent() {
99-
return this.mediaSessionEndTimestamp - this.mediaSessionStartTimestamp;
99+
return Date.now() - this.mediaSessionStartTimestamp;
100100
}
101101
private currentPlaybackStartTimestamp?: number; //Timestamp for beginning of current playback
102102
private storedPlaybackTime = 0; //On Pause calculate playback time and clear currentPlaybackTime

test/session.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,4 +1463,29 @@ describe('MediaSession', () => {
14631463
});
14641464
});
14651465
});
1466+
1467+
describe('Media Session Attributes', () => {
1468+
it('should get mediaTimeSpent based on current time', async () => {
1469+
const options = {
1470+
customAttributes: {
1471+
content_rating: 'epic',
1472+
},
1473+
currentPlayheadPosition: 0,
1474+
};
1475+
1476+
// logPlay is triggered to start media content time tracking.
1477+
mpMedia.logPlay(options);
1478+
// 100ms delay added to account for the time spent on media content.
1479+
await new Promise(f => setTimeout(f, 100));
1480+
mpMedia.logPause(options);
1481+
// Another 100ms delay added after logPause is triggered to account for time spent on media session (total = +200ms).
1482+
await new Promise(f => setTimeout(f, 100));
1483+
1484+
const mpMediaTimeSpent = mpMedia['mediaTimeSpent']();
1485+
// the mediaTimeSpent varies in value each test run by a millisecond or two (i,e value is could be 200ms, 201ms, 202ms)
1486+
// and we can't determine the exact value, hence the greaterThanOrEqual and lessThanOrEqual tests.
1487+
expect(mpMediaTimeSpent).to.greaterThanOrEqual(200);
1488+
expect(mpMediaTimeSpent).to.lessThanOrEqual(300);
1489+
});
1490+
});
14661491
});

0 commit comments

Comments
 (0)