@cloudnest/redxplyr 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.editorconfig +10 -0
  2. package/.gitpod.yml +6 -0
  3. package/.node-version +1 -0
  4. package/.prettierrc +7 -0
  5. package/.stickler.yml +5 -0
  6. package/.stylelintrc.json +26 -0
  7. package/CHANGELOG.md +16 -0
  8. package/CONTRIBUTING.md +34 -0
  9. package/CONTROLS.md +49 -0
  10. package/Dockerfile +32 -0
  11. package/LICENSE.md +22 -0
  12. package/README.md +194 -0
  13. package/cspell.json +48 -0
  14. package/dist/redxplyr.css +1 -0
  15. package/dist/redxplyr.js +8801 -0
  16. package/dist/redxplyr.min.js +2 -0
  17. package/dist/redxplyr.min.js.map +1 -0
  18. package/dist/redxplyr.min.mjs +1 -0
  19. package/dist/redxplyr.min.mjs.map +1 -0
  20. package/dist/redxplyr.mjs +8793 -0
  21. package/dist/redxplyr.polyfilled.js +9294 -0
  22. package/dist/redxplyr.polyfilled.min.js +2 -0
  23. package/dist/redxplyr.polyfilled.min.js.map +1 -0
  24. package/dist/redxplyr.polyfilled.min.mjs +1 -0
  25. package/dist/redxplyr.polyfilled.min.mjs.map +1 -0
  26. package/dist/redxplyr.polyfilled.mjs +9286 -0
  27. package/dist/redxplyr.svg +1 -0
  28. package/eslint.config.mjs +39 -0
  29. package/gulpfile.js +8 -0
  30. package/package.json +114 -0
  31. package/pnpm-workspace.yaml +8 -0
  32. package/src/js/captions.js +411 -0
  33. package/src/js/config/defaults.js +459 -0
  34. package/src/js/config/states.js +10 -0
  35. package/src/js/config/types.js +34 -0
  36. package/src/js/console.js +28 -0
  37. package/src/js/controls.js +1870 -0
  38. package/src/js/fullscreen.js +305 -0
  39. package/src/js/html5.js +148 -0
  40. package/src/js/listeners.js +854 -0
  41. package/src/js/media.js +61 -0
  42. package/src/js/plugins/ads.js +647 -0
  43. package/src/js/plugins/preview-thumbnails.js +706 -0
  44. package/src/js/plugins/vimeo.js +443 -0
  45. package/src/js/plugins/youtube.js +451 -0
  46. package/src/js/plyr.d.ts +729 -0
  47. package/src/js/plyr.js +1291 -0
  48. package/src/js/plyr.polyfilled.js +13 -0
  49. package/src/js/source.js +155 -0
  50. package/src/js/storage.js +70 -0
  51. package/src/js/support.js +100 -0
  52. package/src/js/ui.js +297 -0
  53. package/src/js/utils/animation.js +33 -0
  54. package/src/js/utils/arrays.js +23 -0
  55. package/src/js/utils/browser.js +21 -0
  56. package/src/js/utils/elements.js +263 -0
  57. package/src/js/utils/events.js +116 -0
  58. package/src/js/utils/fetch.js +45 -0
  59. package/src/js/utils/i18n.js +47 -0
  60. package/src/js/utils/is.js +81 -0
  61. package/src/js/utils/load-image.js +19 -0
  62. package/src/js/utils/load-script.js +14 -0
  63. package/src/js/utils/load-sprite.js +77 -0
  64. package/src/js/utils/numbers.js +17 -0
  65. package/src/js/utils/objects.js +43 -0
  66. package/src/js/utils/promise.js +14 -0
  67. package/src/js/utils/strings.js +80 -0
  68. package/src/js/utils/style.js +148 -0
  69. package/src/js/utils/time.js +36 -0
  70. package/src/js/utils/urls.js +40 -0
  71. package/src/sass/base.scss +69 -0
  72. package/src/sass/components/badges.scss +12 -0
  73. package/src/sass/components/captions.scss +58 -0
  74. package/src/sass/components/control.scss +52 -0
  75. package/src/sass/components/controls.scss +65 -0
  76. package/src/sass/components/menus.scss +205 -0
  77. package/src/sass/components/poster.scss +27 -0
  78. package/src/sass/components/progress.scss +107 -0
  79. package/src/sass/components/sliders.scss +99 -0
  80. package/src/sass/components/times.scss +20 -0
  81. package/src/sass/components/tooltips.scss +91 -0
  82. package/src/sass/components/volume.scss +18 -0
  83. package/src/sass/lib/animation.scss +31 -0
  84. package/src/sass/lib/css-vars.scss +103 -0
  85. package/src/sass/lib/functions.scss +3 -0
  86. package/src/sass/lib/mixins.scss +82 -0
  87. package/src/sass/plugins/ads.scss +53 -0
  88. package/src/sass/plugins/preview-thumbnails/index.scss +121 -0
  89. package/src/sass/plugins/preview-thumbnails/settings.scss +17 -0
  90. package/src/sass/plyr.scss +46 -0
  91. package/src/sass/settings/badges.scss +7 -0
  92. package/src/sass/settings/breakpoints.scss +9 -0
  93. package/src/sass/settings/captions.scss +10 -0
  94. package/src/sass/settings/colors.scss +18 -0
  95. package/src/sass/settings/controls.scss +30 -0
  96. package/src/sass/settings/cosmetics.scss +5 -0
  97. package/src/sass/settings/helpers.scss +7 -0
  98. package/src/sass/settings/menus.scss +13 -0
  99. package/src/sass/settings/progress.scss +18 -0
  100. package/src/sass/settings/sliders.scss +39 -0
  101. package/src/sass/settings/tooltips.scss +11 -0
  102. package/src/sass/settings/type.scss +16 -0
  103. package/src/sass/states/fullscreen.scss +15 -0
  104. package/src/sass/types/audio.scss +61 -0
  105. package/src/sass/types/video.scss +170 -0
  106. package/src/sass/utils/animation.scss +7 -0
  107. package/src/sass/utils/hidden.scss +28 -0
  108. package/src/sprite/plyr-airplay.svg +8 -0
  109. package/src/sprite/plyr-captions-off.svg +7 -0
  110. package/src/sprite/plyr-captions-on.svg +7 -0
  111. package/src/sprite/plyr-download.svg +8 -0
  112. package/src/sprite/plyr-enter-fullscreen.svg +4 -0
  113. package/src/sprite/plyr-exit-fullscreen.svg +4 -0
  114. package/src/sprite/plyr-fast-forward.svg +3 -0
  115. package/src/sprite/plyr-logo-vimeo.svg +6 -0
  116. package/src/sprite/plyr-logo-youtube.svg +6 -0
  117. package/src/sprite/plyr-muted.svg +8 -0
  118. package/src/sprite/plyr-pause.svg +8 -0
  119. package/src/sprite/plyr-pip.svg +6 -0
  120. package/src/sprite/plyr-play.svg +5 -0
  121. package/src/sprite/plyr-restart.svg +5 -0
  122. package/src/sprite/plyr-rewind.svg +3 -0
  123. package/src/sprite/plyr-settings.svg +5 -0
  124. package/src/sprite/plyr-volume.svg +11 -0
  125. package/tasks/build.js +226 -0
  126. package/tasks/deploy.js +216 -0
  127. package/tasks/utils/publish.js +34 -0
@@ -0,0 +1,61 @@
1
+ // ==========================================================================
2
+ // Plyr Media
3
+ // ==========================================================================
4
+
5
+ import html5 from './html5';
6
+ import vimeo from './plugins/vimeo';
7
+ import youtube from './plugins/youtube';
8
+ import { createElement, toggleClass, wrap } from './utils/elements';
9
+
10
+ const media = {
11
+ // Setup media
12
+ setup() {
13
+ // If there's no media, bail
14
+ if (!this.media) {
15
+ this.debug.warn('No media element found!');
16
+ return;
17
+ }
18
+
19
+ // Add type class
20
+ toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);
21
+
22
+ // Add provider class
23
+ toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);
24
+
25
+ // Add video class for embeds
26
+ // This will require changes if audio embeds are added
27
+ if (this.isEmbed) {
28
+ toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);
29
+ }
30
+
31
+ // Inject the player wrapper
32
+ if (this.isVideo) {
33
+ // Create the wrapper div
34
+ this.elements.wrapper = createElement('div', {
35
+ class: this.config.classNames.video,
36
+ });
37
+
38
+ // Wrap the video in a container
39
+ wrap(this.media, this.elements.wrapper);
40
+
41
+ // Poster image container
42
+ this.elements.poster = createElement('div', {
43
+ class: this.config.classNames.poster,
44
+ });
45
+
46
+ this.elements.wrapper.appendChild(this.elements.poster);
47
+ }
48
+
49
+ if (this.isHTML5) {
50
+ html5.setup.call(this);
51
+ }
52
+ else if (this.isYouTube) {
53
+ youtube.setup.call(this);
54
+ }
55
+ else if (this.isVimeo) {
56
+ vimeo.setup.call(this);
57
+ }
58
+ },
59
+ };
60
+
61
+ export default media;
@@ -0,0 +1,647 @@
1
+ // ==========================================================================
2
+ // Advertisement plugin using Google IMA HTML5 SDK
3
+ // Create an account with our ad partner, vi here:
4
+ // https://www.vi.ai/publisher-video-monetization/
5
+ // ==========================================================================
6
+
7
+ /* global google */
8
+
9
+ import { createElement } from '../utils/elements';
10
+ import { triggerEvent } from '../utils/events';
11
+ import i18n from '../utils/i18n';
12
+ import is from '../utils/is';
13
+ import loadScript from '../utils/load-script';
14
+ import { silencePromise } from '../utils/promise';
15
+ import { formatTime } from '../utils/time';
16
+ import { buildUrlParams } from '../utils/urls';
17
+
18
+ function destroy(instance) {
19
+ // Destroy our adsManager
20
+ if (instance.manager) {
21
+ instance.manager.destroy();
22
+ }
23
+
24
+ // Destroy our adsManager
25
+ if (instance.elements.displayContainer) {
26
+ instance.elements.displayContainer.destroy();
27
+ }
28
+
29
+ instance.elements.container.remove();
30
+ }
31
+
32
+ class Ads {
33
+ /**
34
+ * Ads constructor.
35
+ * @param {object} player
36
+ * @return {Ads}
37
+ */
38
+ constructor(player) {
39
+ this.player = player;
40
+ this.config = player.config.ads;
41
+ this.playing = false;
42
+ this.initialized = false;
43
+ this.elements = {
44
+ container: null,
45
+ displayContainer: null,
46
+ };
47
+ this.manager = null;
48
+ this.loader = null;
49
+ this.cuePoints = null;
50
+ this.events = {};
51
+ this.safetyTimer = null;
52
+ this.countdownTimer = null;
53
+
54
+ // Setup a promise to resolve when the IMA manager is ready
55
+ this.managerPromise = new Promise((resolve, reject) => {
56
+ // The ad is loaded and ready
57
+ this.on('loaded', resolve);
58
+
59
+ // Ads failed
60
+ this.on('error', reject);
61
+ });
62
+
63
+ this.load();
64
+ }
65
+
66
+ get enabled() {
67
+ const { config } = this;
68
+
69
+ return (
70
+ this.player.isHTML5
71
+ && this.player.isVideo
72
+ && config.enabled
73
+ && (!is.empty(config.publisherId) || is.url(config.tagUrl))
74
+ );
75
+ }
76
+
77
+ /**
78
+ * Load the IMA SDK
79
+ */
80
+ load = () => {
81
+ if (!this.enabled) {
82
+ return;
83
+ }
84
+
85
+ // Check if the Google IMA3 SDK is loaded or load it ourselves
86
+ if (!is.object(window.google) || !is.object(window.google.ima)) {
87
+ loadScript(this.player.config.urls.googleIMA.sdk)
88
+ .then(() => {
89
+ this.ready();
90
+ })
91
+ .catch(() => {
92
+ // Script failed to load or is blocked
93
+ this.trigger('error', new Error('Google IMA SDK failed to load'));
94
+ });
95
+ }
96
+ else {
97
+ this.ready();
98
+ }
99
+ };
100
+
101
+ /**
102
+ * Get the ads instance ready
103
+ */
104
+ ready = () => {
105
+ // Double check we're enabled
106
+ if (!this.enabled) {
107
+ destroy(this);
108
+ }
109
+
110
+ // Start ticking our safety timer. If the whole advertisement
111
+ // thing doesn't resolve within our set time; we bail
112
+ this.startSafetyTimer(12000, 'ready()');
113
+
114
+ // Clear the safety timer
115
+ this.managerPromise.then(() => {
116
+ this.clearSafetyTimer('onAdsManagerLoaded()');
117
+ });
118
+
119
+ // Set listeners on the Plyr instance
120
+ this.listeners();
121
+
122
+ // Setup the IMA SDK
123
+ this.setupIMA();
124
+ };
125
+
126
+ // Build the tag URL
127
+ get tagUrl() {
128
+ const { config } = this;
129
+
130
+ if (is.url(config.tagUrl)) {
131
+ return config.tagUrl;
132
+ }
133
+
134
+ const params = {
135
+ AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',
136
+ AV_CHANNELID: '5a0458dc28a06145e4519d21',
137
+ AV_URL: window.location.hostname,
138
+ cb: Date.now(),
139
+ AV_WIDTH: 640,
140
+ AV_HEIGHT: 480,
141
+ AV_CDIM2: config.publisherId,
142
+ };
143
+
144
+ const base = 'https://go.aniview.com/api/adserver6/vast/';
145
+
146
+ return `${base}?${buildUrlParams(params)}`;
147
+ }
148
+
149
+ /**
150
+ * In order for the SDK to display ads for our video, we need to tell it where to put them,
151
+ * so here we define our ad container. This div is set up to render on top of the video player.
152
+ * Using the code below, we tell the SDK to render ads within that div. We also provide a
153
+ * handle to the content video player - the SDK will poll the current time of our player to
154
+ * properly place mid-rolls. After we create the ad display container, we initialize it. On
155
+ * mobile devices, this initialization is done as the result of a user action.
156
+ */
157
+ setupIMA = () => {
158
+ // Create the container for our advertisements
159
+ this.elements.container = createElement('div', {
160
+ class: this.player.config.classNames.ads,
161
+ });
162
+
163
+ this.player.elements.container.appendChild(this.elements.container);
164
+
165
+ // So we can run VPAID2
166
+ google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
167
+
168
+ // Set language
169
+ google.ima.settings.setLocale(this.player.config.ads.language);
170
+
171
+ // Set playback for iOS10+
172
+ google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);
173
+
174
+ // We assume the adContainer is the video container of the plyr element that will house the ads
175
+ this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);
176
+
177
+ // Create ads loader
178
+ this.loader = new google.ima.AdsLoader(this.elements.displayContainer);
179
+
180
+ // Listen and respond to ads loaded and error events
181
+ this.loader.addEventListener(
182
+ google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
183
+ event => this.onAdsManagerLoaded(event),
184
+ false,
185
+ );
186
+ this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
187
+
188
+ // Request video ads to be pre-loaded
189
+ this.requestAds();
190
+ };
191
+
192
+ /**
193
+ * Request advertisements
194
+ */
195
+ requestAds = () => {
196
+ const { container } = this.player.elements;
197
+
198
+ try {
199
+ // Request video ads
200
+ const request = new google.ima.AdsRequest();
201
+ request.adTagUrl = this.tagUrl;
202
+
203
+ // Specify the linear and nonlinear slot sizes. This helps the SDK
204
+ // to select the correct creative if multiple are returned
205
+ request.linearAdSlotWidth = container.offsetWidth;
206
+ request.linearAdSlotHeight = container.offsetHeight;
207
+ request.nonLinearAdSlotWidth = container.offsetWidth;
208
+ request.nonLinearAdSlotHeight = container.offsetHeight;
209
+
210
+ // We only overlay ads as we only support video.
211
+ request.forceNonLinearFullSlot = false;
212
+
213
+ // Mute based on current state
214
+ request.setAdWillPlayMuted(!this.player.muted);
215
+
216
+ this.loader.requestAds(request);
217
+ }
218
+ catch (error) {
219
+ this.onAdError(error);
220
+ }
221
+ };
222
+
223
+ /**
224
+ * Update the ad countdown
225
+ * @param {boolean} start
226
+ */
227
+ pollCountdown = (start = false) => {
228
+ if (!start) {
229
+ clearInterval(this.countdownTimer);
230
+ this.elements.container.removeAttribute('data-badge-text');
231
+ return;
232
+ }
233
+
234
+ const update = () => {
235
+ const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));
236
+ const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;
237
+ this.elements.container.setAttribute('data-badge-text', label);
238
+ };
239
+
240
+ this.countdownTimer = setInterval(update, 100);
241
+ };
242
+
243
+ /**
244
+ * This method is called whenever the ads are ready inside the AdDisplayContainer
245
+ * @param {Event} event - adsManagerLoadedEvent
246
+ */
247
+ onAdsManagerLoaded = (event) => {
248
+ // Load could occur after a source change (race condition)
249
+ if (!this.enabled) {
250
+ return;
251
+ }
252
+
253
+ // Get the ads manager
254
+ const settings = new google.ima.AdsRenderingSettings();
255
+
256
+ // Tell the SDK to save and restore content video state on our behalf
257
+ settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
258
+ settings.enablePreloading = true;
259
+
260
+ // The SDK is polling currentTime on the contentPlayback. And needs a duration
261
+ // so it can determine when to start the mid- and post-roll
262
+ this.manager = event.getAdsManager(this.player, settings);
263
+
264
+ // Get the cue points for any mid-rolls by filtering out the pre- and post-roll
265
+ this.cuePoints = this.manager.getCuePoints();
266
+
267
+ // Add listeners to the required events
268
+ // Advertisement error events
269
+ this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
270
+
271
+ // Advertisement regular events
272
+ Object.keys(google.ima.AdEvent.Type).forEach((type) => {
273
+ this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));
274
+ });
275
+
276
+ // Resolve our adsManager
277
+ this.trigger('loaded');
278
+ };
279
+
280
+ addCuePoints = () => {
281
+ // Add advertisement cue's within the time line if available
282
+ if (!is.empty(this.cuePoints)) {
283
+ this.cuePoints.forEach((cuePoint) => {
284
+ if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {
285
+ const seekElement = this.player.elements.progress;
286
+
287
+ if (is.element(seekElement)) {
288
+ const cuePercentage = (100 / this.player.duration) * cuePoint;
289
+ const cue = createElement('span', {
290
+ class: this.player.config.classNames.cues,
291
+ });
292
+
293
+ cue.style.left = `${cuePercentage.toString()}%`;
294
+ seekElement.appendChild(cue);
295
+ }
296
+ }
297
+ });
298
+ }
299
+ };
300
+
301
+ /**
302
+ * This is where all the event handling takes place. Retrieve the ad from the event. Some
303
+ * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated
304
+ * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type
305
+ * @param {Event} event
306
+ */
307
+ onAdEvent = (event) => {
308
+ const { container } = this.player.elements;
309
+ // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
310
+ // don't have ad object associated
311
+ const ad = event.getAd();
312
+ const adData = event.getAdData();
313
+
314
+ // Proxy event
315
+ const dispatchEvent = (type) => {
316
+ triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);
317
+ };
318
+
319
+ // Bubble the event
320
+ dispatchEvent(event.type);
321
+
322
+ switch (event.type) {
323
+ case google.ima.AdEvent.Type.LOADED:
324
+ // This is the first event sent for an ad - it is possible to determine whether the
325
+ // ad is a video ad or an overlay
326
+ this.trigger('loaded');
327
+
328
+ // Start countdown
329
+ this.pollCountdown(true);
330
+
331
+ if (!ad.isLinear()) {
332
+ // Position AdDisplayContainer correctly for overlay
333
+ ad.width = container.offsetWidth;
334
+ ad.height = container.offsetHeight;
335
+ }
336
+
337
+ // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());
338
+ // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());
339
+
340
+ break;
341
+
342
+ case google.ima.AdEvent.Type.STARTED:
343
+ // Set volume to match player
344
+ this.manager.setVolume(this.player.volume);
345
+
346
+ break;
347
+
348
+ case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
349
+ // All ads for the current videos are done. We can now request new advertisements
350
+ // in case the video is re-played
351
+
352
+ // TODO: Example for what happens when a next video in a playlist would be loaded.
353
+ // So here we load a new video when all ads are done.
354
+ // Then we load new ads within a new adsManager. When the video
355
+ // Is started - after - the ads are loaded, then we get ads.
356
+ // You can also easily test cancelling and reloading by running
357
+ // player.ads.cancel() and player.ads.play from the console I guess.
358
+ // this.player.source = {
359
+ // type: 'video',
360
+ // title: 'Flower macro study',
361
+ // sources: [{
362
+ // src:
363
+ // 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4', type:
364
+ // 'video/mp4', }], poster:
365
+ // '/media/redxplyr-cover.svg', tracks:
366
+ // [ { kind: 'captions', label: 'English', srclang: 'en', src:
367
+ // '/media/redxplyr-demo.en.vtt', default: true, }, ],
368
+ // };
369
+
370
+ // TODO: So there is still this thing where a video should only be allowed to start
371
+ // playing when the IMA SDK is ready or has failed
372
+
373
+ if (this.player.ended) {
374
+ this.loadAds();
375
+ }
376
+ else {
377
+ // The SDK won't allow new ads to be called without receiving a contentComplete()
378
+ this.loader.contentComplete();
379
+ }
380
+
381
+ break;
382
+
383
+ case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
384
+ // This event indicates the ad has started - the video player can adjust the UI,
385
+ // for example display a pause button and remaining time. Fired when content should
386
+ // be paused. This usually happens right before an ad is about to cover the content
387
+
388
+ this.pauseContent();
389
+
390
+ break;
391
+
392
+ case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
393
+ // This event indicates the ad has finished - the video player can perform
394
+ // appropriate UI actions, such as removing the timer for remaining time detection.
395
+ // Fired when content should be resumed. This usually happens when an ad finishes
396
+ // or collapses
397
+
398
+ this.pollCountdown();
399
+
400
+ this.resumeContent();
401
+
402
+ break;
403
+
404
+ case google.ima.AdEvent.Type.LOG:
405
+ if (adData.adError) {
406
+ this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);
407
+ }
408
+
409
+ break;
410
+
411
+ default:
412
+ break;
413
+ }
414
+ };
415
+
416
+ /**
417
+ * Any ad error handling comes through here
418
+ * @param {Event} event
419
+ */
420
+ onAdError = (event) => {
421
+ this.cancel();
422
+ this.player.debug.warn('Ads error', event);
423
+ };
424
+
425
+ /**
426
+ * Setup hooks for Plyr and window events. This ensures
427
+ * the mid- and post-roll launch at the correct time. And
428
+ * resize the advertisement when the player resizes
429
+ */
430
+ listeners = () => {
431
+ const { container } = this.player.elements;
432
+ let time;
433
+
434
+ this.player.on('canplay', () => {
435
+ this.addCuePoints();
436
+ });
437
+
438
+ this.player.on('ended', () => {
439
+ this.loader.contentComplete();
440
+ });
441
+
442
+ this.player.on('timeupdate', () => {
443
+ time = this.player.currentTime;
444
+ });
445
+
446
+ this.player.on('seeked', () => {
447
+ const seekedTime = this.player.currentTime;
448
+
449
+ if (is.empty(this.cuePoints)) {
450
+ return;
451
+ }
452
+
453
+ this.cuePoints.forEach((cuePoint, index) => {
454
+ if (time < cuePoint && cuePoint < seekedTime) {
455
+ this.manager.discardAdBreak();
456
+ this.cuePoints.splice(index, 1);
457
+ }
458
+ });
459
+ });
460
+
461
+ // Listen to the resizing of the window. And resize ad accordingly
462
+ // TODO: eventually implement ResizeObserver
463
+ window.addEventListener('resize', () => {
464
+ if (this.manager) {
465
+ this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
466
+ }
467
+ });
468
+ };
469
+
470
+ /**
471
+ * Initialize the adsManager and start playing advertisements
472
+ */
473
+ play = () => {
474
+ const { container } = this.player.elements;
475
+
476
+ if (!this.managerPromise) {
477
+ this.resumeContent();
478
+ }
479
+
480
+ // Play the requested advertisement whenever the adsManager is ready
481
+ this.managerPromise
482
+ .then(() => {
483
+ // Set volume to match player
484
+ this.manager.setVolume(this.player.volume);
485
+
486
+ // Initialize the container. Must be done via a user action on mobile devices
487
+ this.elements.displayContainer.initialize();
488
+
489
+ try {
490
+ if (!this.initialized) {
491
+ // Initialize the ads manager. Ad rules playlist will start at this time
492
+ this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
493
+
494
+ // Call play to start showing the ad. Single video and overlay ads will
495
+ // start at this time; the call will be ignored for ad rules
496
+ this.manager.start();
497
+ }
498
+
499
+ this.initialized = true;
500
+ }
501
+ catch (adError) {
502
+ // An error may be thrown if there was a problem with the
503
+ // VAST response
504
+ this.onAdError(adError);
505
+ }
506
+ })
507
+ .catch(() => {});
508
+ };
509
+
510
+ /**
511
+ * Resume our video
512
+ */
513
+ resumeContent = () => {
514
+ // Hide the advertisement container
515
+ this.elements.container.style.zIndex = '';
516
+
517
+ // Ad is stopped
518
+ this.playing = false;
519
+
520
+ // Play video
521
+ silencePromise(this.player.media.play());
522
+ };
523
+
524
+ /**
525
+ * Pause our video
526
+ */
527
+ pauseContent = () => {
528
+ // Show the advertisement container
529
+ this.elements.container.style.zIndex = 3;
530
+
531
+ // Ad is playing
532
+ this.playing = true;
533
+
534
+ // Pause our video.
535
+ this.player.media.pause();
536
+ };
537
+
538
+ /**
539
+ * Destroy the adsManager so we can grab new ads after this. If we don't then we're not
540
+ * allowed to call new ads based on google policies, as they interpret this as an accidental
541
+ * video requests. https://developers.google.com/interactive-
542
+ * media-ads/docs/sdks/android/faq#8
543
+ */
544
+ cancel = () => {
545
+ // Pause our video
546
+ if (this.initialized) {
547
+ this.resumeContent();
548
+ }
549
+
550
+ // Tell our instance that we're done for now
551
+ this.trigger('error');
552
+
553
+ // Re-create our adsManager
554
+ this.loadAds();
555
+ };
556
+
557
+ /**
558
+ * Re-create our adsManager
559
+ */
560
+ loadAds = () => {
561
+ // Tell our adsManager to go bye bye
562
+ this.managerPromise
563
+ .then(() => {
564
+ // Destroy our adsManager
565
+ if (this.manager) {
566
+ this.manager.destroy();
567
+ }
568
+
569
+ // Re-set our adsManager promises
570
+ this.managerPromise = new Promise((resolve) => {
571
+ this.on('loaded', resolve);
572
+ this.player.debug.log(this.manager);
573
+ });
574
+ // Now that the manager has been destroyed set it to also be un-initialized
575
+ this.initialized = false;
576
+
577
+ // Now request some new advertisements
578
+ this.requestAds();
579
+ })
580
+ .catch(() => {});
581
+ };
582
+
583
+ /**
584
+ * Handles callbacks after an ad event was invoked
585
+ * @param {string} event - Event type
586
+ * @param args
587
+ */
588
+ trigger = (event, ...args) => {
589
+ const handlers = this.events[event];
590
+
591
+ if (is.array(handlers)) {
592
+ handlers.forEach((handler) => {
593
+ if (is.function(handler)) {
594
+ handler.apply(this, args);
595
+ }
596
+ });
597
+ }
598
+ };
599
+
600
+ /**
601
+ * Add event listeners
602
+ * @param {string} event - Event type
603
+ * @param {Function} callback - Callback for when event occurs
604
+ * @return {Ads}
605
+ */
606
+ on = (event, callback) => {
607
+ if (!is.array(this.events[event])) {
608
+ this.events[event] = [];
609
+ }
610
+
611
+ this.events[event].push(callback);
612
+
613
+ return this;
614
+ };
615
+
616
+ /**
617
+ * Setup a safety timer for when the ad network doesn't respond for whatever reason.
618
+ * The advertisement has 12 seconds to get its things together. We stop this timer when the
619
+ * advertisement is playing, or when a user action is required to start, then we clear the
620
+ * timer on ad ready
621
+ * @param {number} time
622
+ * @param {string} from
623
+ */
624
+ startSafetyTimer = (time, from) => {
625
+ this.player.debug.log(`Safety timer invoked from: ${from}`);
626
+
627
+ this.safetyTimer = setTimeout(() => {
628
+ this.cancel();
629
+ this.clearSafetyTimer('startSafetyTimer()');
630
+ }, time);
631
+ };
632
+
633
+ /**
634
+ * Clear our safety timer(s)
635
+ * @param {string} from
636
+ */
637
+ clearSafetyTimer = (from) => {
638
+ if (!is.nullOrUndefined(this.safetyTimer)) {
639
+ this.player.debug.log(`Safety timer cleared from: ${from}`);
640
+
641
+ clearTimeout(this.safetyTimer);
642
+ this.safetyTimer = null;
643
+ }
644
+ };
645
+ }
646
+
647
+ export default Ads;