Implementing ads plugin

This commit is contained in:
ferdiemmen 2018-01-13 23:02:59 +01:00
parent d9ec1d1b8e
commit 025fc1090b
12 changed files with 502 additions and 5 deletions

2
demo/dist/demo.css vendored

File diff suppressed because one or more lines are too long

122
demo/dist/demo.js vendored
View File

@ -1,3 +1,123 @@
document.addEventListener("DOMContentLoaded",function(){window.shr&&window.shr.setup({count:{classname:"button__count"}});var e="tab-focus";document.addEventListener("focusout",function(t){t.target.classList.remove(e)}),document.addEventListener("keydown",function(t){9===t.keyCode&&window.setTimeout(function(){document.activeElement.classList.add(e)},0)});var t=new window.Plyr("#player",{debug:!0,title:"View From A Blue Moon",iconUrl:"../dist/plyr.svg",keyboard:{global:!0},tooltips:{controls:!0},captions:{active:!0},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","fullscreen","pip","airplay"],keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"}});window.player=t;var o=document.querySelectorAll("[data-source]"),i={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),n=window.history&&window.history.pushState;function a(e,t,o){e&&e.classList[o?"add":"remove"](t)}function s(e,n){if(e in i&&(n||e!==r)&&(r.length||e!==i.video)){switch(e){case i.video:t.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4",type:"video/mp4"}],poster:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",tracks:[{kind:"captions",label:"English",srclang:"en",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt",default:!0},{kind:"captions",label:"French",srclang:"fr",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt"}]};break;case i.audio:t.source={type:"audio",title:"Kishi Bashi – “It All Began With A Burst”",sources:[{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",type:"audio/mp3"},{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg",type:"audio/ogg"}]};break;case i.youtube:t.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",provider:"youtube"}]};break;case i.vimeo:t.source={type:"video",sources:[{src:"https://vimeo.com/76979871",provider:"vimeo"}]}}r=e,Array.from(o).forEach(function(e){return a(e.parentElement,"active",!1)}),a(document.querySelector('[data-source="'+e+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+e).removeAttribute("hidden")}}if(Array.from(o).forEach(function(e){e.addEventListener("click",function(){var t=e.getAttribute("data-source");s(t),n&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&s(e.state.type)}),n){var c=!r.length;c&&(r=i.video),r in i&&window.history.replaceState({type:r},"",c?"":"#"+r),r!==i.video&&s(r,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,r,n,a){e.GoogleAnalyticsObject="ga",e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,n=t.createElement("script"),a=t.getElementsByTagName("script")[0],n.async=1,n.src="//www.google-analytics.com/analytics.js",a.parentNode.insertBefore(n,a)}(window,document),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview")); document.addEventListener('DOMContentLoaded', function() {
window.shr && window.shr.setup({ count: { classname: 'button__count' } });
var e = 'tab-focus';
document.addEventListener('focusout', function(t) {
t.target.classList.remove(e);
}),
document.addEventListener('keydown', function(t) {
9 === t.keyCode &&
window.setTimeout(function() {
document.activeElement.classList.add(e);
}, 0);
});
var t = new window.Plyr('#player', {
debug: !0,
title: 'View From A Blue Moon',
iconUrl: '../dist/plyr.svg',
keyboard: { global: !0 },
tooltips: { controls: !0 },
captions: { active: !0 },
ads: { adTagUrl: 'http://go.aniview.com/api/adserver6/vast/?AV_PUBLISHERID=58c25bb0073ef448b1087ad6&AV_CHANNELID=5a0458dc28a06145e4519d21&AV_URL=127.0.0.1:3000&cb=1&AV_WIDTH=640&AV_HEIGHT=480' },
controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'fullscreen', 'pip', 'airplay'],
keys: { google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c' },
});
window.player = t;
var o = document.querySelectorAll('[data-source]'),
i = { video: 'video', audio: 'audio', youtube: 'youtube', vimeo: 'vimeo' },
r = window.location.hash.replace('#', ''),
n = window.history && window.history.pushState;
function a(e, t, o) {
e && e.classList[o ? 'add' : 'remove'](t);
}
function s(e, n) {
if (e in i && (n || e !== r) && (r.length || e !== i.video)) {
switch (e) {
case i.video:
t.source = {
type: 'video',
title: 'View From A Blue Moon',
sources: [{ src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type: 'video/mp4' }],
poster: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg',
tracks: [
{
kind: 'captions',
label: 'English',
srclang: 'en',
src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
default: !0,
},
{
kind: 'captions',
label: 'French',
srclang: 'fr',
src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt',
},
],
};
break;
case i.audio:
t.source = {
type: 'audio',
title: 'Kishi Bashi – “It All Began With A Burst”',
sources: [
{ src: 'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3', type: 'audio/mp3' },
{ src: 'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg', type: 'audio/ogg' },
],
};
break;
case i.youtube:
t.source = {
type: 'video',
title: 'View From A Blue Moon',
sources: [{ src: 'https://youtube.com/watch?v=bTqVqk7FSmY', provider: 'youtube' }],
};
break;
case i.vimeo:
t.source = { type: 'video', sources: [{ src: 'https://vimeo.com/76979871', provider: 'vimeo' }] };
}
(r = e),
Array.from(o).forEach(function(e) {
return a(e.parentElement, 'active', !1);
}),
a(document.querySelector('[data-source="' + e + '"]'), 'active', !0),
Array.from(document.querySelectorAll('.plyr__cite')).forEach(function(e) {
e.setAttribute('hidden', '');
}),
document.querySelector('.plyr__cite--' + e).removeAttribute('hidden');
}
}
if (
(Array.from(o).forEach(function(e) {
e.addEventListener('click', function() {
var t = e.getAttribute('data-source');
s(t), n && window.history.pushState({ type: t }, '', '#' + t);
});
}),
window.addEventListener('popstate', function(e) {
e.state && 'type' in e.state && s(e.state.type);
}),
n)
) {
var c = !r.length;
c && (r = i.video), r in i && window.history.replaceState({ type: r }, '', c ? '' : '#' + r), r !== i.video && s(r, !0);
}
}),
'plyr.io' === window.location.host &&
(!(function(e, t, o, i, r, n, a) {
(e.GoogleAnalyticsObject = 'ga'),
(e.ga =
e.ga ||
function() {
(e.ga.q = e.ga.q || []).push(arguments);
}),
(e.ga.l = 1 * new Date()),
(n = t.createElement('script')),
(a = t.getElementsByTagName('script')[0]),
(n.async = 1),
(n.src = '//www.google-analytics.com/analytics.js'),
a.parentNode.insertBefore(n, a);
})(window, document),
window.ga('create', 'UA-40881672-11', 'auto'),
window.ga('send', 'pageview'));
//# sourceMappingURL=demo.js.map //# sourceMappingURL=demo.js.map

View File

@ -39,3 +39,6 @@
// Plyr // Plyr
@import '../../../../src/sass/plyr'; @import '../../../../src/sass/plyr';
// Ads Plugin
@import '../plugins/ads/ads';

View File

@ -0,0 +1,18 @@
.plyr--ready {
position: relative;
}
.plyr__ads {
bottom: 0;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
left: 0;
position: absolute;
right: 0;
top: 0;
z-index: 10;
video {
left: 0;
}
}

2
dist/plyr.css vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.js vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -186,6 +186,9 @@ const defaults = {
youtube: { youtube: {
api: 'https://www.youtube.com/iframe_api', api: 'https://www.youtube.com/iframe_api',
}, },
googleIMA: {
api: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',
},
}, },
// Custom control listeners // Custom control listeners

329
src/js/plugins/ads.js Normal file
View File

@ -0,0 +1,329 @@
import utils from '../utils';
// Events are different on various devices. We det the correct events, based on userAgent.
const getStartEvents = () => {
let startEvents = ['click'];
// For mobile users the start event will be one of
// touchstart, touchend and touchmove.
if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) {
startEvents = [
'touchstart',
'touchend',
'touchmove',
];
}
return startEvents;
};
export default class Ads {
constructor(player) {
// Check if an adTagUrl is provided.
if (!player.config.ads.adTagUrl) {
return this;
}
// Check if the Google IMA3 SDK is loaded.
if (!utils.is.object(window.google)) {
utils.loadScript(player.config.urls.googleIMA.api);
}
this.player = player;
this.startEvents = getStartEvents();
this.adDisplayContainer = null;
this.adDisplayElement = null;
this.adsManager = null;
this.adsLoader = null;
this.adCuePoints = null;
this.currentAd = null;
this.events = {};
this.videoElement = document.createElement('video');
// Setup the ad display container.
this.setupAdDisplayContainer();
// Setup the IMA SDK.
this.setupIMA();
// Set listeners on the Plyr instance.
// this.setupListeners();
}
setupIMA() {
const { container } = this.player.elements;
// Create ads loader.
this.adsLoader = new window.google.ima.AdsLoader(this.adDisplayContainer, this.videoElement);
// Tell the adsLoader we are handling ad breaks manually.
this.adsLoader.getSettings().setAutoPlayAdBreaks(false);
// Listen and respond to ads loaded and error events.
this.adsLoader.addEventListener(window.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, adEvent => this.onAdsManagerLoaded(adEvent), false);
this.adsLoader.addEventListener(window.google.ima.AdErrorEvent.Type.AD_ERROR, adError => this.onAdError(adError), false);
// Request video ads.
const adsRequest = new window.google.ima.AdsRequest();
adsRequest.adTagUrl = this.player.config.ads.adTagUrl;
// Specify the linear and nonlinear slot sizes. This helps the SDK to
// select the correct creative if multiple are returned.
adsRequest.linearAdSlotWidth = container.offsetWidth;
adsRequest.linearAdSlotHeight = container.offsetHeight;
adsRequest.nonLinearAdSlotWidth = container.offsetWidth;
adsRequest.nonLinearAdSlotHeight = container.offsetHeight;
this.adsLoader.requestAds(adsRequest);
}
onAdsManagerLoaded(adsManagerLoadedEvent) {
const { videoElement } = this;
// Get the ads manager.
const adsRenderingSettings = new window.google.ima.AdsRenderingSettings();
adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
adsRenderingSettings.enablePreloading = true;
// The SDK is polling currentTime on the contentPlayback. And needs a duration
// so it can determine when to start the mid- and post-roll.
this.adsManager = adsManagerLoadedEvent.getAdsManager(videoElement, adsRenderingSettings);
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll.
this.adsCuePoints = this.adsManager.getCuePoints().filter(x => x > 0 && x !== -1);
// Add listeners to the required events.
this.adsManager.addEventListener(window.google.ima.AdErrorEvent.Type.AD_ERROR, adError => this.onAdError(adError));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, adEvent => this.onAdEvent(adEvent));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, adEvent => this.onAdEvent(adEvent));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.ALL_ADS_COMPLETED, adEvent => this.onAdEvent(adEvent));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.AD_BREAK_READY, adEvent => this.onAdEvent(adEvent));
// Listen to any additional events, if necessary.
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.LOADED, adEvent => this.onAdEvent(adEvent));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.STARTED, adEvent => this.onAdEvent(adEvent));
this.adsManager.addEventListener(window.google.ima.AdEvent.Type.COMPLETE, adEvent => this.onAdEvent(adEvent));
}
onAdEvent(adEvent) {
const { container } = this.player.elements;
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated.
const ad = adEvent.getAd();
// Set the currently played ad. This information could be used by callback
// events.
this.currentAd = ad;
// let intervalTimer;
switch (adEvent.type) {
case window.google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to
// determine whether the ad is a video ad or an overlay.
// Show the ad display element.
this.adDisplayElement.style.display = 'block';
this.handleEventListeners('LOADED');
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay.
ad.width = container.offsetWidth;
ad.height = container.offsetHeight;
}
break;
case window.google.ima.AdEvent.Type.STARTED:
// This event indicates the ad has started - the video player
// can adjust the UI, for example display a pause button and
// remaining time.
this.player.pause();
this.handleEventListeners('STARTED');
// if (ad.isLinear()) {
// For a linear ad, a timer can be started to poll for
// the remaining time.
// intervalTimer = setInterval(
// () => {
// let remainingTime = this.adsManager.getRemainingTime();
// console.log(remainingTime);
// },
// 300); // every 300ms
// }
break;
case window.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
this.handleEventListeners('CONTENT_PAUSE_REQUESTED');
break;
case window.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
this.handleEventListeners('CONTENT_RESUME_REQUESTED');
break;
case window.google.ima.AdEvent.Type.AD_BREAK_READY:
// This event indicates that a mid-roll ad is ready to start.
// We pause the player and tell the adsManager to start playing the ad.
this.player.pause();
this.adsManager.start();
this.handleEventListeners('AD_BREAK_READY');
break;
case window.google.ima.AdEvent.Type.COMPLETE:
// This event indicates the ad has finished - the video player
// can perform appropriate UI actions, such as removing the timer for
// remaining time detection.
// clearInterval(intervalTimer);
this.handleEventListeners('COMPLETE');
this.adDisplayElement.style.display = 'none';
if (this.player.currentTime < this.player.duration) {
this.player.play();
}
break;
case window.google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
this.handleEventListeners('ALL_ADS_COMPLETED');
break;
default:
break;
}
}
onAdError(adErrorEvent) {
// Handle the error logging.
this.adDisplayElement.remove();
if (this.adsManager) {
this.adsManager.destroy();
}
if (this.player.debug) {
throw new Error(adErrorEvent);
}
}
setupAdDisplayContainer() {
const { container } = this.player.elements;
// We assume the adContainer is the video container of the plyr element
// that will house the ads.
this.adDisplayContainer = new window.google.ima.AdDisplayContainer(container);
this.adDisplayElement = container.firstChild;
// The AdDisplayContainer call from google IMA sets the style attribute
// by default. We remove the inline style and set it through the stylesheet.
this.adDisplayElement.removeAttribute('style');
// Set class name on the adDisplayContainer element.
this.adDisplayElement.setAttribute('class', 'plyr__ads');
// Play ads when clicked.
this.setOnClickHandler(this.adDisplayElement, this.playAds);
}
playAds() {
const { container } = this.player.elements;
// Initialize the container. Must be done via a user action on mobile devices.
this.adDisplayContainer.initialize();
try {
// Initialize the ads manager. Ad rules playlist will start at this time.
this.adsManager.init(container.offsetWidth, container.offsetHeight, window.google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules.
this.adsManager.start();
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
this.player.play();
this.adDisplayElement.remove();
if (this.player.debug) {
throw new Error(adError);
}
}
}
/**
* Setup hooks for Plyr and window events. This ensures
* the mid- and post-roll launch at the correct time. And
* resize the advertisement when the player resizes.
*/
setupListeners() {
const { container } = this.player.elements;
let time;
// Add listeners to the required events.
this.player.on('ended', () => {
this.adsLoader.contentComplete();
});
this.player.on('timeupdate', event => {
const { currentTime } = event.detail.plyr;
this.videoElement.currentTime = Math.ceil(currentTime);
});
this.player.on('seeking', event => {
time = event.detail.plyr.currentTime;
return time;
});
this.player.on('seeked', event => {
const seekedTime = event.detail.plyr.currentTime;
for (let i = 0; i < this.adsCuePoints.length; i += 1) {
const cuePoint = this.adsCuePoints[i];
if (time < cuePoint && cuePoint < seekedTime) {
this.adsManager.discardAdBreak();
this.adsCuePoints.splice(i, 1);
}
}
});
// Listen to the resizing of the window. And resize ad accordingly.
window.addEventListener('resize', () => {
this.adsManager.resize(container.offsetWidth, container.offsetHeight, window.google.ima.ViewMode.NORMAL);
});
}
/**
* Handles callbacks after an ad event was invoked.
*/
handleEventListeners(event) {
if (typeof this.events[event] !== 'undefined') {
this.events[event].call(this);
}
}
/**
* Set start event listener on a DOM element and triggers the
* callback when clicked.
* @param {HtmlElment} element - The element on which to set the listener
* @param {Function} callback - The callback which will be invoked once triggered.
*/
setOnClickHandler(element, callback) {
for (let i = 0; i < this.startEvents.length; i += 1) {
const startEvent = this.startEvents[i];
element.addEventListener(
startEvent,
event => {
if ((event.type === 'touchend' && startEvent === 'touchend') || event.type === 'click') {
callback.call(this);
}
},
{ once: true },
);
}
}
/**
* Add event listeners
* @param {string} event - Event type
* @param {function} callback - Callback for when event occurs
*/
on(event, callback) {
this.events[event] = callback;
return this;
}
}

View File

@ -12,6 +12,7 @@ import utils from './utils';
import Console from './console'; import Console from './console';
import Storage from './storage'; import Storage from './storage';
import Ads from './plugins/ads';
import captions from './captions'; import captions from './captions';
import controls from './controls'; import controls from './controls';
@ -273,6 +274,9 @@ class Plyr {
if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) { if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {
ui.build.call(this); ui.build.call(this);
} }
// Setup ads if provided
this.ads = new Ads(this);
} }
// --------------------------------------- // ---------------------------------------

View File

@ -0,0 +1,18 @@
.plyr--ready {
position: relative;
}
.plyr__ads {
bottom: 0;
cursor: pointer;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
left: 0;
position: absolute;
right: 0;
top: 0;
z-index: 10;
video {
left: 0;
}
}

View File

@ -42,3 +42,5 @@
@import 'utils/animation'; @import 'utils/animation';
@import 'utils/hidden'; @import 'utils/hidden';
@import 'plugins/ads/ads';