-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
495 lines (438 loc) · 15.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// external modules
import { createNanoEvents } from 'nanoevents';
// instance methods
import renderVideoElement from './lib/renderVideoElement';
import runVPAID from './lib/runVPAID';
import enableVASTTracking from './lib/enableVASTTracking';
import configureVPAID from './lib/configureVPAID';
import renderControls from './lib/controls';
import fullscreenToggle from './lib/fullscreenToggle';
// helper functions
import inIframe from './helpers/inIframe';
import isElement from './helpers/isElement';
import parseVAST from './helpers/parseVAST';
import secondsToReadableTime from './helpers/secondsToReadableTime';
import hasTouchScreen from './helpers/hasTouchScreen';
import createNode from './helpers/createNode';
// styles
import './styles.css';
import {
CSS_ROOT,
DATA_READY,
PLAYBACK_PROGRESS,
PLAYER_CLICK,
PRE_DESTROY,
READY,
RESIZE,
VPAID_STARTED,
ERROR,
TIMESTAMP_AD,
TIMESTAMP,
SKIP,
DEFAULT_OPTIONS as defaultOptions
} from './constants';
const JS_FILENAME = `/${CSS_ROOT}.js`;
// List of events fired by the instance instead of events the <video> tag
const internalEvents = [
DATA_READY,
PLAYBACK_PROGRESS,
PLAYER_CLICK,
PRE_DESTROY,
READY,
RESIZE,
VPAID_STARTED,
SKIP,
ERROR
];
export default class GgEzVp {
constructor(options) {
// set up the event emitter
this.emitter = createNanoEvents();
// flag than can be used from the outside to check if the instance is ready
this.ready = false;
// flag than can be used from the outside to check if the data needed to render is ready
this.dataReady = false;
this.isFullscreen = false;
this.config = this.__getConfig(options);
// Create the video container
this.playerContainer = createNode('div', this.__getCSSClass('player-container'));
// Create the video node
this.player = createNode('video', this.__getCSSClass('viewer'));
this.player.muted = true;
// set vast data default
this.VASTData = null;
this.VPAIDWrapper = null;
this.controlsRendered = false;
this.__onTouchScreen = hasTouchScreen();
// find the base url that the file was loaded from
this.__baseURL = this.__getBaseURL();
// set up any extra processes
this.__init();
}
__getConfig = options => {
const adControlOpts = options?.adControls
? {
[TIMESTAMP_AD]: options.controls?.[TIMESTAMP_AD] ?? true,
[SKIP]: options.controls?.[SKIP] ?? true,
[TIMESTAMP]: false
}
: {
[TIMESTAMP_AD]: defaultOptions.controls[TIMESTAMP_AD],
[SKIP]: defaultOptions.controls[SKIP]
};
// merge default options with user provided options
const config = {
...defaultOptions,
...options,
controls:
options.controls === false || options.controls === null
? false
: options.controls
? {
...defaultOptions.controls,
...options.controls,
...adControlOpts
}
: { ...defaultOptions.controls, ...adControlOpts }
};
config.volume = parseFloat(config.volume);
this.__prevVol = config.volume;
return config;
};
// find the base URL that the file was loaded from
// only the last URL ending in '/gg-ez-vp.js' is allowed
// Base URL is used to preload icons
// TODO: find a better way to preload them, maybe include them in build (#63)
__getBaseURL = () => {
const ggEzVpScripts = [].slice
.call(document.getElementsByTagName('script'))
.filter(a => a.src.includes(JS_FILENAME));
return ggEzVpScripts[ggEzVpScripts.length - 1].src.replace(JS_FILENAME, '');
};
// set up controls and internal listeners
// fetch VAST data if necessary
__init = () => {
try {
const { container, isVAST } = this.config;
this.container = isElement(container) ? container : document.getElementById(container);
this.__validateConfig();
this.__allowIframeFullscreen();
this.container.classList.add(this.__getCSSClass());
// listen for <video> tag resize
this.__nodeOn(window, RESIZE, this.__playerResizeListener());
// Insert the video node into its container
this.playerContainer.appendChild(this.player);
// Insert the video container into the main container
this.container.appendChild(this.playerContainer);
if (isVAST) {
return this.__runVAST();
}
// set click listener on player
this.on('click', this.__emitPlayerClick);
this.__renderVideoElement();
} catch (err) {
console.log('GgEzVp [ERR]:', err); //eslint-disable-line no-console
}
};
__allowIframeFullscreen = () => {
// This will allow fullscreen in firefox when inside iframes
// https://stackoverflow.com/a/9747340/1335287
if (window.frameElement && inIframe()) {
window.frameElement.setAttribute('allow', 'fullscreen');
}
};
__getCSSClass = (suffix = '') => CSS_ROOT + (suffix ? `--${suffix}` : '');
__validateConfig = () => {
const { src, container } = this.config;
let err = '';
// Validate that there is a source
if (!src || (typeof src !== 'string' && !Array.isArray(src))) {
err = 'video src should be a string or an array of strings';
}
if (!this.container) {
err = `container should be a DOM node or a node's id. Current container: ${container}`;
}
if (err) {
throw new Error(err);
}
};
// add pass all the required data into the video element
__mountVideoElement = renderVideoElement;
// renders the video element once the data to render it is ready
// emits: READY
__renderVideoElement = () => {
this.__mountVideoElement();
// set up controls
this.__renderControls();
// set up playback progress listener
this.on('timeupdate', this.__playbackProgressReporter);
if (this.isVPAID) {
return this.__setReadyNextTick();
}
this.once('loadedmetadata', () => {
this.emitter.emit(DATA_READY);
this.__setReadyNextTick();
});
};
__setReadyNextTick = () => {
const nextTick = requestAnimationFrame || setTimeout;
// Execute the callback in the next cycle, using requestAnimationFrame
// if available or setTimeout as a fallback
nextTick(this.__setReady);
};
__setReady = () => {
this.ready = true;
this.emitter.emit(READY);
};
__renderControls = renderControls;
__parseVAST = parseVAST;
__enableVASTTracking = enableVASTTracking;
__runVPAID = runVPAID;
__configureVPAID = configureVPAID;
// helps retrieve and parse the VAST data
// emits: DATA_READY || error
__runVAST = async () => {
try {
await this.__parseVAST(this.config.src);
} catch (err) {
if (this.VASTTracker) this.VASTTracker.error({ ERRORCODE: 901 });
this.emitter.emit(ERROR, err);
console.log('GgEzVp [ERR]:', err); //eslint-disable-line no-console
}
};
__isInternalEvent = eventName => internalEvents.includes(eventName);
// add event listeners to any node
__nodeOn = (node, eventName, ...args) => {
node.addEventListener(eventName, ...args);
// Store listener for teardown on this.destroy
const eventData = [node, eventName, ...args];
this.__nodeListeners.push(eventData);
// return the node teardown function
return () => {
this.__nodeListeners = this.__nodeListeners.filter(data => data !== eventData);
node.removeEventListener(eventName, ...args);
};
};
// list of active node event listeners
__nodeListeners = [];
// emit event for clicks inside the player container
// emits: PLAYER_CLICK
__emitPlayerClick = (...args) => {
this.emitter.emit(PLAYER_CLICK, ...args);
};
__playerResizeListener = () => {
const { offsetWidth: initialWidth, offsetHeight: initialHeight } = this.player;
this.dimensions.width = initialWidth;
this.dimensions.height = initialHeight;
return this.__resizeHandler;
};
// listen for changes in the video tag dimensions
// emits: RESIZE
__resizeHandler = () => {
const { offsetWidth: currentWidth, offsetHeight: currentHeight } = this.player;
const changedWidth = currentWidth !== this.dimensions.width;
const changedHeight = currentHeight !== this.dimensions.height;
if (changedWidth || changedHeight) {
const newDimensions = { width: currentWidth, height: currentHeight };
this.dimensions = newDimensions;
this.emitter.emit(RESIZE, newDimensions);
}
};
// listens for timeupdate and emits an event with duration, currentTime and readableTime of the <video> tag, for VPAID, see VPAIDWrapper.onAdRemainingTimeChange
// emits: PLAYBACK_PROGRESS
// { remainingTime, readableTime, duration, currentTime }
__playbackProgressReporter = () => {
const { currentTime, duration } = this.player;
const fancyCurrentTime = secondsToReadableTime(currentTime);
const fancyDuration = secondsToReadableTime(duration);
const remainingTime = duration - currentTime;
const payload = {
remainingTime,
fancyCurrentTime,
fancyDuration,
duration,
currentTime
};
this.emitter.emit(PLAYBACK_PROGRESS, payload);
};
// teardown methods
__removeListeners = () => {
// remove internal listeners
this.emitter.events = {};
// remove player listeners
this.__nodeListeners.forEach(([node, ...args]) => {
node.removeEventListener(...args);
});
};
__listenerStore = {
on: [],
once: []
};
__storeListener =
type =>
(...args) => {
this.__listenerStore?.[type].push(args);
};
// attach pending listeners
// emits: 'attaching-EVENT_NAME', where EVENT_NAME is the original event name
// this event is useful when the user wants access to the teardown function
__attachStoredListeners = () => {
let key;
for (key in this.__listenerStore) {
this.__listenerStore[key].forEach(args => {
const teardown = this[key](...args);
const storageEvent = `attaching-${key}`;
// emit an event that allows recovering the teardown fn of async listeners
this.emitter.emit(storageEvent, teardown);
});
}
this.__listenerStore = null;
};
__shouldStoreListener = eventName => {
const isInternal = this.__isInternalEvent(eventName);
const {
config: { isVAST },
dataReady
} = this;
const shouldStoreListener = !isInternal && isVAST && !dataReady;
return shouldStoreListener;
};
// event handler
on = (eventName, ...args) => {
const { isVPAID } = this;
if (this.__shouldStoreListener(eventName)) {
this.__storeListener('on')(eventName, ...args);
return;
}
const teardown =
// All VPAID events are considered as internal and mapped in VPAIDWrapper
isVPAID || this.__isInternalEvent(eventName)
? // Set instance listener
this.emitter.on.apply(this.emitter, [eventName, ...args])
: // Set player listeners
this.__nodeOn(this.player, eventName, ...args);
// return the teardown function
return teardown;
};
// listen for an event just once
once = (eventName, callback) => {
if (this.__shouldStoreListener(eventName)) {
this.__storeListener('once')(eventName, callback);
return;
}
const unbind = this.on(eventName, (...args) => {
unbind();
callback.apply(this, args);
});
return unbind;
};
// store for current video dimensions
dimensions = {
width: 0,
height: 0
};
// start media playback
play = () => {
const { isVPAID, VPAIDStarted, VPAIDWrapper } = this;
if (isVPAID) {
if (VPAIDStarted) {
return VPAIDWrapper?.resumeAd();
}
return VPAIDWrapper?.startAd();
}
this.player.play();
};
// stop media playback
pause = () => {
const { isVPAID, VPAIDWrapper } = this;
if (isVPAID) {
return VPAIDWrapper?.pauseAd();
}
this.player.pause();
};
// toggle media playback
playPause = () => {
if (this.isVPAID && this.VPAIDFinished) {
// REPLAYING VAST
return this.__runVAST();
}
if (this.player.paused) {
return this.play();
}
return this.pause();
};
// set the media volume, accepts float numbers between 0 and 1
volume = value => {
const { isVPAID, VPAIDWrapper } = this;
const volume = Math.min(Math.max(value, 0), 1);
this.player.muted = !volume;
if (isVPAID) {
return this.dataReady ? VPAIDWrapper?.setAdVolume(volume) : 0;
}
this.player.volume = volume;
};
// mute audio
mute = () => {
this.__prevVol = this.getVolume() || this.config.volume || 1;
this.volume(0);
this.muted = true;
};
// unmute audio
unmute = () => {
const vol = this.__prevVol || this.config.volume || 1;
this.volume(vol);
this.muted = false;
};
// toggle mute
muteUnmute = () => {
const currentVol = this.getVolume();
if (currentVol) {
return this.mute();
}
return this.unmute();
};
// return the video volume
getVolume = () => {
if (this.isVPAID) {
return this.dataReady ? this.VPAIDWrapper?.getAdVolume() : 0;
}
return this.player.muted ? 0 : this.player.volume;
};
// return the duration of the video
getDuration = () => {
let duration;
if (this.isVPAID) {
if (this.VPAIDFinished) {
// Use last known duration
duration = this.duration;
} else {
// Retrieve duration from VPAID wrapper
duration = this.dataReady && this.VPAIDWrapper?.getAdDuration();
}
} else {
// Get video tag duration
duration = this.player.duration;
}
// store duration
this.duration = duration;
return duration || 0;
};
// return the currentTime of the video
getCurrentTime = () => {
if (this.isVPAID) {
return this.VPAIDFinished ? this.duration : this.VPAIDWrapper?.currentTime;
}
const { currentTime } = this.player;
return currentTime;
};
// turn fullscreen on/off
fullscreenToggle = fullscreenToggle;
// remove all event listeners and remove everything inside the container
// emits PRE_DESTROY
destroy = () => {
this.emitter.emit(PRE_DESTROY);
this.pause();
this.__removeListeners();
this.container.innerHTML = '';
};
}