UNPKG

@xnstream/player-sdk

Version:

XStream Player SDK - A powerful video player SDK for streaming content

100 lines 3.67 kB
export class WatchtimeCollector { constructor(video, streamCode, resource, edge_id, context) { this.watchStartTime = null; this.totalWatchTime = 0; this.onPlay = () => { if (this.watchStartTime === null) { this.watchStartTime = Date.now(); } }; this.onPause = () => { if (this.watchStartTime !== null) { this.totalWatchTime += Date.now() - this.watchStartTime; this.watchStartTime = null; } }; this.onVisibilityChange = () => { if (document.hidden) { this.onPause(); } else if (!this.video.paused && this.watchStartTime === null) { this.onPlay(); } }; this.context = context || {}; this.video = video; this.streamCode = streamCode; this.resource = resource; this.edge_id = edge_id; this.setupVideoEventListeners(); } setupVideoEventListeners() { this.video.addEventListener('play', this.onPlay); this.video.addEventListener('playing', this.onPlay); this.video.addEventListener('pause', this.onPause); this.video.addEventListener('seeking', this.onPause); this.video.addEventListener('seeked', this.onPlay); this.video.addEventListener('ended', this.onPause); this.video.addEventListener('waiting', this.onPause); this.video.addEventListener('stalled', this.onPause); document.addEventListener('visibilitychange', this.onVisibilityChange); } getTotalWatchTimeSeconds() { let currentWatchTime = this.totalWatchTime; if (this.watchStartTime !== null) { currentWatchTime += Date.now() - this.watchStartTime; } return Math.floor(currentWatchTime / 1000); } getContentTitle() { if (this.resource.type === 'live') { return this.resource.resource.name; } else { return this.resource.resource.title || this.streamCode; } } exportWatchtimeStats() { const event = { action: 'playback', duration: this.getTotalWatchTimeSeconds(), content_type: this.resource.type, content_id: this.streamCode, content_title: this.getContentTitle(), edge_id: this.edge_id, }; return this.context.user_id ? { ...event, user_id: this.context.user_id } : event; } flush() { const stats = this.exportWatchtimeStats(); this.reset(); if (stats.duration == 0) return []; if (!this.video.paused) this.onPlay(); return [ { name: 'watchtime', timestamp: Date.now(), data: stats, }, ]; } reset() { this.watchStartTime = null; this.totalWatchTime = 0; } destroy() { this.reset(); this.video.removeEventListener('play', this.onPlay); this.video.removeEventListener('playing', this.onPlay); this.video.removeEventListener('pause', this.onPause); this.video.removeEventListener('ended', this.onPause); this.video.removeEventListener('seeking', this.onPause); this.video.removeEventListener('seeked', this.onPlay); this.video.removeEventListener('waiting', this.onPause); this.video.removeEventListener('stalled', this.onPause); document.removeEventListener('visibilitychange', this.onVisibilityChange); } } //# sourceMappingURL=WatchtimeCollector.js.map