Some tweaks

This commit is contained in:
ferdiemmen
2018-01-16 23:06:40 +01:00
parent 1cef48d4f8
commit ec73d34bd3
7 changed files with 102 additions and 82 deletions

2
demo/dist/demo.js vendored
View File

@ -1,3 +1,3 @@
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},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/ad_rule_samples&ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&output=vmap&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ar%3Dpremidpostoptimizedpod&cmsid=496&vid=short_onecue&correlator="}});window.player=t;var o=document.querySelectorAll("[data-source]"),i={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;function n(e,t,o){e&&e.classList[o?"add":"remove"](t)}function s(e,a){if(e in i&&(a||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 n(e.parentElement,"active",!1)}),n(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),a&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&s(e.state.type)}),a){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,a,n){e.GoogleAnalyticsObject=r,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,a=t.createElement(o),n=t.getElementsByTagName(o)[0],a.async=1,a.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(a,n)}(window,document,"script",0,"ga"),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},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"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"}});window.player=t;var o=document.querySelectorAll("[data-source]"),i={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},a=window.location.hash.replace("#",""),r=window.history&&window.history.pushState;function n(e,t,o){e&&e.classList[o?"add":"remove"](t)}function s(e,r){if(e in i&&(r||e!==a)&&(a.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"}]}}a=e,Array.from(o).forEach(function(e){return n(e.parentElement,"active",!1)}),n(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),r&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&s(e.state.type)}),r){var c=!a.length;c&&(a=i.video),a in i&&window.history.replaceState({type:a},"",c?"":"#"+a),a!==i.video&&s(a,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,a,r,n){e.GoogleAnalyticsObject=a,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement(o),n=t.getElementsByTagName(o)[0],r.async=1,r.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(r,n)}(window,document,"script",0,"ga"),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview"));
//# sourceMappingURL=demo.js.map //# sourceMappingURL=demo.js.map

File diff suppressed because one or more lines are too long

View File

@ -52,12 +52,7 @@ document.addEventListener('DOMContentLoaded', () => {
google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c', google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c',
}, },
ads: { ads: {
tagUrl: 'https://pubads.g.doubleclick.net/gampad/ads' + tagUrl: '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',
'?sz=640x480&iu=/124319096/external/ad_rule_samples&' +
'ciu_szs=300x250&ad_rule=1&impl=s&gdfp_req=1&env=vp&' +
'output=vmap&unviewed_position_start=1&cust_params=d' +
'eployment%3Ddevsite%26sample_ar%3Dpremidpostoptimiz' +
'edpod&cmsid=496&vid=short_onecue&correlator=',
}, },
}); });

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

@ -18,9 +18,11 @@ const getStartEvents = () => {
return events; return events;
}; };
export default class Ads { class Ads {
constructor(player) { constructor(player) {
this.player = player; this.player = player;
this.isPlaying = false;
this.isInitialized = false;
// Check if a tag URL is provided. // Check if a tag URL is provided.
if (!utils.is.url(player.config.ads.tagUrl)) { if (!utils.is.url(player.config.ads.tagUrl)) {
@ -37,6 +39,22 @@ export default class Ads {
} }
} }
set playing(bool = false) {
this.isPlaying = bool;
}
get playing() {
return this.isPlaying;
}
set initialized(bool = false) {
this.isInitialized = bool;
}
get initialized() {
return this.isInitialized;
}
ready() { ready() {
this.time = Date.now(); this.time = Date.now();
this.startEvents = getStartEvents(); this.startEvents = getStartEvents();
@ -48,7 +66,6 @@ export default class Ads {
this.currentAd = null; this.currentAd = null;
this.events = {}; this.events = {};
this.safetyTimer = null; this.safetyTimer = null;
this.playing = false;
// Setup a simple promise to resolve if the IMA loader is ready. // Setup a simple promise to resolve if the IMA loader is ready.
this.adsLoaderResolve = () => {}; this.adsLoaderResolve = () => {};
@ -91,9 +108,6 @@ export default class Ads {
// Create ads loader. // Create ads loader.
this.adsLoader = new google.ima.AdsLoader(this.adDisplayContainer); this.adsLoader = new google.ima.AdsLoader(this.adDisplayContainer);
// Tell the adsLoader we are handling ad breaks manually.
this.adsLoader.getSettings().setAutoPlayAdBreaks(false);
// Listen and respond to ads loaded and error events. // Listen and respond to ads loaded and error events.
this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);
this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
@ -119,8 +133,8 @@ export default class Ads {
// Get the ads manager. // Get the ads manager.
const settings = new google.ima.AdsRenderingSettings(); const settings = new google.ima.AdsRenderingSettings();
// Tell the SDK NOT to save and restore content video state on our behalf. // Tell the SDK to save and restore content video state on our behalf.
settings.restoreCustomPlaybackStateOnAdBreakComplete = false; settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
settings.enablePreloading = true; settings.enablePreloading = true;
// The SDK is polling currentTime on the contentPlayback. And needs a duration // The SDK is polling currentTime on the contentPlayback. And needs a duration
@ -128,7 +142,7 @@ export default class Ads {
this.adsManager = adsManagerLoadedEvent.getAdsManager(this.player, settings); this.adsManager = adsManagerLoadedEvent.getAdsManager(this.player, settings);
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll. // 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); this.adsCuePoints = this.adsManager.getCuePoints();
// Add listeners to the required events. // Add listeners to the required events.
this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
@ -165,9 +179,9 @@ export default class Ads {
// This event indicates that a mid-roll ad is ready to start. // 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. // We pause the player and tell the adsManager to start playing the ad.
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_BREAK_READY |`, 'Fired when an ad rule or a VMAP ad break would have played if autoPlayAdBreaks is false.'); this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_BREAK_READY |`, 'Fired when an ad rule or a VMAP ad break would have played if autoPlayAdBreaks is false.');
this.handleEventListeners('AD_BREAK_READY'); // this.handleEventListeners('AD_BREAK_READY');
this.adsManager.start(); // this.playing = true;
this.playing = true; // this.adsManager.start();
break; break;
case google.ima.AdEvent.Type.AD_METADATA: case google.ima.AdEvent.Type.AD_METADATA:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_METADATA |`, 'Fired when an ads list is loaded.'); this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] AD_METADATA |`, 'Fired when an ads list is loaded.');
@ -186,9 +200,9 @@ export default class Ads {
// clearInterval(intervalTimer); // clearInterval(intervalTimer);
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] COMPLETE |`, 'Fired when the ad completes playing.'); this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] COMPLETE |`, 'Fired when the ad completes playing.');
this.handleEventListeners('COMPLETE'); this.handleEventListeners('COMPLETE');
this.playing = false;
this.adsDisplayElement.style.display = 'none'; this.adsDisplayElement.style.display = 'none';
this.playing = false;
if (this.player.currentTime < this.player.duration) { if (this.player.currentTime < this.player.duration) {
this.player.play(); this.player.play();
@ -196,13 +210,16 @@ export default class Ads {
break; break;
case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_PAUSE_REQUESTED |`, 'Fired when content should be paused. This usually happens right before an ad is about to cover the content.'); this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_PAUSE_REQUESTED |`, 'Fired when content should be paused. This usually happens right before an ad is about to cover the content.');
this.player.pause();
this.handleEventListeners('CONTENT_PAUSE_REQUESTED'); this.handleEventListeners('CONTENT_PAUSE_REQUESTED');
this.player.pause();
break; break;
case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_RESUME_REQUESTED |`, 'Fired when content should be resumed. This usually happens when an ad finishes or collapses.'); this.player.debug.log(`[${(Date.now() - this.time) / 1000}s][IMA SDK] CONTENT_RESUME_REQUESTED |`, 'Fired when content should be resumed. This usually happens when an ad finishes or collapses.');
this.handleEventListeners('CONTENT_RESUME_REQUESTED'); this.handleEventListeners('CONTENT_RESUME_REQUESTED');
if (this.player.currentTime < this.player.duration) {
this.player.play();
}
break; break;
case google.ima.AdEvent.Type.LOADED: case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to // This is the first event sent for an ad - it is possible to
@ -287,29 +304,8 @@ export default class Ads {
} }
} }
/**
* Destroy the adsManager so we can grab new ads after this.
* If we don't then we're not allowed to call new ads based
* on google policies, as they interpret this as an accidental
* video requests. https://developers.google.com/interactive-
* media-ads/docs/sdks/android/faq#8
*/
cancel() {
this.player.debug.warn(`[${(Date.now() - this.time) / 1000}s][IMA SDK]`, 'Advertisement cancelled.');
// Todo: Removing the ad container might be problematic if we were to recreate the adsManager. Think of playlists. Every new video you need to request a new VAST xml and preload the advertisement.
this.adsDisplayElement.remove();
// Tell our adsManager to go bye bye.
this.adsManagerPromise.then(() => {
if (this.adsManager) {
this.adsManager.destroy();
}
});
}
setupAdDisplayContainer() { setupAdDisplayContainer() {
const { container } = this.player.elements; const { wrapper } = this.player.elements;
// So we can run VPAID2. // So we can run VPAID2.
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
@ -320,9 +316,9 @@ export default class Ads {
// We assume the adContainer is the video container of the plyr element // We assume the adContainer is the video container of the plyr element
// that will house the ads. // that will house the ads.
this.adDisplayContainer = new google.ima.AdDisplayContainer(container); this.adDisplayContainer = new google.ima.AdDisplayContainer(wrapper);
this.adsDisplayElement = container.firstChild; this.adsDisplayElement = wrapper.firstChild;
// The AdDisplayContainer call from google IMA sets the style attribute // The AdDisplayContainer call from google IMA sets the style attribute
// by default. We remove the inline style and set it through the stylesheet. // by default. We remove the inline style and set it through the stylesheet.
@ -337,41 +333,10 @@ export default class Ads {
this.adsManagerPromise, this.adsManagerPromise,
this.adsLoaderPromise, this.adsLoaderPromise,
]).then(() => { ]).then(() => {
this.setOnClickHandler(this.adsDisplayElement, this.playAds); this.setOnClickHandler(this.adsDisplayElement, this.play);
}); });
} }
playAds() {
const { container } = this.player.elements;
// Play the requested advertisement whenever the adsManager is ready.
this.adsManagerPromise.then(() => {
// 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, 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.adsDisplayElement.remove();
if (this.player.debug) {
throw new Error(adError);
}
}
});
}
isPlaying() {
return this.playing;
}
/** /**
* Setup hooks for Plyr and window events. This ensures * Setup hooks for Plyr and window events. This ensures
* the mid- and post-roll launch at the correct time. And * the mid- and post-roll launch at the correct time. And
@ -408,6 +373,62 @@ export default class Ads {
}); });
} }
/**
* Initialize the adsManager and start playing advertisements.
*/
play() {
const { container } = this.player.elements;
// Initialize the container. Must be done via a user action on mobile devices.
this.adDisplayContainer.initialize();
// Play the requested advertisement whenever the adsManager is ready.
this.adsManagerPromise.then(() => {
try {
if (!this.initialized) {
// Initialize the ads manager. Ad rules playlist will start at this time.
this.adsManager.init(container.offsetWidth, container.offsetHeight, 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();
}
this.initialized = true;
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
this.adsDisplayElement.remove();
if (this.player.debug) {
throw new Error(adError);
}
this.player.play();
}
});
}
/**
* Destroy the adsManager so we can grab new ads after this.
* If we don't then we're not allowed to call new ads based
* on google policies, as they interpret this as an accidental
* video requests. https://developers.google.com/interactive-
* media-ads/docs/sdks/android/faq#8
*/
cancel() {
this.player.debug.warn(`[${(Date.now() - this.time) / 1000}s][IMA SDK]`, 'Advertisement cancelled.');
// Todo: Removing the ad container might be problematic if we were to recreate the adsManager. Think of playlists. Every new video you need to request a new VAST xml and preload the advertisement.
this.adsDisplayElement.remove();
// Tell our adsManager to go bye bye.
this.adsManagerPromise.then(() => {
if (this.adsManager) {
this.adsManager.destroy();
}
});
}
/** /**
* Handles callbacks after an ad event was invoked. * Handles callbacks after an ad event was invoked.
*/ */
@ -480,3 +501,6 @@ export default class Ads {
} }
} }
} }
export default Ads;

View File

@ -310,11 +310,12 @@ class Plyr {
*/ */
play() { play() {
if (this.ads) { if (this.ads) {
this.ads.playAds(); this.ads.play();
return this;
} }
return this.media.play(); if (!this.ads.playing) {
return this.media.play();
}
} }
/** /**