@aller/blink
Version:
A library for tracking user behaviour.
82 lines (73 loc) • 2.4 kB
text/typescript
import generalData from '../utils/general-data';
import { BlinkEvent } from '../types';
import {
calculateVideoEventTime,
VideoWatchEvent,
} from '../utils/video-event-time';
import { Page } from '../selectors/get-page-state';
export interface PrepareVideoWatchEventInput {
page: Page;
videoId: string;
playerId: string;
time?: Date;
}
export function prepareSingleVideoWatchEvent(
videoId: string,
generalData: any,
watchEvent: VideoWatchEvent,
): BlinkEvent {
const { startEvent, stopEvent, watchTime } = watchEvent;
return {
...generalData,
type: 'videoWatch',
id: videoId,
videoId,
videoPlayVolume: startEvent.volume,
videoStopVolume: stopEvent.volume,
videoPlayPosition: startEvent.position,
videoStopPosition: stopEvent.position,
videoPlayReason: startEvent.reason,
videoStopReason: stopEvent.reason,
videoPlayMuted: startEvent.muted,
videoStopMuted: stopEvent.muted,
activeTime: watchTime,
};
}
export default function prepareVideoWatchEvents(
input: PrepareVideoWatchEventInput,
): BlinkEvent[] {
const startEvents = calculateVideoEventTime(
input.page.state.video.events,
input.videoId,
input.page.state.player,
input.playerId,
input.time || new Date(),
);
const general = generalData(input.page.state);
const watchEvents = startEvents.length > 0 ? startEvents : [];
return watchEvents.map(watchEvent =>
prepareSingleVideoWatchEvent(input.videoId, general, watchEvent),
);
}
export function getAllVideoWatchEventsPrepared(page: Page, time?: Date) {
// Get all unique (videoId, playerId)-pairs from page
const allIdPairs = page.state.video.events.map(
({ videoId, playerId }: { videoId: string; playerId: string }) => ({
videoId,
playerId,
}),
);
const uniqueIdPairsObj = allIdPairs.reduce((register: any, idPair: any) => {
register[idPair.videoId + idPair.playerId] = idPair;
return register;
}, {});
const uniqueIdPairs: Array<{
videoId: string;
playerId: string;
}> = Object.keys(uniqueIdPairsObj).map(key => uniqueIdPairsObj[key]);
// Prepare all events for each (videoId, playerId)-pair, and merge them into a single list
return uniqueIdPairs.reduce((all: any, { videoId, playerId }) => {
const events = prepareVideoWatchEvents({ page, time, videoId, playerId });
return all.concat(events);
}, []);
}