diff --git a/dist/feed-media-audio-player.min.js b/dist/feed-media-audio-player.min.js index 366321f6..839d552e 100644 --- a/dist/feed-media-audio-player.min.js +++ b/dist/feed-media-audio-player.min.js @@ -1 +1 @@ -var Feed=function(){"use strict";function t(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function e(t){var e=t.charAt(t.length-1),i=parseInt(t,10),n=new Date;switch(e){case"Y":n.setFullYear(n.getFullYear()+i);break;case"M":n.setMonth(n.getMonth()+i);break;case"D":n.setDate(n.getDate()+i);break;case"h":n.setHours(n.getHours()+i);break;case"m":n.setMinutes(n.getMinutes()+i);break;case"s":n.setSeconds(n.getSeconds()+i);break;default:n=new Date(t)}return n}function i(){return(i=Object.assign||function(t){for(var e=1;e500&&t.history.shift()};r.history=[],r.enable=function(){o=!0},r.reset=function(){var t=r.history;return r.history=[],t};var u=0;function l(t){return t+ ++u}var c=Array.prototype.indexOf;function d(t,e,i,n){"function"==typeof e&&(n=i,i=e,e=!1);var s=i?t.map(i,n):t,a=[],o=[];return s.forEach((function(i,n){var s,r;(e?n&&o[o.length-1]===i:(r=i,null!==(s=o)&&(c&&s.indexOf===c?-1!=s.indexOf(r):s.some((function(t){return t===r})))))||(o.push(i),a.push(t[n]))})),a}function h(t,e){var i=e.map((function(t){return new RegExp(t)}));return d(t).filter((function(t){return i.find((function(e){return e.test(t)}))}))}function p(t,e,i){(t=t?2*t:200)>e&&(t=e),setTimeout((function(){i(t)}),t)}var f="https://feed.fm";function g(){return f}function y(t){f=function(t,e){return"//"===t.slice(0,2)&&(t=!0===e?"https:"+t:!1===e?"http:"+t:"http"===window.location.protocol.substr(0,4)?window.location.protocol+t:"http"),t}(t)}var v,m="undefined"==typeof document,_=null;function P(){return m?_:n("cid")}function S(t){m?_=t:s("cid",t,{expires:3650,path:"/"})}function b(){if(!v)var t=v=new Promise((function(e){!function t(e,i){var n=P();if(n)return e(n);fetch(g()+"/api/v2/client",{method:"POST"}).then((function(t){return t.json()})).then((function(n){n.success?e(n.client_id):p(i,2e3,(function(i){t(e,i)}))})).catch((function(n){if(403===n.status)try{var s=JSON.parse(n.responseText);r("error trying to get client id:",s)}catch(t){r("unknown response for client id request",t.message)}else r("unknown client id response status",n.status);p(i,2e3,(function(i){t(e,i)}))}))}((function(i){v===t?(S(i),e(i)):v?v.then((function(t){e(t)})):b().then((function(t){e(t)}))}))}));return v}var k=P,A=S;function T(t){return(T="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function w(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function O(t,e){for(var i=0;it.length)&&(e=t.length);for(var i=0,n=new Array(e);i=t.length?{done:!0}:{done:!1,value:t[e++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,s,a=!0,o=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return a=t.done,t},e:function(t){o=!0,s=t},f:function(){try{a||null==n.return||n.return()}finally{if(o)throw s}}}}for(var R=Array.prototype.slice,q={on:function(t,e,i){return D(this,"on",t,[e,i])&&e?(this._events||(this._events={}),(this._events[t]||(this._events[t]=[])).push({callback:e,context:i,ctx:i||this}),this):this},once:function(t,e,i){if(!D(this,"once",t,[e,i])||!e)return this;var n,s,a,o=this,r=(n=function(){o.off(t,r),e.apply(this,arguments)},a=!1,function(){return a||(a=!0,s=n.apply(this,arguments),n=null),s});return r._callback=e,this.on(t,r,i)},off:function(t,e,i){var n,s,a,o,r,u,l,c;if(!this._events||!D(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events={},this;for(r=0,u=(o=t?[t]:Object.keys(this._events)).length;r20&&i.play.duration_in_seconds-i.seconds_since_start>20&&(n=15e3)}}else if(i.error&&19===i.error.code)return e._state="music-unavailable",void e.trigger("music-unavailable");e._timeout=setTimeout((function(){e.onTimeout(t)}),n)})).catch((function(i){if(403===i.status)try{var n=JSON.parse(i.responseText);if(n.error&&19===n.error.code){try{e._state="music-unavailable",e.trigger("music-unavailable")}catch(t){}return}console.log("unexpected error:",n)}catch(t){console.log("bad response",t.message)}else console.log("odd response",i);e._timeout=setTimeout((function(){e.onTimeout(t)}),15e3)}))}},{key:"getCurrentState",value:function(){return this._state}},{key:"getCurrentPlay",value:function(){return this._activePlay}}]),t}();function $(){try{return"localStorage"in window&&null!==window.localStorage}catch(t){return!1}}function F(t,e){$()&&localStorage.setItem(t,e)}function J(t){$()&&localStorage.removeItem(t)}function W(t){return $()?localStorage.getItem(t):null}function K(t){var e=W("feedfm:active");if(e){var i=JSON.parse(e);if(i.timestamp+t>Date.now()){var n=parseFloat(W("feedfm:elapsed_time"),10);return[i.state,n]}}return[]}var G=function(t,e,i){Object.assign(this,q),t&&e&&((i=i||{}).baseUrl&&y(i.baseUrl),this.config={remoteLogging:!!i.remoteLogging,formats:"mp3,aac",maxBitrate:128,timeOffset:0,current:null,pendingRequest:null,pendingPlay:null},t&&e&&this.setCredentials(t,e),i.remoteLogging&&(r("remote logging enabled",this.config),this._submitLogHistory()))};G.prototype.setCredentials=function(t,e){this.config.token=t,this.config.secret=e},G.prototype.setStationId=function(t,e,i){if(this.config.stations){var n=""+t,s=""+this.config.stationId!==n;if(s||e){var a=this.config.stations.find((function(t){return""+t.id===n}));a&&(this.config.stationId=t,this.config.station=a,s&&this.trigger("station-changed",t,a),this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0),this._requestNextPlay(0,e,i))}}},G.prototype.setFormats=function(t){this.config.formats=t,this.isTuned()&&this.tune()},G.prototype.setMaxBitrate=function(t){this.config.maxBitrate=t},G.prototype.tune=function(){if(!this.config.token)throw new Error("no token set with setCredentials()");if(!this.config.secret)throw new Error("no secret set with setCredentials()");this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0),this._getDefaultPlacementInformation()},G.prototype._getDefaultPlacementInformation=function(t){var e=this;this.config.placementId&&this.config.placement&&this.config.placement.id===this.config.placementId?this._requestNextPlay():(r("requesting default placement information from server"),e._signedAjax(g()+"/api/v2/session",{method:"POST",body:JSON.stringify({client_id:k()}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).then((function(t){return t.session&&t.session.client_id&&A(t.session.client_id),e._getClientId().then((function(){return t}))})).then(e._receiveDefaultPlacementInformation.bind(e)).catch(e._failedDefaultPlacementInformation.bind(e,t)))},G.prototype._receiveDefaultPlacementInformation=function(t){t&&t.success&&t.placement?(this.config.placement=t.placement,this.config.stations=t.stations,this.config.placementId=t.placement.id,this.trigger("placement",this.config.placement),this.config.stations.length>0&&(this.config.stationId=this.config.stations[0].id,this.config.station=this.config.stations[0],this.trigger("station-changed",this.config.stationId,this.config.station)),this.trigger("stations",this.config.stations),this._requestNextPlay()):this.trigger("music-unavailable")},G.prototype._failedDefaultPlacementInformation=function(t,e){var i=this;if(401===e.status)try{var n=JSON.parse(e.responseText);if(n.error&&5===n.error.code)return void this.trigger("invalid-credentials")}catch(t){}else console.warn("error from placement request",e);t=t?2*t:500,setTimeout((function(){i._getDefaultPlacementInformation(t)}),t)},G.prototype.getActivePlacement=function(){return this.config.placement?this.config.placement:null},G.prototype.getActivePlay=function(){return this.config.current?this.config.current.play:null},G.prototype.isTuned=function(){return this.config.current||this.config.pendingRequest},G.prototype.hasActivePlayStarted=function(){return this.config.current&&this.config.current.started},G.prototype.reportPlayStarted=function(){if(!this.config.current)throw new Error("attempt to report a play started, but there is no active play");this._startPlay(this.config.current.play)},G.prototype.reportPlayElapsed=function(t){if(!this.config.current)throw new Error("attempt to report elapsed play time, but the play hasn't started");this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/elapse",{method:"POST",body:JSON.stringify({seconds:t}),headers:{"Content-Type":"application/json"}}).catch((function(t){return r("server returned error on elapse call. ignoring",t)}))},G.prototype.reportPlayCompleted=function(){if(!this.config.current||!this.config.current.started)throw r("finish on non-active or playing song"),new Error("no active or playing song");this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/complete",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){r("play completed returned error - ignoring",t)})).finally(this._receivePlayCompleted.bind(this))},G.prototype._receivePlayCompleted=function(){if(this.config.pendingRequest)r("song finished, but we're still waiting for next one to return"),this._assignCurrentPlay(null,!0);else{r("song finished, and no outstanding request, so playing pendingPlay");var t=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(t)}},G.prototype.reportPlayStopped=function(t){this.config.current&&this.config.current.started&&this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/elapse",{method:"POST",body:JSON.stringify({seconds:t}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on elapse call. ignoring",t)})),this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0)},G.prototype.requestSkip=function(){var t=this;if(!this.hasActivePlayStarted())throw new Error("No song playing or started");this.config.current.canSkip?this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/skip",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveSkip.bind(this,this.config.current.play)).catch(this._failSkip.bind(this,this.config.current.play)):setTimeout((function(){t.trigger("skip-denied")}),1)},G.prototype.requestInvalidate=function(t){if(t)this.config.current&&this.config.current.play.audio_file.url===t?this._sendInvalidate(this.config.current.play):this.config.pendingPlay&&this.config.pendingPlay.audio_file.url===t&&this._sendInvalidate(this.config.pendingPlay);else{if(!this.config.current)throw new Error("No active song to invalidate!");this._sendInvalidate(this.config.current.play)}},G.prototype._sendInvalidate=function(t,e){this._signedAjax(g()+"/api/v2/play/"+t.id+"/invalidate",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveInvalidate.bind(this,t)).catch(this._failInvalidate.bind(this,e,t))},G.prototype._failInvalidate=function(t,e,i){var n=this;(t=t?2*t:200)<3e3?setTimeout((function(){n._sendInvalidate(e)}),t):r("gave up trying to invalidate play",i)},G.prototype._receiveInvalidate=function(t,e){var i=this;if(r("invalidate response"),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after invalidate"),i._submitLogHistory()}),5e3),e.success)if(this.config.current&&this.config.current.play===t)if(this.config.pendingPlay){r("invalidating to song already queued up");var n=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(n)}else r("invalidating current song"),this._assignCurrentPlay(null,!0),this.config.pendingRequest||(r("queueing up new song"),this._requestNextPlay());else t===this.config.pendingPlay&&(r("invalidated pending play, queueing up new pending play"),this.config.pendingPlay=null,this._requestNextPlay());else r("failed invalidate! - technically this is impossible")},G.prototype._failSkip=function(t){this.config.current&&this.config.current.play===t&&this.trigger("skip-denied")},G.prototype._receiveSkip=function(t,e){if(this.config.current&&this.config.current.play===t){if(!e.success)return r("failed skip!"),void this.trigger("skip-denied");if(this.config.pendingPlay){r("skipping to song already queued up");var i=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(i)}else this.config.pendingRequest?(r("skipping to what is queued up"),this._assignCurrentPlay(null,!0)):(r("skipping to what is queued up"),this._assignCurrentPlay(null))}},G.prototype._startPlay=function(t){this.config.current.retryCount>2?this._receiveStartPlay(t,{success:!0,can_skip:!0}):(r("telling server we're starting the play",t),this._signedAjax(g()+"/api/v2/play/"+t.id+"/start",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveStartPlay.bind(this,t)).catch(this._failStartPlay.bind(this,t)))},G.prototype._receiveStartPlay=function(t,e){e.success?this.config.current&&this.config.current.play===t?(this.config.current.canSkip=e.can_skip,this.config.current.started=!0,this._requestNextPlay(),this.trigger("play-started",t)):r("received start play, but not waiting any more"):r("received failed start success")},G.prototype._failStartPlay=function(t,e){var i=this,n=this;if(r("start failed",e),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after start failure"),n._submitLogHistory()}),5e3),this.config.current&&this.config.current.play===t){if(e&&403===e.status)try{var s=JSON.parse(e.responseText);if(s.error&&20===s.error.code)return this._receiveStartPlay(t,{success:!0,can_skip:!0})}catch(t){r("unable to parse start play response",t.message)}r("request failed - trying again in 1 second",e),this.config.current.retryCount++,setTimeout((function(){i._startPlay(t)}))}else r("startPlay failed, but we don't care any more")},G.prototype._assignCurrentPlay=function(t,e){if(this.config.current){var i=this.config.current.play;this.config.current=null,this.trigger("play-completed",i)}null===t?e?r("nothing to play... waiting"):(r("nothing to play from the current station"),this.trigger("plays-exhausted")):(this.config.current={play:t,canSkip:!1,started:!1,retryCount:0},r("activated new song"),this.trigger("play-active",t))},G.prototype._requestNextPlay=function(t,e,i){var n=this;n._getClientId().then((function(s){if(n.config.pendingRequest){if(t){if(t>6e4)return r("giving up on retrieving next play"),n.config.pendingRequest=null,void(null===n.config.current&&n._assignCurrentPlay(null));r("retrying pending request"),n.config.pendingRequest.retryCount++;var a=n.config.pendingRequest.ajax;return void n._signedAjax(n.config.pendingRequest.url,a).then((function(t){return t.json()})).then(n._receiveNextPlay.bind(n,a)).catch(n._failedNextPlay.bind(n,t,a))}r("already waiting for a request to finish")}else{var o={formats:n.config.formats,client_id:s,max_bitrate:n.config.maxBitrate,secure:!0};n.config.placementId&&(o.placement_id=n.config.placementId),n.config.stationId&&(o.station_id=n.config.stationId),e&&(o.at=e,i&&(o.crossfade=i));var u={method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}};n.config.pendingRequest={url:g()+"/api/v2/play",ajax:u,retryCount:0},r("requesting new play from server",u),n._signedAjax(g()+"/api/v2/play",u).then((function(t){return t.json()})).then(n._receiveNextPlay.bind(n,u)).catch(n._failedNextPlay.bind(n,t,u))}}))},G.prototype._receiveNextPlay=function(t,e){this.config.pendingRequest&&this.config.pendingRequest.ajax===t?(this.config.pendingRequest=null,e.success?(this.trigger("prepare-sound",e.play.audio_file.url,e.play.start_at,e.play.id),this.config.current?(r("received play, but we're already playing, so queueing up",e.play),this.config.pendingPlay=e.play):(r("received play and no current song, making active now",e.play),this._assignCurrentPlay(e.play))):e.error&&9===e.error.code?this.config.current?(r("ran out of music to play, but we're already playing"),this.config.pendingPlay=null):(r("ran out of music, and nothing playing now"),this.trigger("plays-exhausted")):e.error&&6===e.error.code?this.trigger("forbidden",e.error.message):r("unsuccessful response",e)):r("nextPlay succeeded, but we don't care")},G.prototype._failedNextPlay=function(t,e,i){var n=this;if(r("next play failed",i),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after next play failure"),n._submitLogHistory()}),5e3),this.config.pendingRequest&&this.config.pendingRequest.ajax===e){if(i&&403===i.status)try{var s=JSON.parse(i.responseText);if(s.error&&19===s.error.code)return this.trigger("music-unavailable",s.error.message),void this.trigger("not-in-us",s.error.message)}catch(t){r("problem parsing 403 response",t.message)}t=Math.min(t?2*t:500,2e3),r("request failed - trying again after "+t+"ms"),setTimeout((function(){n._requestNextPlay(t)}),t)}else r("nextPlay failed, but we don't care")},G.prototype.canSkipInStation=function(){return!(this.config.station&&!1===this.config.station.can_skip)},G.prototype.maybeCanSkip=function(){return this.canSkip()},G.prototype.canSkip=function(){return!!(this.canSkipInStation()&&this.config.current&&this.config.current.started&&this.config.current.canSkip)},G.prototype.canLike=function(){return!(this.config.station&&!1===this.config.station.can_like)},G.prototype.likePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/like",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on like call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&(this.config.current.play.liked=!0))},G.prototype.unlikePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/like",{method:"DELETE"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on unlike call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&delete this.config.current.play.liked)},G.prototype.dislikePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/dislike",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on invalidate call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&(this.config.current.play.liked=!1))};G.prototype._getStoredCid=function(){return n("cid")},G.prototype._setStoredCid=function(t){s("cid",t,{expires:3650,path:"/"})},G.prototype._deleteStoredCid=function(){a("cid")},G.prototype._sign=function(t){var e;if(t||(t={}),e="Basic "+btoa(this.config.token+":"+this.config.secret),t.headers?t.headers.Authorization=e:t.headers={Authorization:e},t.headers["X-Feed-SDK"]="1.103.0 js",this.extraHeaders)for(var i in this.extraHeaders)this.extraHeaders.hasOwnProperty(i)&&(t.headers[i]=this.extraHeaders[i]);return t},G.prototype._signedAjax=function(t,e){return this._ajax(t,this._sign(e)).then((function(t){if(!t.ok)throw new Error("server returned error "+t.status+": "+t.statusText);return t}))},G.prototype._ajax=function(t,e){return fetch(t,e)},G.prototype._submitLogHistory=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this,i=r.history;if(r.history=[],this.config.remoteLogging)return this._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:i}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).catch((function(){t<2&&setTimeout((function(){r.history=i.concat(["failed log report attempt, try #"+t],r.history),e._submitLogHistory(t+1)}),5e3)}))},G.prototype._submitLogHistory=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this,i=r.history;if(r.history=[],this.config.remoteLogging)return this._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:i}),headers:{"Content-Type":"application/json"}}).catch((function(){t<2&&setTimeout((function(){r.history=i.concat(["failed log report attempt, try #"+t],r.history),e._submitLogHistory(t+1)}),5e3)}))},G.prototype._submitEvent=function(t,e){var i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,s=this;return this._getClientId().then((function(n){return i._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:t,client_id:n,parameters:JSON.stringify(e)}),headers:{"Content-Type":"application/json"}})})).catch((function(){n<2&&setTimeout((function(){r.history=history.concat(["failed event submission, try #"+n],r.history),s._submitLogHistory(n+1)}),5e3)}))},G.prototype._getClientId=function(){return b()};var Y=!1;var Q=function(t){for(var e=t.length,i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;s=this.fading.sound.endPosition/1e3?(this.fading.sound=null,ut(this.fading.audio),this.fading.audio.src=st):this._setVolume(this.fading);else if(e===this.active.audio&&this.active.sound&&!this.active.sound.awaitingPlayResponse){if(this.active.sound.endPosition&&this.active.sound.endPosition/1e3<=e.currentTime){var i=this.active.sound;this.active.sound=null,ut(this.active.audio),this.active.audio.src=st,i.trigger("finish")}else if(this.active.sound.fadeOutEnd&&e.currentTime>=this.active.sound.fadeOutStart){this._setVolume(this.active);var n=this.fading;this.fading=this.active,this.active=n,this.active.sound=null,this.fading.sound.trigger("finish")}else this._setVolume(this.active),this.active.sound.trigger("elapse");this.prepareWhenReady&&this.prepare(this.prepareWhenReady.url,this.prepareWhenReady.startPosition)}},_setVolume:function(t,e){e||(e=t.sound);var i=t.audio.currentTime,n=t.volume,s=e.gainAdjustedVolume(this.vol);e.fadeInStart!==e.fadeInEnd&&i=e.fadeInStart&&i<=e.fadeInEnd?(s=(i-e.fadeInStart)/(e.fadeInEnd-e.fadeInStart)*s,r("ramping \u25b2 volume",{currentTime:i,currentVolume:n,calculatedVolume:s,sound:e})):e.fadeOutStart!==e.fadeOutEnd&&i>e.fadeOutEnd?(s=0,r("post-fade-out volume is 0")):e.fadeOutStart!==e.fadeOutEnd&&i>=e.fadeOutStart&&i<=e.fadeOutEnd&&(s=(1-(i-e.fadeOutStart)/(e.fadeOutEnd-e.fadeOutStart))*s,r("ramping \u25bc volume",{currentTime:i,currentVolume:n,calculatedVolume:s,sound:e})),n!==s&&(rt.IOS?nt||(t.gain.value=s):t.audio.volume=s,t.volume=s)},_debugAudioObject:function(t){for(var e=["abort","load","loadend","loadstart","loadeddata","loadedmetadata","canplay","canplaythrough","seeked","seeking","stalled","timeupdate","volumechange","waiting","durationchange","progress","emptied","ended","play","pause","error"],i=this,n=0;n1&&void 0!==arguments[1]?arguments[1]:0;if(!this.active||!this.active.audio)return et()?(r("pre-loading audio",{url:t}),this._preload(t)):(r("saving url to prepare when audio is initialized",{url:t,startPosition:e}),this.prepareWhenReady={url:t,startPosition:e},!1);var i=this.active.audio.buffered,n=i.length>0&&i.end(i.length-1);return n>=this.active.audio.duration?(r("active song has loaded enough, so preparing",t),et()?this._preload(t):this._prepare(t,e)):this.active.audio.src===st?(r("preparing over silence"),et()?this._preload(t):this._prepare(t,e)):(r("still loading primary, so waiting to do active prepare",{activeUrl:this.active.audio.src,range:n}),this.prepareWhenReady={url:t,startPosition:e},!1)},logState:function(t){for(var e in console.group("speaker: "+(t||"")),this.active?(console.group("active"),console.log("audio.src: ".concat(this.active.audio.src)),console.log("audio.paused: ".concat(this.active.audio.paused)),console.log("sound: ".concat(this.active.sound?this.active.sound.id:"NULL")),console.log("volume: ".concat(this.active.volume)),console.groupEnd(),console.group("preparing"),console.log("audio.src: ".concat(this.preparing.audio.src)),console.log("audio.paused: ".concat(this.preparing.audio.paused)),console.log("sound: ".concat(this.preparing.sound?this.preparing.sound.id:"NULL")),console.log("volume: ".concat(this.preparing.volume)),console.groupEnd(),console.group("fading"),console.log("audio.src: ".concat(this.fading.audio.src)),console.log("audio.paused: ".concat(this.fading.audio.paused)),console.log("sound: ".concat(this.fading.sound?this.fading.sound.id:"NULL")),console.log("volume: ".concat(this.fading.volume)),console.groupEnd()):(console.group("active"),console.log("uninitialized"),console.groupEnd(),console.group("preparing"),console.log("uninitialized"),console.groupEnd(),console.group("fading"),console.log("uninitialized"),console.groupEnd()),console.group("outstanding sounds"),this.outstandingSounds){var i=this.outstandingSounds[e];console.log(i.id+": "+i.url)}console.groupEnd(),console.groupEnd()},_preload:function(t){if(r("preloading!"),this.prepareWhenReady=null,this.preloaded){if(this.preloaded.url===t){var e=!!this.preloaded.blobUrl;return r("preloading",{url:t,preloaded:e}),e}this.preloaded.blobUrl&&(r("revoking previously loaded url",{url:this.preloaded.url}),URL.revokeObjectURL(this.preloaded.blobUrl),this.preloaded=null)}return this.preloaded={url:t,blobUrl:null,responses:[]},this._fetch(t,this.preloaded.responses),!1},_fetch:function(t,e){var i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;r("preload attempt #".concat(n),{url:t});var s={start:(new Date).toString()};e.push(s);var a=function(){if(i.preloaded&&i.preloaded.url===t)return n>i.maxRetries?(r("preload failed to fetch",{url:t,responses:e}),i.preloaded=null,void i.trigger("prepared",t,!1,e)):void setTimeout((function(){return i._fetch(t,e,n+1)}),Math.min(Math.pow(10,n),1e4));r("preload abandoning retry because we have moved on",{url:t})};r("preloading",{url:t,responses:e}),fetch(t).then((function(n){return r("preload got response"),s.end=(new Date).toString(),s.status=n.status,s.text=n.statusText,s.headers=C(n.headers.entries()),"opaque"===n.type?(r("preload opaque response, so retrying"),s.name="OpaqueResponse",s.message="Browser returned oaque response",void a()):n.ok?void n.blob().then((function(n){if(r("preload got blob"),i.preloaded&&i.preloaded.url===t){r("preloaded",{url:t});var s=new Blob([n],{type:"audio/mpeg"});i.preloaded.blobUrl=URL.createObjectURL(s),i.trigger("prepared",t,!0,e)}else r("preload retrieved url, but nobody cares any more")})).catch((function(t){r("preload error blobbing",t,t.name,t.message),s.name=t.name,s.message=t.message,a()})):(r("preload fetch error - retrying"),void a())})).catch((function(t){r("preload error",t,t.name,t.message),s.end=(new Date).toString(),s.name=t.name,s.message=t.message,a()}))},_prepare:function(t,e){return this.prepareWhenReady=null,!!t&&(this.preparing&&this.preparing.audio.src===t&&this.preparing.canplaythrough?(r("play already prepared!"),!0):(this.preparing.audio.src!==t&&(r("preparing",t),this.preparing.audio.playing&&this.preparing.audio.pause(),this.preparing.canplaythrough=!1,ut(this.preparing.audio),this.preparing.audio.src=t),e&&this.preparing.audio.currentTime!==e&&(r("advancing preparing audio to",e/1e3),this.preparing.audio.currentTime=e/1e3),!1))},_playSound:function(t){var e=this,i=this;if(this.active&&this.active.audio)if(this.active.sound!==t){this.preloaded&&this.preloaded.url===t.url&&this.preloaded.blobUrl?(r(t.id+" using preloaded audio",this.preloaded),this.preparing.audio.playing&&this.preparing.audio.pause(),t.responses=this.preloaded.responses,ut(this.preparing.audio),this.preparing.audio.src=this.preloaded.blobUrl,this.preparing.canplaythrough=!0,this.preloaded=null):this.preparing.audio.src!==t.url&&this._prepare(t.url,t.startPosition);var n=this.active;if(this.active=this.preparing,this.preparing=n,this.preparing.canplaythrough=!1,ut(this.preparing.audio),this.preparing.audio.src=st,this.active.sound=null,this._setVolume(this.active,t),this.preparing.sound){var s=this.preparing.sound;this.preparing.sound=null,s.trigger("finish")}t.awaitingPlayResponse=!0,this.active.sound=t;var a=this.active,o=1;!function n(){r(t.id+" initiating play()",{attempt:o}),e.active.audio.play().then((function(){if(delete t.awaitingPlayResponse,!i.outstandingSounds[t.id])return r(t.id+" play() succeeded, but sound has been destroyed"),void(a.audio&&a.audio.src===t.url&&(r(t.id+" being paused and unloaded"),a.audio.pause(),ut(a.audio),a.audio.src=st));r(t.id+" play() succeeded"),t.fadeOutSeconds&&0===t.fadeOutEnd&&(t.fadeOutStart=a.audio.duration-t.fadeOutSeconds,t.fadeOutEnd=a.audio.duration),t.startPosition&&(r("updating start position"),a.audio.currentTime=t.startPosition/1e3,r("updated"));var e=a.audio.paused;t.trigger("play"),a.pauseAfterPlay?a.audio.pause():e&&t.trigger("pause")})).catch((function(e){r("error starting playback with sound "+t.id,{name:e.name,message:e.message,attempt:o}),o<4?(o++,setTimeout(n,10)):t.trigger("finish",e)}))}()}else this.active.audio.paused?(r(t.id+" was paused, so resuming"),this.active.audio.play().then((function(){r("resumed playback"),t.trigger("play")})).catch((function(e){r("error resuming playback",e.name,e.message,e.stack,t.id),i.active.sound=null,t.trigger("finish")})),this.fading.sound&&this.fading.audio.play().then((function(){r("resumed fading playback")})).catch((function(e){r("error resuming fading playback",e.name,e.message,e.stack,t.id),i.fading.sound=null,ut(i.fading.audio),i.fading.audio.src=st}))):r(t.id+" is already playing");else console.error("**** player.initializeAudio() *** not called before playback!")},_destroySound:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(t.off(),this.active&&this.active.sound===t)if(e&&t.fadeOutSeconds){r("destroy triggered for current sound (with fadeout)",t.id);var i=this.active.audio;t.fadeOutStart=i.currentTime,t.endPosition?(t.fadeOutEnd=Math.min(i.currentTime+t.fadeOutSeconds,t.endPosition/1e3),t.endPosition=Math.min(1e3*t.fadeOutEnd,t.endPosition)):(t.fadeOutEnd=i.currentTime+t.fadeOutSeconds,t.endPosition=1e3*t.fadeOutEnd),this._setVolume(this.active);var n=this.fading;this.fading=this.active,this.active=n,this.active.sound=null}else r("destroy triggered for current sound (no fadeout)",t.id),this.active.audio.pause(),ut(this.active.audio),this.active.audio.src=st;else r("destroy triggered for inactive sound",t.id);delete this.outstandingSounds[t.id]},flush:function(){for(var t in this.outstandingSounds)this.outstandingSounds[t].destroy()},_pauseSound:function(t){this.active&&t===this.active.sound&&(t.awaitingPlayResponse?this.active.pauseAfterPlay=!0:this.active.audio.pause()),this.fading&&this.fading.audio&&this.fading.audio.pause()},_position:function(t){return this.active&&t===this.active.sound?Math.floor(1e3*this.active.audio.currentTime):0},_duration:function(t){if(t===this.active.sound){var e=this.active.audio.duration;return isNaN(e)?0:Math.floor(1e3*e)}return 0},setVolume:function(t){return void 0!==t&&(this.vol=t,this.active&&this.active.sound&&this._setVolume(this.active),this.trigger("volume",t)),this.vol},getVolume:function(){return this.vol}},Object.assign(rt.prototype,q);var ct=function(t,e,i){var n=this;if(e){(i=i||{}).maxRetries=i.maxRetries||10,this.options=i,this.state={paused:!0,simulcast:i.simulcast},i.debug&&r.enable(),this.trimming=!1!==i.trimming,this.normalizeVolume=!("normalizeVolume"in i)||i.normalizeVolume,this.resumable=!("resumable"in i)||i.resumable,this.secondsOfCrossfade=i.secondsOfCrossfade||0,this.crossfadeIn=!!i.crossfadeIn,this.serverAssignedCrossfade=!1,this._stationsPromise=new Promise((function(t,e){n._stationsResolve=t,n._stationsReject=e}));var s=this.speaker=new rt({maxRetries:i.maxRetries}),a=this.session=new G(t,e,i);if(i.brokenWebkitFormats&&rt.brokenWebkit){var o=i.brokenWebkitFormats.split(","),u=s.getSupportedFormats().split(","),l=h(o,u),c=l.join(",");r("input format list is",o,u),r("final support list is",c),0===l.length&&(c=s.getSupportedFormats()),a.setFormats(c)}else if(i.formats){var d=i.formats.split(","),p=s.getSupportedFormats().split(","),f=h(d,p),g=f.join(",");0===f.length&&(g=s.getSupportedFormats()),r("input format list is",d,p),r("final support list is",g),a.setFormats(g)}else a.setFormats(s.getSupportedFormats())}else this._restore(t);Object.assign(this,q),this.session.on("play-active",this._onPlayActive,this),this.session.on("play-started",this._onPlayStarted,this),this.session.on("play-completed",this._onPlayCompleted,this),this.session.on("plays-exhausted",this._onPlaysExhausted,this),this.session.on("prepare-sound",this._onPrepareSound,this),this.session.on("placement",this._onPlacement,this),this.session.on("stations",this._onStations,this),this.session.on("station-changed",this._onStationChanged,this);for(var y=this,v=function(){var t=_[m];n.session.on(t,(function(){y.trigger.apply(y,[t].concat(Array.prototype.slice.call(arguments,0)))}))},m=0,_=["music-unavailable","not-in-us","invalid-credentials","skip-denied","play-active","forbidden"];m<_.length;m++)v();this.setMuted(this.isMuted())};ct.prototype._persist=function(){var t=dt(this.state);return t.activePlay&&(t.activePlay=dt(t.activePlay),delete t.activePlay.sound),{state:t,options:this.options,trimming:this.trimming,normalizeVolume:this.normalizeVolume,secondsOfCrossfade:this.secondsOfCrossfade,serverAssignedCrossfade:this.serverAssignedCrossfade,crossfadeIn:this.crossfadeIn,sessionConfig:this.session.config}},ct.prototype._restore=function(t){var e=this,i=t.persisted,n=t.elapsed;i.options.debug&&r.enable(),r("restoring!");var s=i.sessionConfig,a=s.current;s.current=null,s.pendingRequest=null,s.pendingPlay=null,this.session=new G,this.session.config=s,this.options=i.options,this.speaker=new rt({maxRetries:this.options.maxRetries}),this.state={paused:!0,simulcast:this.options.simulcast},this.trimming=i.trimming,this.normalizeVolume=i.normalizeVolume,this.resumable=!0,this.secondsOfCrossfade=i.secondsOfCrossfade,this.serverAssignedCrossfade=i.serverAssignedCrossfade,this.crossfadeIn=i.crossfadeIn,this._stationsPromise=new Promise((function(t,i){e._stationsResolve=t,e._stationsReject=i})),this.tune=function(){var t=this;return Promise.resolve(!0).then((function(){t._station=i.sessionConfig.station,t._stations=i.sessionConfig.stations,t._placement=i.sessionConfig.placement,t._stationsResolve(i._stations),t.trigger("placement",t._placement),t.trigger("station-changed",t._station),t.trigger("stations",t._stations),t.session.config.current=a,t.session.config.current.started=!1;var e=t.session.config.current.play;e.start_at=n/1e3,t.session.trigger("play-active",e),t.session.config.current.started=!0,t.state.paused=!1,t.session.trigger("play-started",e,!0),t.state.paused=!0,t.trigger("play-paused",e,!0)})).then((function(){return t._stationsPromise}))}},ct.prototype.initializeAudio=function(){r("INTIALIZE AUDIO"),this.speaker.initializeAudio()},ct.prototype._onPlacement=function(t){this._placement=t,t.options&&t.options.crossfade_seconds&&(this.secondsOfCrossfade=t.options.crossfade_seconds,this.serverAssignedCrossfade=!0),this.trigger("placement",t)},ct.prototype._onStations=function(t){this._stations=t,this._stationsResolve(t),this.trigger("stations",t)},ct.prototype._onStationChanged=function(t,e){this._station=e,this.serverAssignedCrossfade&&e.options&&"crossfade_seconds"in e.options?this.secondsOfCrossfade=e.options.crossfade_seconds:this.serverAssignedCrossfade&&this._placement.options&&"crossfade_seconds"in this._placement.options&&(this.secondsOfCrossfade=this._placement.options.crossfade_seconds),this.trigger("station-changed",t,e)},ct.prototype.setStationId=function(t,e){var i,n=!1;!0===e?(n=e,r("SET STATION ID (WITH FADE)",t)):e?r("SET STATION ID (WITH ADVANCE)",t,i=e):r("SET STATION ID",t),n&&this.state.activePlay&&(this.state.activePlay.fadeOnDestroy=!0),this.session.setStationId(t,i,this.crossfadeIn)},ct.prototype._onPlayActive=function(t){var e={play:this._onSoundPlay.bind(this,t.id),pause:this._onSoundPause.bind(this,t.id),finish:this._onSoundFinish.bind(this,t.id),elapse:this._onSoundElapse.bind(this,t.id)};this.normalizeVolume&&(e.gain=(t.audio_file.replaygain_track_gain||0)+(t.station.pre_gain||0)),t.start_at?e.startPosition=1e3*t.start_at:this.trimming&&t.audio_file.extra&&t.audio_file.extra.trim_start&&(e.startPosition=1e3*t.audio_file.extra.trim_start),this.trimming&&t.audio_file.extra&&t.audio_file.extra.trim_end&&t.audio_file.duration_in_seconds&&(e.endPosition=1e3*(t.audio_file.duration_in_seconds-t.audio_file.extra.trim_end)),this.secondsOfCrossfade&&(this.crossfadeIn&&(e.fadeInSeconds=this.secondsOfCrossfade),e.fadeOutSeconds=this.secondsOfCrossfade);var i=this.speaker.create(t.audio_file.url,e);(this.state.activePlay={id:t.id,sound:i,startReportedToServer:!1,soundCompleted:!1,playStarted:!1,fadeOnDestroy:!1,previousPosition:0},this.state.paused)||this.state.activePlay.sound.play()},ct.prototype._onSoundPlay=function(t){if(this.state.activePlay&&this.state.activePlay.id===t){this.state.paused=!1;var e=this.state.activePlay.playStarted;if(this.state.activePlay.playStarted=!0,!this.state.activePlay.startReportedToServer)return this.resumable&&function(t){var e=Date.now(),i=JSON.stringify({state:t,timestamp:e}),n=Date.now();F("feedfm:active",i);var s=Date.now();F("feedfm:elapsed_time","0"),r("persisted state",{timestamp:e,encodingTime:n-e,storageTime:s-n,state:t})}(this._persist()),this.session.reportPlayStarted();e&&this.trigger("play-resumed",this.session.getActivePlay())}else r("received sound play, but active play does not match",this.state.activePlay,t)},ct.prototype.getActivePlay=function(){return this.session.getActivePlay()},ct.prototype.hasActivePlayStarted=function(){return this.session.hasActivePlayStarted()},ct.prototype.getActivePlacement=function(){return this.session.getActivePlacement()},ct.prototype._onSoundPause=function(t){this.state.activePlay&&this.state.activePlay.id===t?(this.state.paused=!0,this.trigger("play-paused",this.session.getActivePlay())):r("received sound pause, but active play does not match",this.state.activePlay,t)},ct.prototype._onSoundFinish=function(t,e){if(this.state.activePlay&&this.state.activePlay.id===t){var i=this.state.activePlay.sound;return this.state.activePlay.soundCompleted=!0,e&&(this.session._submitEvent("playback-error",{url:i.url,responses:i.responses,error:e,play_id:t}),this.state.activePlay.soundCompletedWithError=!0,"NotAllowedError"===e.name)?(console.error('Feed.fm: first call to "initializeAudio()" or "play()" must be made in user-initiated event handler'),void this.stop()):this.state.activePlay.playStarted?void(this.state.activePlay.startReportedToServer&&(e?(r("song completed with error - marking as invalid",e),this.trigger("invalidated",t),this.session.requestInvalidate()):this.session.reportPlayCompleted())):(this.trigger("invalidated",t),void this.session.requestInvalidate())}r("received sound finish, but active play does not match",this.state.activePlay,t)},ct.prototype._onSoundElapse=function(t){if(this.state.activePlay&&this.state.activePlay.id===t){var e=this.state.activePlay.sound.position(),i=Math.floor(this.state.activePlay.previousPosition/3e4),n=Math.floor(e/3e4);this.resumable&&F("feedfm:elapsed_time",e.toString()),this.state.activePlay.previousPosition=e,n!==i&&this.session.reportPlayElapsed(Math.floor(e/1e3))}else r("received sound elapse, but active play does not match",this.state.activePlay,t)},ct.prototype._onPlayStarted=function(t){var e=this,i=this.session;this.state.activePlay&&this.state.activePlay.id===t.id?(this.state.activePlay.startReportedToServer=!0,this.state.activePlay.soundCompleted&&(r("sound completed before we finished reporting start",this.state.activePlay),this.state.activePlay.soundCompletedWithError?setTimeout((function(){e.trigger("invalidated",t.id),i.requestInvalidate()}),1):setTimeout((function(){return i.reportPlayCompleted()}),1)),this.updateSimulcast(),this.trigger("play-started",t)):r("received play started, but it does not match active play",t,this.state.activePlay)},ct.prototype._onPlayCompleted=function(t){if(this.state.activePlay&&this.state.activePlay.id===t.id){this.state.activePlay.sound.destroy(this.state.activePlay.fadeOnDestroy);var e=this.state.activePlay.playStarted;delete this.state.activePlay,e&&this.trigger("play-completed",t)}else r("received play completed, but it does not match active play",t,this.state.activePlay)},ct.prototype._onPlaysExhausted=function(){this.state.paused||(this.state.paused=!1,this.updateSimulcast(),this.trigger("plays-exhausted"))},ct.prototype._onPrepareSound=function(t,e,i){var n=this;r("preparing sound",t,e),this.speaker.prepare(t,1e3*e),this.speaker.once("prepared",(function(e,s,a){if(t===e){a&&a.length>1&&n.session._submitEvent("preload-error",{url:t,play_id:i,responses:a});var o=n.session.getActivePlay();s||o&&o.id===i||n.session.requestInvalidate(t)}}))},ct.prototype.isPaused=function(){return this.session.isTuned()&&this.state.paused},ct.prototype.tune=function(){return r("TUNE"),this.session.isTuned()||this.session.tune(),this._stationsPromise},ct.prototype.prepare=function(){return r("PREPARE"),this.speaker.initializeAudio(),this._prepare()},ct.prototype._prepare=function(){var t=this,e=this.state.activePlay;if(e){var i=e.sound.url;return this.speaker.prepare(i,e.sound.startPosition)?Promise.resolve(!0).then((function(){r("already prepared"),t.trigger("prepared")})):new Promise((function(n){r("waiting for un/prepared event"),t.speaker.once("prepared",(function(s,a,o){o&&o.length>1&&t.session._submitEvent("preload-error",{url:s,play_id:e.id,responses:o}),s===i&&(a?(t.trigger("prepared"),n(!0)):(t.session.requestInvalidate(),t.session.once("play-active",(function(){t._prepare().then((function(t){return n(t)}))}))))}))}))}return new Promise((function(e){t.session.once("play-active",(function(){t._prepare().then((function(t){return e(t)}))})),t.session.isTuned()||(r("tuning"),t.session.tune())}))},ct.prototype.play=function(){r("PLAY");var t=this.session,e=this.state;if(this.speaker.initializeAudio(),!t.isTuned())return e.paused=!1,t.tune();t.getActivePlay()&&e.activePlay&&e.paused&&(e.activePlay.playStarted?e.activePlay.sound.resume():e.activePlay.sound.play()),e.paused=!1,this.updateSimulcast()},ct.prototype.pause=function(){r("PAUSE"),this.session.hasActivePlayStarted()&&this.state.activePlay&&!this.state.paused&&(this.state.activePlay.sound.pause(),this.state.paused=!0,this.updateSimulcast())},ct.prototype.canLike=function(){return this.session.canLike()},ct.prototype.like=function(){r("LIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.likePlay(this.state.activePlay.id),this.trigger("play-liked"))},ct.prototype.unlike=function(){r("UNLIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.unlikePlay(this.state.activePlay.id),this.trigger("play-unliked"))},ct.prototype.dislike=function(){r("DISLIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.dislikePlay(this.state.activePlay.id),this.trigger("play-disliked"),this.state.paused=!1,this.skip())},ct.prototype.skip=function(){r("SKIP"),this.session.hasActivePlayStarted()&&this.session.canSkipInStation()&&(this.state.paused=!1,this.session.requestSkip())},ct.prototype.stop=function(){r("STOP"),J("feedfm:active"),J("feedfm:elapsed_time"),this.state.paused=!0;var t=this.state.activePlay;if(t&&t.sound){if(r("stopping active play",t),t.startReportedToServer){var e=t.sound.position();this.session.reportPlayStopped(Math.floor(e/1e3))}t.sound.pause(),t.sound.destroy()}else r("no active play");delete this.state.activePlay,this.speaker.flush(),this.trigger("play-stopped"),this.updateSimulcast()},ct.prototype.destroy=function(){this.session=null,this.state.activePlay&&this.state.activePlay.sound&&this.state.activePlay.sound.destroy()},ct.prototype.getCurrentState=function(){return this.session.hasActivePlayStarted()?this.state.paused?"paused":"playing":"idle"},ct.prototype.getPosition=function(){return this.state.activePlay&&this.state.activePlay.sound?this.state.activePlay.sound.position():0},ct.prototype.getDuration=function(){return this.state.activePlay&&this.state.activePlay.sound?this.state.activePlay.sound.duration():0},ct.prototype.canSkip=function(){return this.session.canSkip()},ct.prototype.maybeCanSkip=function(){return this.canSkip()};function dt(t){return null===t?null:Object.assign({},t)}ct.prototype.isMuted=function(){return!(!lt()||!("muted"in localStorage))&&"true"===localStorage.muted},ct.prototype.setMuted=function(t){t?(this.speaker.setVolume(0),lt()&&(localStorage.muted=!0),this.trigger("muted")):(this.speaker.setVolume(100),lt()&&(localStorage.muted=!1),this.trigger("unmuted"))},ct.prototype.getVolume=function(){return this.speaker.getVolume()},ct.prototype.setVolume=function(t){this.speaker.setVolume(t)},ct.prototype.getStations=function(){return this._stationsPromise},ct.prototype.updateSimulcast=function(){var t=this;if(this.state.simulcast){var e=this.getCurrentState();b().then((function(i){t.session._signedAjax(g()+"/api/v2/simulcast/".concat(t.state.simulcast,"/in-progress"),{method:"POST",body:JSON.stringify({state:e,client_id:i}),headers:{"Content-Type":"application/json"}})}))}},window.NodeList&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=function(t,e){e=e||window;for(var i=0;i"+t.audio_file.track.title+" by "+t.audio_file.artist.name+" on "+t.audio_file.release.title+""},ht.prototype.renderStatus=function(t){var e=this;void 0!==t&&(this.displayText=t),this.alertId||this.$el.querySelectorAll(".status").forEach((function(t){t.innerHTML=e.displayText,t.classList.remove("alert")}))},ht.prototype.renderPosition=function(t,e){if(this.$el.querySelectorAll(".elapsed").forEach((function(e){e.innerHTML=pt(t)})),this.$el.querySelectorAll(".duration").forEach((function(t){t.innerHTML=pt(e)})),0===e)this.$el.querySelectorAll(".progress").forEach((function(t){t.style.width="0"}));else{var i=Math.round((t+1e3)/e*100);i=i>100?100:i,this.$el.querySelectorAll(".progress").forEach((function(t){t.style.width=i+"%"}))}},ht.prototype.renderAlert=function(t){this.alertId&&window.clearTimeout(this.alertId),this.$el.querySelectorAll(".status").forEach((function(e){e.innerHTML=t,e.classList.add("alert")}));var e=this;this.alertId=window.setTimeout((function(){e.alertId=null,e.renderStatus()}),3e3)},ht.prototype._onSuspend=function(){this._enableButtonsBasedOnState()},ht.prototype._enableButtonsBasedOnState=function(){var t,e,i=this.player.getCurrentState();switch(i){case"playing":t=[".pause-button"],e=[".play-button",".start-button",".resume-button"],this.player.canLike()?t.push(".dislike-button",".like-button"):e.push(".dislike-button",".like-button"),this.player.canSkip()?t.push(".skip-button"):e.push(".skip-button");break;case"paused":t=[".play-button",".resume-button"],e=[".pause-button",".start-button"],this.player.canLike()?t.push(".dislike-button",".like-button"):e.push(".dislike-button",".like-button"),this.player.canSkip()?t.push(".skip-button"):e.push(".skip-button");break;default:t=[".play-button",".start-button"],e=[".resume-button",".pause-button",".like-button",".dislike-button",".skip-button"]}var n,s=j(e);try{for(s.s();!(n=s.n()).done;){var a=n.value;this.$el.querySelectorAll(a).forEach((function(t){t.classList.remove("button-enabled"),t.classList.add("button-disabled"),t.disabled=!0}))}}catch(t){s.e(t)}finally{s.f()}var o,r=j(t);try{for(r.s();!(o=r.n()).done;){var u=o.value;this.$el.querySelectorAll(u).forEach((function(t){t.classList.remove("button-disabled"),t.classList.add("button-enabled"),t.disabled=!1}))}}catch(t){r.e(t)}finally{r.f()}var l=this.$el.classList;l.remove("state-playing"),l.remove("state-paused"),l.remove("state-idle"),l.add("state-"+i)};var ft=function(){function t(e){w(this,t),Object.assign(this,q),this._speaker=new rt,this._uuid=e,this._state="idle",this._activePlay=null,this._activeSound=null,this._metadataTimeout=null,this._tryingToPlay=!1,this._retries=0}return E(t,[{key:"initializeAudio",value:function(){r("INTIALIZE AUDIO"),this._speaker.initializeAudio()}},{key:"connect",value:function(){if(r("CONNECT to ".concat(this._uuid)),this._tryingToPlay)r("ignoring pointless connect to ".concat(this._uuid));else if("idle"===this._state){this._tryingToPlay=!0,this._speaker.initializeAudio(),this._setState("connecting");var t=new URL(g());this._streamUrl="https://cast."+t.hostname+"/"+this._uuid,this._requestStream()}else r("ignoring connect() since we're already connected")}},{key:"_onSoundPlay",value:function(){var t=this;r("sound play!"),this._retries=0,this._lastElapsedAt=Date.now(),"connecting"===this._state?(this._setState("connected"),fetch(this._streamUrl+"/play?elapsed="+this._elapsed).then((function(t){return t.json()})).then((function(e){e.success?(t._activePlay=e.play,t.trigger("play-started",t._activePlay),t._scheduleMetadataTimeout()):t._scheduleMetadataTimeout(3e3)})).catch((function(){t._scheduleMetadataTimeout(2e3)}))):this._metadataTimeout||this._scheduleMetadataTimeout()}},{key:"_scheduleMetadataTimeout",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;this._cancelMetadataTimeout(),this._metadataTimeout=setTimeout((function(){t._onMetadataTimeout()}),e)}},{key:"_cancelMetadataTimeout",value:function(){this._metadataTimeout&&clearTimeout(this._metadataTimeout),this._metadataTimeout=null}},{key:"_onSoundElapse",value:function(){if(this._activeSound){var t=this._elapsed;(this._elapsed=this._activeSound.position())-t>0&&(this._lastElapsedAt=Date.now())}}},{key:"_requestStream",value:function(){r("requesting stream"),this._tryingToPlay&&(this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._cancelMetadataTimeout(),this._activePlay=null,this._activeSound=this._speaker.create(this._streamUrl,{play:this._onSoundPlay.bind(this),finish:this._onSoundFinish.bind(this),elapse:this._onSoundElapse.bind(this)}),this._activeSound.play(),this._elapsed=0,this._lastElapsedAt=Date.now())}},{key:"_onMetadataTimeout",value:function(){var t=this;this._cancelMetadataTimeout(),fetch(this._streamUrl+"/play?elapsed="+this._elapsed).then((function(t){return t.json()})).then((function(e){e.success&&(null===e.play&&null!==t._activePlay||null!==e.play&&null===t._activePlay||null!==e.play&&null!==t._activePlay&&e.play.audio_file.id!==t._activePlay.audio_file.id)&&(t._activePlay=e.play,r("current play updated",t._activePlay),t.trigger("play-started",t._activePlay)),t._scheduleMetadataTimeout();var i=Date.now()-t._lastElapsedAt;i>8e3&&(r("stream has not advanced for ".concat(i," ms, so reconnecting"),t.toObject()),t._requestStream())})).catch((function(){var e=Date.now()-t._lastElapsedAt;e>8e3?(r("stream has not advanced for ".concat(e," ms, so reconnecting"),t.toObject()),t._requestStream()):t._scheduleMetadataTimeout()}))}},{key:"_onSoundFinish",value:function(t){var e=this;r("sound finished",this.toObject()),"connecting"===this._state&&t?(this._tryingToPlay=!1,this._setState("music-unavailable"),this.trigger("music-unavailable")):(r("reconnecting after stream ended",t),this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._cancelMetadataTimeout(),this._activePlay=null,this._retries+=1,setTimeout((function(){e._tryingToPlay&&(r("retrying connection after stream ended"),e._requestStream())}),Math.pow(2,this._retries))),this._logEvents()}},{key:"disconnect",value:function(){r("DISCONNECT",this.toObject()),this._tryingToPlay&&(this._tryingToPlay=!1,this._activePlay=null,this._elapsed=0,this._cancelMetadataTimeout(),this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._setState("idle"),this._logEvents())}},{key:"getVolume",value:function(){return this._speaker.getVolume()}},{key:"setVolume",value:function(t){this._speaker.setVolume(t)}},{key:"_setState",value:function(t){this._state!==t&&(r("state transition ".concat(this._state," -> ").concat(t)),this._state=t,this.trigger("state-changed",this._state))}},{key:"getCurrentState",value:function(){return this._state}},{key:"getCurrentPlay",value:function(){return this._activePlay}},{key:"_logEvents",value:function(){var t=r.reset();return fetch(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:t}),headers:{"Content-Type":"application/json","X-Feed-SDK":"1.103.0 js"}})}},{key:"toObject",value:function(){return{state:this._state,activePlay:this._activePlay,uuid:this._uuid,metadataTimeoutIsNull:null===this._metadataTimeout,tryingToPlay:this._tryingToPlay,elapsed:this._elapsed,retries:this._retries}}},{key:"toString",value:function(){return JSON.stringify(this.toString())}}]),t}();return{Speaker:rt,Session:G,Player:ct,Listener:H,PlayerView:ht,SimulcastPlayer:ft,log:r,version:"1.103.0",resetClientId:function(){m?_=null:a("cid"),v=null},getClientId:b,setBaseUrl:y,resumable:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:4e3,e=K(t);if(2===e.length){var i=I(e,2),n=i[0],s=i[1],a=new ct({persisted:n,elapsed:s});return a}return null}}}(); +var Feed=function(){"use strict";function t(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function e(t){var e=t.charAt(t.length-1),i=parseInt(t,10),n=new Date;switch(e){case"Y":n.setFullYear(n.getFullYear()+i);break;case"M":n.setMonth(n.getMonth()+i);break;case"D":n.setDate(n.getDate()+i);break;case"h":n.setHours(n.getHours()+i);break;case"m":n.setMinutes(n.getMinutes()+i);break;case"s":n.setSeconds(n.getSeconds()+i);break;default:n=new Date(t)}return n}function i(){return(i=Object.assign||function(t){for(var e=1;e500&&t.history.shift()};r.history=[],r.enable=function(){o=!0},r.reset=function(){var t=r.history;return r.history=[],t};var u=0;function l(t){return t+ ++u}var c=Array.prototype.indexOf;function d(t,e,i,n){"function"==typeof e&&(n=i,i=e,e=!1);var s=i?t.map(i,n):t,a=[],o=[];return s.forEach((function(i,n){var s,r;(e?n&&o[o.length-1]===i:(r=i,null!==(s=o)&&(c&&s.indexOf===c?-1!=s.indexOf(r):s.some((function(t){return t===r})))))||(o.push(i),a.push(t[n]))})),a}function h(t,e){var i=e.map((function(t){return new RegExp(t)}));return d(t).filter((function(t){return i.find((function(e){return e.test(t)}))}))}function p(t,e,i){(t=t?2*t:200)>e&&(t=e),setTimeout((function(){i(t)}),t)}var f="https://feed.fm";function g(){return f}function y(t){f=function(t,e){return"//"===t.slice(0,2)&&(t=!0===e?"https:"+t:!1===e?"http:"+t:"http"===window.location.protocol.substr(0,4)?window.location.protocol+t:"http"),t}(t)}var v,m="undefined"==typeof document,_=null;function P(){return m?_:n("cid")}function S(t){m?_=t:s("cid",t,{expires:3650,path:"/"})}function b(){if(!v)var t=v=new Promise((function(e){!function t(e,i){var n=P();if(n)return e(n);fetch(g()+"/api/v2/client",{method:"POST"}).then((function(t){return t.json()})).then((function(n){n.success?e(n.client_id):p(i,2e3,(function(i){t(e,i)}))})).catch((function(n){if(403===n.status)try{var s=JSON.parse(n.responseText);r("error trying to get client id:",s)}catch(t){r("unknown response for client id request",t.message)}else r("unknown client id response status",n.status);p(i,2e3,(function(i){t(e,i)}))}))}((function(i){v===t?(S(i),e(i)):v?v.then((function(t){e(t)})):b().then((function(t){e(t)}))}))}));return v}var k=P,A=S;function T(t){return(T="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function w(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function O(t,e){for(var i=0;it.length)&&(e=t.length);for(var i=0,n=new Array(e);i=t.length?{done:!0}:{done:!1,value:t[e++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,s,a=!0,o=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return a=t.done,t},e:function(t){o=!0,s=t},f:function(){try{a||null==n.return||n.return()}finally{if(o)throw s}}}}for(var R=Array.prototype.slice,q={on:function(t,e,i){return D(this,"on",t,[e,i])&&e?(this._events||(this._events={}),(this._events[t]||(this._events[t]=[])).push({callback:e,context:i,ctx:i||this}),this):this},once:function(t,e,i){if(!D(this,"once",t,[e,i])||!e)return this;var n,s,a,o=this,r=(n=function(){o.off(t,r),e.apply(this,arguments)},a=!1,function(){return a||(a=!0,s=n.apply(this,arguments),n=null),s});return r._callback=e,this.on(t,r,i)},off:function(t,e,i){var n,s,a,o,r,u,l,c;if(!this._events||!D(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events={},this;for(r=0,u=(o=t?[t]:Object.keys(this._events)).length;r20&&i.play.duration_in_seconds-i.seconds_since_start>20&&(n=15e3)}}else if(i.error&&19===i.error.code)return e._state="music-unavailable",void e.trigger("music-unavailable");e._timeout=setTimeout((function(){e.onTimeout(t)}),n)})).catch((function(i){if(403===i.status)try{var n=JSON.parse(i.responseText);if(n.error&&19===n.error.code){try{e._state="music-unavailable",e.trigger("music-unavailable")}catch(t){}return}console.log("unexpected error:",n)}catch(t){console.log("bad response",t.message)}else console.log("odd response",i);e._timeout=setTimeout((function(){e.onTimeout(t)}),15e3)}))}},{key:"getCurrentState",value:function(){return this._state}},{key:"getCurrentPlay",value:function(){return this._activePlay}}]),t}();function $(){try{return"localStorage"in window&&null!==window.localStorage}catch(t){return!1}}function F(t,e){$()&&localStorage.setItem(t,e)}function J(t){$()&&localStorage.removeItem(t)}function W(t){return $()?localStorage.getItem(t):null}function K(t){var e=W("feedfm:active");if(e){var i=JSON.parse(e);if(i.timestamp+t>Date.now()){var n=parseFloat(W("feedfm:elapsed_time"),10);return[i.state,n]}}return[]}var G=function(t,e,i){Object.assign(this,q),t&&e&&((i=i||{}).baseUrl&&y(i.baseUrl),this.config={remoteLogging:!!i.remoteLogging,formats:"mp3,aac",maxBitrate:128,timeOffset:0,current:null,pendingRequest:null,pendingPlay:null},t&&e&&this.setCredentials(t,e),i.remoteLogging&&(r("remote logging enabled",this.config),this._submitLogHistory()))};G.prototype.setCredentials=function(t,e){this.config.token=t,this.config.secret=e},G.prototype.setStationId=function(t,e,i){if(this.config.stations){var n=""+t,s=""+this.config.stationId!==n;if(s||e){var a=this.config.stations.find((function(t){return""+t.id===n}));a&&(this.config.stationId=t,this.config.station=a,s&&this.trigger("station-changed",t,a),this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0),this._requestNextPlay(0,e,i))}}},G.prototype.setFormats=function(t){this.config.formats=t,this.isTuned()&&this.tune()},G.prototype.setMaxBitrate=function(t){this.config.maxBitrate=t},G.prototype.tune=function(){if(!this.config.token)throw new Error("no token set with setCredentials()");if(!this.config.secret)throw new Error("no secret set with setCredentials()");this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0),this._getDefaultPlacementInformation()},G.prototype._getDefaultPlacementInformation=function(t){var e=this;this.config.placementId&&this.config.placement&&this.config.placement.id===this.config.placementId?this._requestNextPlay():(r("requesting default placement information from server"),e._signedAjax(g()+"/api/v2/session",{method:"POST",body:JSON.stringify({client_id:k()}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).then((function(t){return t.session&&t.session.client_id&&A(t.session.client_id),e._getClientId().then((function(){return t}))})).then(e._receiveDefaultPlacementInformation.bind(e)).catch(e._failedDefaultPlacementInformation.bind(e,t)))},G.prototype._receiveDefaultPlacementInformation=function(t){t&&t.success&&t.placement?(this.config.placement=t.placement,this.config.stations=t.stations,this.config.placementId=t.placement.id,this.trigger("placement",this.config.placement),this.config.stations.length>0&&(this.config.stationId=this.config.stations[0].id,this.config.station=this.config.stations[0],this.trigger("station-changed",this.config.stationId,this.config.station)),this.trigger("stations",this.config.stations),this._requestNextPlay()):this.trigger("music-unavailable")},G.prototype._failedDefaultPlacementInformation=function(t,e){var i=this;if(401===e.status)try{var n=JSON.parse(e.responseText);if(n.error&&5===n.error.code)return void this.trigger("invalid-credentials")}catch(t){}else console.warn("error from placement request",e);t=t?2*t:500,setTimeout((function(){i._getDefaultPlacementInformation(t)}),t)},G.prototype.getActivePlacement=function(){return this.config.placement?this.config.placement:null},G.prototype.getActivePlay=function(){return this.config.current?this.config.current.play:null},G.prototype.isTuned=function(){return this.config.current||this.config.pendingRequest},G.prototype.hasActivePlayStarted=function(){return this.config.current&&this.config.current.started},G.prototype.reportPlayStarted=function(){if(!this.config.current)throw new Error("attempt to report a play started, but there is no active play");this._startPlay(this.config.current.play)},G.prototype.reportPlayElapsed=function(t){if(!this.config.current)throw new Error("attempt to report elapsed play time, but the play hasn't started");this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/elapse",{method:"POST",body:JSON.stringify({seconds:t}),headers:{"Content-Type":"application/json"}}).catch((function(t){return r("server returned error on elapse call. ignoring",t)}))},G.prototype.reportPlayCompleted=function(){if(!this.config.current||!this.config.current.started)throw r("finish on non-active or playing song"),new Error("no active or playing song");this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/complete",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){r("play completed returned error - ignoring",t)})).finally(this._receivePlayCompleted.bind(this))},G.prototype._receivePlayCompleted=function(){if(this.config.pendingRequest)r("song finished, but we're still waiting for next one to return"),this._assignCurrentPlay(null,!0);else{r("song finished, and no outstanding request, so playing pendingPlay");var t=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(t)}},G.prototype.reportPlayStopped=function(t){this.config.current&&this.config.current.started&&this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/elapse",{method:"POST",body:JSON.stringify({seconds:t}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on elapse call. ignoring",t)})),this.config.pendingRequest=null,this.config.pendingPlay=null,this._assignCurrentPlay(null,!0)},G.prototype.requestSkip=function(){var t=this;if(!this.hasActivePlayStarted())throw new Error("No song playing or started");this.config.current.canSkip?this._signedAjax(g()+"/api/v2/play/"+this.config.current.play.id+"/skip",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveSkip.bind(this,this.config.current.play)).catch(this._failSkip.bind(this,this.config.current.play)):setTimeout((function(){t.trigger("skip-denied")}),1)},G.prototype.requestInvalidate=function(t){if(t)this.config.current&&this.config.current.play.audio_file.url===t?this._sendInvalidate(this.config.current.play):this.config.pendingPlay&&this.config.pendingPlay.audio_file.url===t&&this._sendInvalidate(this.config.pendingPlay);else{if(!this.config.current)throw new Error("No active song to invalidate!");this._sendInvalidate(this.config.current.play)}},G.prototype._sendInvalidate=function(t,e){this._signedAjax(g()+"/api/v2/play/"+t.id+"/invalidate",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveInvalidate.bind(this,t)).catch(this._failInvalidate.bind(this,e,t))},G.prototype._failInvalidate=function(t,e,i){var n=this;(t=t?2*t:200)<3e3?setTimeout((function(){n._sendInvalidate(e)}),t):r("gave up trying to invalidate play",i)},G.prototype._receiveInvalidate=function(t,e){var i=this;if(r("invalidate response"),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after invalidate"),i._submitLogHistory()}),5e3),e.success)if(this.config.current&&this.config.current.play===t)if(this.config.pendingPlay){r("invalidating to song already queued up");var n=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(n)}else r("invalidating current song"),this._assignCurrentPlay(null,!0),this.config.pendingRequest||(r("queueing up new song"),this._requestNextPlay());else t===this.config.pendingPlay&&(r("invalidated pending play, queueing up new pending play"),this.config.pendingPlay=null,this._requestNextPlay());else r("failed invalidate! - technically this is impossible")},G.prototype._failSkip=function(t){this.config.current&&this.config.current.play===t&&this.trigger("skip-denied")},G.prototype._receiveSkip=function(t,e){if(this.config.current&&this.config.current.play===t){if(!e.success)return r("failed skip!"),void this.trigger("skip-denied");if(this.config.pendingPlay){r("skipping to song already queued up");var i=this.config.pendingPlay;this.config.pendingPlay=null,this._assignCurrentPlay(i)}else this.config.pendingRequest?(r("skipping to what is queued up"),this._assignCurrentPlay(null,!0)):(r("skipping to what is queued up"),this._assignCurrentPlay(null))}},G.prototype._startPlay=function(t){this.config.current.retryCount>2?this._receiveStartPlay(t,{success:!0,can_skip:!0}):(r("telling server we're starting the play",t),this._signedAjax(g()+"/api/v2/play/"+t.id+"/start",{method:"POST"}).then((function(t){return t.json()})).then(this._receiveStartPlay.bind(this,t)).catch(this._failStartPlay.bind(this,t)))},G.prototype._receiveStartPlay=function(t,e){e.success?this.config.current&&this.config.current.play===t?(this.config.current.canSkip=e.can_skip,this.config.current.started=!0,this._requestNextPlay(),this.trigger("play-started",t)):r("received start play, but not waiting any more"):r("received failed start success")},G.prototype._failStartPlay=function(t,e){var i=this,n=this;if(r("start failed",e),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after start failure"),n._submitLogHistory()}),5e3),this.config.current&&this.config.current.play===t){if(e&&403===e.status)try{var s=JSON.parse(e.responseText);if(s.error&&20===s.error.code)return this._receiveStartPlay(t,{success:!0,can_skip:!0})}catch(t){r("unable to parse start play response",t.message)}r("request failed - trying again in 1 second",e),this.config.current.retryCount++,setTimeout((function(){i._startPlay(t)}))}else r("startPlay failed, but we don't care any more")},G.prototype._assignCurrentPlay=function(t,e){if(this.config.current){var i=this.config.current.play;this.config.current=null,this.trigger("play-completed",i)}null===t?e?r("nothing to play... waiting"):(r("nothing to play from the current station"),this.trigger("plays-exhausted")):(this.config.current={play:t,canSkip:!1,started:!1,retryCount:0},r("activated new song"),this.trigger("play-active",t))},G.prototype._requestNextPlay=function(t,e,i){var n=this;n._getClientId().then((function(s){if(n.config.pendingRequest){if(t){if(t>6e4)return r("giving up on retrieving next play"),n.config.pendingRequest=null,void(null===n.config.current&&n._assignCurrentPlay(null));r("retrying pending request"),n.config.pendingRequest.retryCount++;var a=n.config.pendingRequest.ajax;return void n._signedAjax(n.config.pendingRequest.url,a).then((function(t){return t.json()})).then(n._receiveNextPlay.bind(n,a)).catch(n._failedNextPlay.bind(n,t,a))}r("already waiting for a request to finish")}else{var o={formats:n.config.formats,client_id:s,max_bitrate:n.config.maxBitrate,secure:!0};n.config.placementId&&(o.placement_id=n.config.placementId),n.config.stationId&&(o.station_id=n.config.stationId),e&&(o.at=e,i&&(o.crossfade=i));var u={method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}};n.config.pendingRequest={url:g()+"/api/v2/play",ajax:u,retryCount:0},r("requesting new play from server",u),n._signedAjax(g()+"/api/v2/play",u).then((function(t){return t.json()})).then(n._receiveNextPlay.bind(n,u)).catch(n._failedNextPlay.bind(n,t,u))}}))},G.prototype._receiveNextPlay=function(t,e){this.config.pendingRequest&&this.config.pendingRequest.ajax===t?(this.config.pendingRequest=null,e.success?(this.trigger("prepare-sound",e.play.audio_file.url,e.play.start_at,e.play.id),this.config.current?(r("received play, but we're already playing, so queueing up",e.play),this.config.pendingPlay=e.play):(r("received play and no current song, making active now",e.play),this._assignCurrentPlay(e.play))):e.error&&9===e.error.code?this.config.current?(r("ran out of music to play, but we're already playing"),this.config.pendingPlay=null):(r("ran out of music, and nothing playing now"),this.trigger("plays-exhausted")):e.error&&6===e.error.code?this.trigger("forbidden",e.error.message):r("unsuccessful response",e)):r("nextPlay succeeded, but we don't care")},G.prototype._failedNextPlay=function(t,e,i){var n=this;if(r("next play failed",i),this._submitLogHistory(),setTimeout((function(){r("5 second follow up after next play failure"),n._submitLogHistory()}),5e3),this.config.pendingRequest&&this.config.pendingRequest.ajax===e){if(i&&403===i.status)try{var s=JSON.parse(i.responseText);if(s.error&&19===s.error.code)return this.trigger("music-unavailable",s.error.message),void this.trigger("not-in-us",s.error.message)}catch(t){r("problem parsing 403 response",t.message)}t=Math.min(t?2*t:500,2e3),r("request failed - trying again after "+t+"ms"),setTimeout((function(){n._requestNextPlay(t)}),t)}else r("nextPlay failed, but we don't care")},G.prototype.canSkipInStation=function(){return!(this.config.station&&!1===this.config.station.can_skip)},G.prototype.maybeCanSkip=function(){return this.canSkip()},G.prototype.canSkip=function(){return!!(this.canSkipInStation()&&this.config.current&&this.config.current.started&&this.config.current.canSkip)},G.prototype.canLike=function(){return!(this.config.station&&!1===this.config.station.can_like)},G.prototype.likePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/like",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on like call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&(this.config.current.play.liked=!0))},G.prototype.unlikePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/like",{method:"DELETE"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on unlike call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&delete this.config.current.play.liked)},G.prototype.dislikePlay=function(t){this.canLike()&&(this._signedAjax(g()+"/api/v2/play/"+t+"/dislike",{method:"POST"}).then((function(t){return t.json()})).catch((function(t){return r("server returned error on invalidate call. ignoring",t)})),this.config.current&&this.config.current.play.id===t&&(this.config.current.play.liked=!1))};G.prototype._getStoredCid=function(){return n("cid")},G.prototype._setStoredCid=function(t){s("cid",t,{expires:3650,path:"/"})},G.prototype._deleteStoredCid=function(){a("cid")},G.prototype._sign=function(t){var e;if(t||(t={}),e="Basic "+btoa(this.config.token+":"+this.config.secret),t.headers?t.headers.Authorization=e:t.headers={Authorization:e},t.headers["X-Feed-SDK"]="1.103.0 js",this.extraHeaders)for(var i in this.extraHeaders)this.extraHeaders.hasOwnProperty(i)&&(t.headers[i]=this.extraHeaders[i]);return t},G.prototype._signedAjax=function(t,e){return this._ajax(t,this._sign(e)).then((function(t){if(!t.ok)throw new Error("server returned error "+t.status+": "+t.statusText);return t}))},G.prototype._ajax=function(t,e){return fetch(t,e)},G.prototype._submitLogHistory=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this,i=r.history;if(r.history=[],this.config.remoteLogging)return this._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:i}),headers:{"Content-Type":"application/json"}}).then((function(t){return t.json()})).catch((function(){t<2&&setTimeout((function(){r.history=i.concat(["failed log report attempt, try #"+t],r.history),e._submitLogHistory(t+1)}),5e3)}))},G.prototype._submitLogHistory=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this,i=r.history;if(r.history=[],this.config.remoteLogging)return this._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:i}),headers:{"Content-Type":"application/json"}}).catch((function(){t<2&&setTimeout((function(){r.history=i.concat(["failed log report attempt, try #"+t],r.history),e._submitLogHistory(t+1)}),5e3)}))},G.prototype._submitEvent=function(t,e){var i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,s=this;return this._getClientId().then((function(n){return i._signedAjax(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:t,client_id:n,parameters:JSON.stringify(e)}),headers:{"Content-Type":"application/json"}})})).catch((function(){n<2&&setTimeout((function(){r.history=history.concat(["failed event submission, try #"+n],r.history),s._submitLogHistory(n+1)}),5e3)}))},G.prototype._getClientId=function(){return b()};var Y=!1;var Q=function(t){for(var e=t.length,i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;s=this.active.sound.fadeOutStart){this._setVolume(this.active);var n=this.fading;this.fading=this.active,this.active=n,this.active.sound=null,this.fading.sound.trigger("finish")}else this._setVolume(this.active),this.active.sound.trigger("elapse");this.prepareWhenReady&&this.prepare(this.prepareWhenReady.url,this.prepareWhenReady.startPosition)}}else this.fading.sound.endPosition&&e.currentTime>=this.fading.sound.endPosition/1e3?(this.fading.sound=null,lt(this.fading.audio),this.fading.audio.src=at):this._setVolume(this.fading)},_setVolume:function(t,e){e||(e=t.sound);var i=t.audio.currentTime,n=t.volume,s=e.gainAdjustedVolume(this.vol);e.fadeInStart!==e.fadeInEnd&&i=e.fadeInStart&&i<=e.fadeInEnd?(s=(i-e.fadeInStart)/(e.fadeInEnd-e.fadeInStart)*s,r("ramping \u25b2 volume",{currentTime:i,currentVolume:n,calculatedVolume:s,sound:e})):e.fadeOutStart!==e.fadeOutEnd&&i>e.fadeOutEnd?(s=0,r("post-fade-out volume is 0")):e.fadeOutStart!==e.fadeOutEnd&&i>=e.fadeOutStart&&i<=e.fadeOutEnd&&(s=(1-(i-e.fadeOutStart)/(e.fadeOutEnd-e.fadeOutStart))*s,r("ramping \u25bc volume",{currentTime:i,currentVolume:n,calculatedVolume:s,sound:e})),n!==s&&(ut.IOS?st||(t.gain.value=s):t.audio.volume=s,t.volume=s)},_debugAudioObject:function(t){for(var e=["abort","load","loadend","loadstart","loadeddata","loadedmetadata","canplay","canplaythrough","seeked","seeking","stalled","timeupdate","volumechange","waiting","durationchange","progress","emptied","ended","play","pause","error"],i=this,n=0;n1&&void 0!==arguments[1]?arguments[1]:0;if(!this.active||!this.active.audio)return et()?(r("pre-loading audio",{url:t}),this._preload(t)):(r("saving url to prepare when audio is initialized",{url:t,startPosition:e}),this.prepareWhenReady={url:t,startPosition:e},!1);var i=this.active.audio.buffered,n=i.length>0&&i.end(i.length-1);return!nt&&i.length>0&&i.end(i.length-1)>=this.active.audio.duration?(r("active song has loaded enough, so preparing",t),et()?this._preload(t):this._prepare(t,e)):this.active.audio.src===at?(r("preparing over silence"),et()?this._preload(t):this._prepare(t,e)):(r("still loading primary, so waiting to do active prepare",{activeUrl:this.active.audio.src,range:n}),this.prepareWhenReady={url:t,startPosition:e},!1)},logState:function(t){for(var e in console.group("speaker: "+(t||"")),this.active?(console.group("active"),console.log("audio.src: ".concat(this.active.audio.src)),console.log("audio.paused: ".concat(this.active.audio.paused)),console.log("sound: ".concat(this.active.sound?this.active.sound.id:"NULL")),console.log("volume: ".concat(this.active.volume)),console.groupEnd(),console.group("preparing"),console.log("audio.src: ".concat(this.preparing.audio.src)),console.log("audio.paused: ".concat(this.preparing.audio.paused)),console.log("sound: ".concat(this.preparing.sound?this.preparing.sound.id:"NULL")),console.log("volume: ".concat(this.preparing.volume)),console.groupEnd(),console.group("fading"),console.log("audio.src: ".concat(this.fading.audio.src)),console.log("audio.paused: ".concat(this.fading.audio.paused)),console.log("sound: ".concat(this.fading.sound?this.fading.sound.id:"NULL")),console.log("volume: ".concat(this.fading.volume)),console.groupEnd()):(console.group("active"),console.log("uninitialized"),console.groupEnd(),console.group("preparing"),console.log("uninitialized"),console.groupEnd(),console.group("fading"),console.log("uninitialized"),console.groupEnd()),console.group("outstanding sounds"),this.outstandingSounds){var i=this.outstandingSounds[e];console.log(i.id+": "+i.url)}console.groupEnd(),console.groupEnd()},_preload:function(t){if(r("preloading!"),this.prepareWhenReady=null,this.preloaded){if(this.preloaded.url===t){var e=!!this.preloaded.blobUrl;return r("preloading",{url:t,preloaded:e}),e}this.preloaded.blobUrl&&(r("revoking previously loaded url",{url:this.preloaded.url}),URL.revokeObjectURL(this.preloaded.blobUrl),this.preloaded=null)}return this.preloaded={url:t,blobUrl:null,responses:[]},this._fetch(t,this.preloaded.responses),!1},_fetch:function(t,e){var i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;r("preload attempt #".concat(n),{url:t});var s={start:(new Date).toString()};e.push(s);var a=function(){if(i.preloaded&&i.preloaded.url===t)return n>i.maxRetries?(r("preload failed to fetch",{url:t,responses:e}),i.preloaded=null,void i.trigger("prepared",t,!1,e)):void setTimeout((function(){return i._fetch(t,e,n+1)}),Math.min(Math.pow(10,n),1e4));r("preload abandoning retry because we have moved on",{url:t})};r("preloading",{url:t,responses:e}),fetch(t).then((function(n){return r("preload got response"),s.end=(new Date).toString(),s.status=n.status,s.text=n.statusText,s.headers=C(n.headers.entries()),"opaque"===n.type?(r("preload opaque response, so retrying"),s.name="OpaqueResponse",s.message="Browser returned oaque response",void a()):n.ok?void n.blob().then((function(n){if(r("preload got blob"),i.preloaded&&i.preloaded.url===t){r("preloaded",{url:t});var s=new Blob([n],{type:"audio/mpeg"});i.preloaded.blobUrl=URL.createObjectURL(s),i.trigger("prepared",t,!0,e)}else r("preload retrieved url, but nobody cares any more")})).catch((function(t){r("preload error blobbing",t,t.name,t.message),s.name=t.name,s.message=t.message,a()})):(r("preload fetch error - retrying"),void a())})).catch((function(t){r("preload error",t,t.name,t.message),s.end=(new Date).toString(),s.name=t.name,s.message=t.message,a()}))},_prepare:function(t,e){return this.prepareWhenReady=null,nt?(r("preparing "+t),this.active.audio.playing&&this.active.audio.pause(),this.active.audio.src=t):this.preparing.audio.src!==t&&(r("preparing "+t),this.preparing.audio.playing&&this.preparing.audio.pause(),this.preparing.canplaythrough=!1,lt(this.preparing.audio),this.preparing.audio.src=t),nt&&e&&this.active.audio.currentTime!==e?(r("advancing preparing audio to",e/1e3),this.active.audio.currentTime=e/1e3):e&&this.preparing.audio.currentTime!==e&&(r("advancing preparing audio to",e/1e3),this.preparing.audio.currentTime=e/1e3),!1},_playSound:function(t){var e=this,i=this;if(this.active&&this.active.audio)if(this.active.sound!==t){!nt&&this.preloaded&&this.preloaded.url===t.url&&this.preloaded.blobUrl?(r(t.id+" using preloaded audio",this.preloaded),this.preparing.audio.playing&&this.preparing.audio.pause(),t.responses=this.preloaded.responses,lt(this.preparing.audio),this.preparing.audio.src=this.preloaded.blobUrl,this.preparing.canplaythrough=!0,this.preloaded=null):this.preparing.audio.src!==t.url&&this._prepare(t.url,t.startPosition);var n=this.active;if(nt||(this.active=this.preparing,this.preparing=n),!nt&&this.preparing.sound){this.preparing.audio.src=at;var s=this.preparing.sound;this.preparing.sound=null,s.trigger("finish")}if(this.preparing.canplaythrough=!1,lt(this.preparing.audio),this.preparing.audio.src=at,this.active.sound=null,this._setVolume(this.active,t),this.preparing.sound){s=this.preparing.sound;this.preparing.sound=null,s.trigger("finish")}t.awaitingPlayResponse=!0,this.active.sound=t;var a=this.active,o=1;!function n(){r(t.id+" initiating play()",{attempt:o}),e.active.audio.play().then((function(){if(delete t.awaitingPlayResponse,!i.outstandingSounds[t.id])return r(t.id+" play() succeeded, but sound has been destroyed"),void(a.audio&&a.audio.src===t.url&&(r(t.id+" being paused and unloaded"),a.audio.pause(),lt(a.audio),a.audio.src=at));r(t.id+" play() succeeded"),t.fadeOutSeconds&&0===t.fadeOutEnd&&(t.fadeOutStart=a.audio.duration-t.fadeOutSeconds,t.fadeOutEnd=a.audio.duration),t.startPosition&&(r("updating start position"),a.audio.currentTime=t.startPosition/1e3,r("updated"));var e=a.audio.paused;t.trigger("play"),a.pauseAfterPlay?a.audio.pause():e&&t.trigger("pause")})).catch((function(e){r("error starting playback with sound "+t.id,{name:e.name,message:e.message,attempt:o}),o<4?(o++,setTimeout(n,10)):t.trigger("finish",e)}))}()}else this.active.audio.paused||"not-a-real-file-paused"===this.active.audio.src?(r(t.id+" was paused, so resuming"),nt&&(this.active.audio.currentTime=t.savedPos,this.active.audio.src=t.savedSrc),this.active.audio.play().then((function(){r("resumed playback"),t.trigger("play")})).catch((function(e){r("error resuming playback",e.name,e.message,e.stack,t.id),i.active.sound=null,t.trigger("finish")})),!nt&&this.fading.sound&&this.fading.audio.play().then((function(){r("resumed fading playback")})).catch((function(e){r("error resuming fading playback",e.name,e.message,e.stack,t.id),i.fading.sound=null,lt(i.fading.audio),i.fading.audio.src=at}))):r(t.id+" is already playing");else console.error("**** player.initializeAudio() *** not called before playback!")},_destroySound:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(t.off(),this.active&&this.active.sound===t)if(e&&t.fadeOutSeconds){r("destroy triggered for current sound (with fadeout)",t.id);var i=this.active.audio;if(t.fadeOutStart=i.currentTime,t.endPosition?(t.fadeOutEnd=Math.min(i.currentTime+t.fadeOutSeconds,t.endPosition/1e3),t.endPosition=Math.min(1e3*t.fadeOutEnd,t.endPosition)):(t.fadeOutEnd=i.currentTime+t.fadeOutSeconds,t.endPosition=1e3*t.fadeOutEnd),this._setVolume(this.active),!nt){var n=this.fading;this.fading=this.active,this.active=n,this.active.sound=null}}else r("destroy triggered for current sound (no fadeout)",t.id),this.active.audio.pause(),lt(this.active.audio),this.active.audio.src=at;else r("destroy triggered for inactive sound",t.id);delete this.outstandingSounds[t.id]},flush:function(){for(var t in this.outstandingSounds)this.outstandingSounds[t].destroy()},_pauseSound:function(t){this.active&&t.url===this.active.audio.src&&(this.active.sound===t?nt?(t.savedPos=this.active.audio.currentTime,t.savedSrc=this.active.audio.src,this.active.audio.src="not-a-real-file-paused"):this.active.audio.pause():this.active.pauseAfterPlay=!0,this.active.audio.pause()),!nt&&this.fading&&this.fading.audio&&this.fading.audio.pause()},_position:function(t){return this.active&&t===this.active.sound?Math.floor(1e3*this.active.audio.currentTime):0},_duration:function(t){if(t===this.active.sound){var e=this.active.audio.duration;return isNaN(e)?0:Math.floor(1e3*e)}return 0},setVolume:function(t){return void 0!==t&&(this.vol=t,this.active&&this.active.sound&&this._setVolume(this.active),this.trigger("volume",t)),this.vol},getVolume:function(){return this.vol}},Object.assign(ut.prototype,q);var dt=function(t,e,i){var n=this;if(e){(i=i||{}).maxRetries=i.maxRetries||10,this.options=i,this.state={paused:!0,simulcast:i.simulcast},i.debug&&r.enable(),this.trimming=!1!==i.trimming,this.normalizeVolume=!("normalizeVolume"in i)||i.normalizeVolume,this.resumable=!("resumable"in i)||i.resumable,this.secondsOfCrossfade=i.secondsOfCrossfade||0,this.crossfadeIn=!!i.crossfadeIn,this.serverAssignedCrossfade=!1,this._stationsPromise=new Promise((function(t,e){n._stationsResolve=t,n._stationsReject=e}));var s=this.speaker=new ut({maxRetries:i.maxRetries}),a=this.session=new G(t,e,i);if(i.brokenWebkitFormats&&ut.brokenWebkit){var o=i.brokenWebkitFormats.split(","),u=s.getSupportedFormats().split(","),l=h(o,u),c=l.join(",");r("input format list is",o,u),r("final support list is",c),0===l.length&&(c=s.getSupportedFormats()),a.setFormats(c)}else if(i.formats){var d=i.formats.split(","),p=s.getSupportedFormats().split(","),f=h(d,p),g=f.join(",");0===f.length&&(g=s.getSupportedFormats()),r("input format list is",d,p),r("final support list is",g),a.setFormats(g)}else a.setFormats(s.getSupportedFormats())}else console.log("^^^ this was messing up chromecast");Object.assign(this,q),this.session.on("play-active",this._onPlayActive,this),this.session.on("play-started",this._onPlayStarted,this),this.session.on("play-completed",this._onPlayCompleted,this),this.session.on("plays-exhausted",this._onPlaysExhausted,this),this.session.on("prepare-sound",this._onPrepareSound,this),this.session.on("placement",this._onPlacement,this),this.session.on("stations",this._onStations,this),this.session.on("station-changed",this._onStationChanged,this);for(var y=this,v=function(){var t=_[m];n.session.on(t,(function(){y.trigger.apply(y,[t].concat(Array.prototype.slice.call(arguments,0)))}))},m=0,_=["music-unavailable","not-in-us","invalid-credentials","skip-denied","play-active","forbidden"];m<_.length;m++)v();this.setMuted(this.isMuted())};dt.prototype._persist=function(){var t=ht(this.state);return t.activePlay&&(t.activePlay=ht(t.activePlay),delete t.activePlay.sound),{state:t,options:this.options,trimming:this.trimming,normalizeVolume:this.normalizeVolume,secondsOfCrossfade:this.secondsOfCrossfade,serverAssignedCrossfade:this.serverAssignedCrossfade,crossfadeIn:this.crossfadeIn,sessionConfig:this.session.config}},dt.prototype._restore=function(t){var e=this,i=t.persisted,n=t.elapsed;i.options.debug&&r.enable(),r("restoring!");var s=i.sessionConfig,a=s.current;s.current=null,s.pendingRequest=null,s.pendingPlay=null,this.session=new G,this.session.config=s,this.options=i.options,this.speaker=new ut({maxRetries:this.options.maxRetries}),this.state={paused:!0,simulcast:this.options.simulcast},this.trimming=i.trimming,this.normalizeVolume=i.normalizeVolume,this.resumable=!0,this.secondsOfCrossfade=i.secondsOfCrossfade,this.serverAssignedCrossfade=i.serverAssignedCrossfade,this.crossfadeIn=i.crossfadeIn,this._stationsPromise=new Promise((function(t,i){e._stationsResolve=t,e._stationsReject=i})),this.tune=function(){var t=this;return Promise.resolve(!0).then((function(){t._station=i.sessionConfig.station,t._stations=i.sessionConfig.stations,t._placement=i.sessionConfig.placement,t._stationsResolve(i._stations),t.trigger("placement",t._placement),t.trigger("station-changed",t._station),t.trigger("stations",t._stations),t.session.config.current=a,t.session.config.current.started=!1;var e=t.session.config.current.play;e.start_at=n/1e3,t.session.trigger("play-active",e),t.session.config.current.started=!0,t.state.paused=!1,t.session.trigger("play-started",e,!0),t.state.paused=!0,t.trigger("play-paused",e,!0)})).then((function(){return t._stationsPromise}))}},dt.prototype.initializeAudio=function(){r("INTIALIZE AUDIO"),this.speaker.initializeAudio()},dt.prototype._onPlacement=function(t){this._placement=t,t.options&&t.options.crossfade_seconds&&(this.secondsOfCrossfade=t.options.crossfade_seconds,this.serverAssignedCrossfade=!0),this.trigger("placement",t)},dt.prototype._onStations=function(t){this._stations=t,this._stationsResolve(t),this.trigger("stations",t)},dt.prototype._onStationChanged=function(t,e){this._station=e,this.serverAssignedCrossfade&&e.options&&"crossfade_seconds"in e.options?this.secondsOfCrossfade=e.options.crossfade_seconds:this.serverAssignedCrossfade&&this._placement.options&&"crossfade_seconds"in this._placement.options&&(this.secondsOfCrossfade=this._placement.options.crossfade_seconds),this.trigger("station-changed",t,e)},dt.prototype.setStationId=function(t,e){var i,n=!1;!0===e?(n=e,r("SET STATION ID (WITH FADE)",t)):e?r("SET STATION ID (WITH ADVANCE)",t,i=e):r("SET STATION ID",t),n&&this.state.activePlay&&(this.state.activePlay.fadeOnDestroy=!0),this.session.setStationId(t,i,this.crossfadeIn)},dt.prototype._onPlayActive=function(t){var e={play:this._onSoundPlay.bind(this,t.id),pause:this._onSoundPause.bind(this,t.id),finish:this._onSoundFinish.bind(this,t.id),elapse:this._onSoundElapse.bind(this,t.id)};this.normalizeVolume&&(e.gain=(t.audio_file.replaygain_track_gain||0)+(t.station.pre_gain||0)),t.start_at?e.startPosition=1e3*t.start_at:this.trimming&&t.audio_file.extra&&t.audio_file.extra.trim_start&&(e.startPosition=1e3*t.audio_file.extra.trim_start),this.trimming&&t.audio_file.extra&&t.audio_file.extra.trim_end&&t.audio_file.duration_in_seconds&&(e.endPosition=1e3*(t.audio_file.duration_in_seconds-t.audio_file.extra.trim_end)),this.secondsOfCrossfade&&(this.crossfadeIn&&(e.fadeInSeconds=this.secondsOfCrossfade),e.fadeOutSeconds=this.secondsOfCrossfade);var i=this.speaker.create(t.audio_file.url,e);(this.state.activePlay={id:t.id,sound:i,startReportedToServer:!1,soundCompleted:!1,playStarted:!1,fadeOnDestroy:!1,previousPosition:0},this.state.paused)||this.state.activePlay.sound.play()},dt.prototype._onSoundPlay=function(t){if(this.state.activePlay&&this.state.activePlay.id===t){this.state.paused=!1;var e=this.state.activePlay.playStarted;if(this.state.activePlay.playStarted=!0,!this.state.activePlay.startReportedToServer)return this.resumable&&function(t){var e=Date.now(),i=JSON.stringify({state:t,timestamp:e}),n=Date.now();F("feedfm:active",i);var s=Date.now();F("feedfm:elapsed_time","0"),r("persisted state",{timestamp:e,encodingTime:n-e,storageTime:s-n,state:t})}(this._persist()),this.session.reportPlayStarted();e&&this.trigger("play-resumed",this.session.getActivePlay())}else r("received sound play, but active play does not match",this.state.activePlay,t)},dt.prototype.getActivePlay=function(){return this.session.getActivePlay()},dt.prototype.hasActivePlayStarted=function(){return this.session.hasActivePlayStarted()},dt.prototype.getActivePlacement=function(){return this.session.getActivePlacement()},dt.prototype._onSoundPause=function(t){this.state.activePlay&&this.state.activePlay.id===t?(this.state.paused=!0,this.trigger("play-paused",this.session.getActivePlay())):r("received sound pause, but active play does not match",this.state.activePlay,t)},dt.prototype._onSoundFinish=function(t,e){if(this.state.activePlay&&this.state.activePlay.id===t){var i=this.state.activePlay.sound;return this.state.activePlay.soundCompleted=!0,e&&(this.session._submitEvent("playback-error",{url:i.url,responses:i.responses,error:e,play_id:t}),this.state.activePlay.soundCompletedWithError=!0,"NotAllowedError"===e.name)?(console.error('Feed.fm: first call to "initializeAudio()" or "play()" must be made in user-initiated event handler'),void this.stop()):this.state.activePlay.playStarted?void(this.state.activePlay.startReportedToServer&&(e?(r("song completed with error - marking as invalid",e),this.trigger("invalidated",t),this.session.requestInvalidate()):this.session.reportPlayCompleted())):(this.trigger("invalidated",t),void this.session.requestInvalidate())}r("received sound finish, but active play does not match",this.state.activePlay,t)},dt.prototype._onSoundElapse=function(t){if(this.state.activePlay&&this.state.activePlay.id===t){var e=this.state.activePlay.sound.position(),i=Math.floor(this.state.activePlay.previousPosition/3e4),n=Math.floor(e/3e4);this.resumable&&F("feedfm:elapsed_time",e.toString()),this.state.activePlay.previousPosition=e,n!==i&&this.session.reportPlayElapsed(Math.floor(e/1e3))}else r("received sound elapse, but active play does not match",this.state.activePlay,t)},dt.prototype._onPlayStarted=function(t){var e=this,i=this.session;this.state.activePlay&&this.state.activePlay.id===t.id?(this.state.activePlay.startReportedToServer=!0,this.state.activePlay.soundCompleted&&(r("sound completed before we finished reporting start",this.state.activePlay),this.state.activePlay.soundCompletedWithError?setTimeout((function(){e.trigger("invalidated",t.id),i.requestInvalidate()}),1):setTimeout((function(){return i.reportPlayCompleted()}),1)),this.updateSimulcast(),this.trigger("play-started",t)):r("received play started, but it does not match active play",t,this.state.activePlay)},dt.prototype._onPlayCompleted=function(t){if(this.state.activePlay&&this.state.activePlay.id===t.id){this.state.activePlay.sound.destroy(this.state.activePlay.fadeOnDestroy);var e=this.state.activePlay.playStarted;delete this.state.activePlay,e&&this.trigger("play-completed",t)}else r("received play completed, but it does not match active play",t,this.state.activePlay)},dt.prototype._onPlaysExhausted=function(){this.state.paused||(this.state.paused=!1,this.updateSimulcast(),this.trigger("plays-exhausted"))},dt.prototype._onPrepareSound=function(t,e,i){var n=this;r("preparing sound",t,e),this.speaker.prepare(t,1e3*e),this.speaker.once("prepared",(function(e,s,a){if(t===e){a&&a.length>1&&n.session._submitEvent("preload-error",{url:t,play_id:i,responses:a});var o=n.session.getActivePlay();s||o&&o.id===i||n.session.requestInvalidate(t)}}))},dt.prototype.isPaused=function(){return this.session.isTuned()&&this.state.paused},dt.prototype.tune=function(){return r("TUNE"),this.session.isTuned()||this.session.tune(),this._stationsPromise},dt.prototype.prepare=function(){return r("PREPARE"),this.speaker.initializeAudio(),this._prepare()},dt.prototype._prepare=function(){var t=this,e=this.state.activePlay;if(e){var i=e.sound.url;return this.speaker.prepare(i,e.sound.startPosition)?Promise.resolve(!0).then((function(){r("already prepared"),t.trigger("prepared")})):new Promise((function(n){r("waiting for un/prepared event"),t.speaker.once("prepared",(function(s,a,o){o&&o.length>1&&t.session._submitEvent("preload-error",{url:s,play_id:e.id,responses:o}),s===i&&(a?(t.trigger("prepared"),n(!0)):(t.session.requestInvalidate(),t.session.once("play-active",(function(){t._prepare().then((function(t){return n(t)}))}))))}))}))}return new Promise((function(e){t.session.once("play-active",(function(){t._prepare().then((function(t){return e(t)}))})),t.session.isTuned()||(r("tuning"),t.session.tune())}))},dt.prototype.play=function(){r("PLAY");var t=this.session,e=this.state;if(this.speaker.initializeAudio(),!t.isTuned())return e.paused=!1,t.tune();t.getActivePlay()&&e.activePlay&&e.paused&&(e.activePlay.playStarted?e.activePlay.sound.resume():e.activePlay.sound.play()),e.paused=!1,this.updateSimulcast()},dt.prototype.pause=function(){r("PAUSE"),this.session.hasActivePlayStarted()&&this.state.activePlay&&!this.state.paused&&(this.state.activePlay.sound.pause(),this.state.paused=!0,this.updateSimulcast())},dt.prototype.canLike=function(){return this.session.canLike()},dt.prototype.like=function(){r("LIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.likePlay(this.state.activePlay.id),this.trigger("play-liked"))},dt.prototype.unlike=function(){r("UNLIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.unlikePlay(this.state.activePlay.id),this.trigger("play-unliked"))},dt.prototype.dislike=function(){r("DISLIKE"),this.session.hasActivePlayStarted()&&this.session.canLike()&&(this.session.dislikePlay(this.state.activePlay.id),this.trigger("play-disliked"),this.state.paused=!1,this.skip())},dt.prototype.skip=function(){r("SKIP"),this.session.hasActivePlayStarted()&&this.session.canSkipInStation()&&(this.state.paused=!1,this.session.requestSkip())},dt.prototype.stop=function(){r("STOP"),J("feedfm:active"),J("feedfm:elapsed_time"),this.state.paused=!0;var t=this.state.activePlay;if(t&&t.sound){if(r("stopping active play",t),t.startReportedToServer){var e=t.sound.position();this.session.reportPlayStopped(Math.floor(e/1e3))}t.sound.pause(),t.sound.destroy()}else r("no active play");delete this.state.activePlay,this.speaker.flush(),this.trigger("play-stopped"),this.updateSimulcast()},dt.prototype.destroy=function(){this.session=null,this.state.activePlay&&this.state.activePlay.sound&&this.state.activePlay.sound.destroy()},dt.prototype.getCurrentState=function(){return this.session.hasActivePlayStarted()?this.state.paused?"paused":"playing":"idle"},dt.prototype.getPosition=function(){return this.state.activePlay&&this.state.activePlay.sound?this.state.activePlay.sound.position():0},dt.prototype.getDuration=function(){return this.state.activePlay&&this.state.activePlay.sound?this.state.activePlay.sound.duration():0},dt.prototype.canSkip=function(){return this.session.canSkip()},dt.prototype.maybeCanSkip=function(){return this.canSkip()};function ht(t){return null===t?null:Object.assign({},t)}dt.prototype.isMuted=function(){return!(!ct()||!("muted"in localStorage))&&"true"===localStorage.muted},dt.prototype.setMuted=function(t){t?(this.speaker.setVolume(0),ct()&&(localStorage.muted=!0),this.trigger("muted")):(this.speaker.setVolume(100),ct()&&(localStorage.muted=!1),this.trigger("unmuted"))},dt.prototype.getVolume=function(){return this.speaker.getVolume()},dt.prototype.setVolume=function(t){this.speaker.setVolume(t)},dt.prototype.getStations=function(){return this._stationsPromise},dt.prototype.updateSimulcast=function(){var t=this;if(this.state.simulcast){var e=this.getCurrentState();b().then((function(i){t.session._signedAjax(g()+"/api/v2/simulcast/".concat(t.state.simulcast,"/in-progress"),{method:"POST",body:JSON.stringify({state:e,client_id:i}),headers:{"Content-Type":"application/json"}})}))}},window.NodeList&&!NodeList.prototype.forEach&&(NodeList.prototype.forEach=function(t,e){e=e||window;for(var i=0;i"+t.audio_file.track.title+" by "+t.audio_file.artist.name+" on "+t.audio_file.release.title+""},pt.prototype.renderStatus=function(t){var e=this;void 0!==t&&(this.displayText=t),this.alertId||this.$el.querySelectorAll(".status").forEach((function(t){t.innerHTML=e.displayText,t.classList.remove("alert")}))},pt.prototype.renderPosition=function(t,e){if(this.$el.querySelectorAll(".elapsed").forEach((function(e){e.innerHTML=ft(t)})),this.$el.querySelectorAll(".duration").forEach((function(t){t.innerHTML=ft(e)})),0===e)this.$el.querySelectorAll(".progress").forEach((function(t){t.style.width="0"}));else{var i=Math.round((t+1e3)/e*100);i=i>100?100:i,this.$el.querySelectorAll(".progress").forEach((function(t){t.style.width=i+"%"}))}},pt.prototype.renderAlert=function(t){this.alertId&&window.clearTimeout(this.alertId),this.$el.querySelectorAll(".status").forEach((function(e){e.innerHTML=t,e.classList.add("alert")}));var e=this;this.alertId=window.setTimeout((function(){e.alertId=null,e.renderStatus()}),3e3)},pt.prototype._onSuspend=function(){this._enableButtonsBasedOnState()},pt.prototype._enableButtonsBasedOnState=function(){var t,e,i=this.player.getCurrentState();switch(i){case"playing":t=[".pause-button"],e=[".play-button",".start-button",".resume-button"],this.player.canLike()?t.push(".dislike-button",".like-button"):e.push(".dislike-button",".like-button"),this.player.canSkip()?t.push(".skip-button"):e.push(".skip-button");break;case"paused":t=[".play-button",".resume-button"],e=[".pause-button",".start-button"],this.player.canLike()?t.push(".dislike-button",".like-button"):e.push(".dislike-button",".like-button"),this.player.canSkip()?t.push(".skip-button"):e.push(".skip-button");break;default:t=[".play-button",".start-button"],e=[".resume-button",".pause-button",".like-button",".dislike-button",".skip-button"]}var n,s=j(e);try{for(s.s();!(n=s.n()).done;){var a=n.value;this.$el.querySelectorAll(a).forEach((function(t){t.classList.remove("button-enabled"),t.classList.add("button-disabled"),t.disabled=!0}))}}catch(t){s.e(t)}finally{s.f()}var o,r=j(t);try{for(r.s();!(o=r.n()).done;){var u=o.value;this.$el.querySelectorAll(u).forEach((function(t){t.classList.remove("button-disabled"),t.classList.add("button-enabled"),t.disabled=!1}))}}catch(t){r.e(t)}finally{r.f()}var l=this.$el.classList;l.remove("state-playing"),l.remove("state-paused"),l.remove("state-idle"),l.add("state-"+i)};var gt=function(){function t(e){w(this,t),Object.assign(this,q),this._speaker=new ut,this._uuid=e,this._state="idle",this._activePlay=null,this._activeSound=null,this._metadataTimeout=null,this._tryingToPlay=!1,this._retries=0}return E(t,[{key:"initializeAudio",value:function(){r("INTIALIZE AUDIO"),this._speaker.initializeAudio()}},{key:"connect",value:function(){if(r("CONNECT to ".concat(this._uuid)),this._tryingToPlay)r("ignoring pointless connect to ".concat(this._uuid));else if("idle"===this._state){this._tryingToPlay=!0,this._speaker.initializeAudio(),this._setState("connecting");var t=new URL(g());this._streamUrl="https://cast."+t.hostname+"/"+this._uuid,this._requestStream()}else r("ignoring connect() since we're already connected")}},{key:"_onSoundPlay",value:function(){var t=this;r("sound play!"),this._retries=0,this._lastElapsedAt=Date.now(),"connecting"===this._state?(this._setState("connected"),fetch(this._streamUrl+"/play?elapsed="+this._elapsed).then((function(t){return t.json()})).then((function(e){e.success?(t._activePlay=e.play,t.trigger("play-started",t._activePlay),t._scheduleMetadataTimeout()):t._scheduleMetadataTimeout(3e3)})).catch((function(){t._scheduleMetadataTimeout(2e3)}))):this._metadataTimeout||this._scheduleMetadataTimeout()}},{key:"_scheduleMetadataTimeout",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;this._cancelMetadataTimeout(),this._metadataTimeout=setTimeout((function(){t._onMetadataTimeout()}),e)}},{key:"_cancelMetadataTimeout",value:function(){this._metadataTimeout&&clearTimeout(this._metadataTimeout),this._metadataTimeout=null}},{key:"_onSoundElapse",value:function(){if(this._activeSound){var t=this._elapsed;(this._elapsed=this._activeSound.position())-t>0&&(this._lastElapsedAt=Date.now())}}},{key:"_requestStream",value:function(){r("requesting stream"),this._tryingToPlay&&(this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._cancelMetadataTimeout(),this._activePlay=null,this._activeSound=this._speaker.create(this._streamUrl,{play:this._onSoundPlay.bind(this),finish:this._onSoundFinish.bind(this),elapse:this._onSoundElapse.bind(this)}),this._activeSound.play(),this._elapsed=0,this._lastElapsedAt=Date.now())}},{key:"_onMetadataTimeout",value:function(){var t=this;this._cancelMetadataTimeout(),fetch(this._streamUrl+"/play?elapsed="+this._elapsed).then((function(t){return t.json()})).then((function(e){e.success&&(null===e.play&&null!==t._activePlay||null!==e.play&&null===t._activePlay||null!==e.play&&null!==t._activePlay&&e.play.audio_file.id!==t._activePlay.audio_file.id)&&(t._activePlay=e.play,r("current play updated",t._activePlay),t.trigger("play-started",t._activePlay)),t._scheduleMetadataTimeout();var i=Date.now()-t._lastElapsedAt;i>8e3&&(r("stream has not advanced for ".concat(i," ms, so reconnecting"),t.toObject()),t._requestStream())})).catch((function(){var e=Date.now()-t._lastElapsedAt;e>8e3?(r("stream has not advanced for ".concat(e," ms, so reconnecting"),t.toObject()),t._requestStream()):t._scheduleMetadataTimeout()}))}},{key:"_onSoundFinish",value:function(t){var e=this;r("sound finished",this.toObject()),"connecting"===this._state&&t?(this._tryingToPlay=!1,this._setState("music-unavailable"),this.trigger("music-unavailable")):(r("reconnecting after stream ended",t),this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._cancelMetadataTimeout(),this._activePlay=null,this._retries+=1,setTimeout((function(){e._tryingToPlay&&(r("retrying connection after stream ended"),e._requestStream())}),Math.pow(2,this._retries))),this._logEvents()}},{key:"disconnect",value:function(){r("DISCONNECT",this.toObject()),this._tryingToPlay&&(this._tryingToPlay=!1,this._activePlay=null,this._elapsed=0,this._cancelMetadataTimeout(),this._activeSound&&(this._activeSound.destroy(),this._activeSound=null),this._setState("idle"),this._logEvents())}},{key:"getVolume",value:function(){return this._speaker.getVolume()}},{key:"setVolume",value:function(t){this._speaker.setVolume(t)}},{key:"_setState",value:function(t){this._state!==t&&(r("state transition ".concat(this._state," -> ").concat(t)),this._state=t,this.trigger("state-changed",this._state))}},{key:"getCurrentState",value:function(){return this._state}},{key:"getCurrentPlay",value:function(){return this._activePlay}},{key:"_logEvents",value:function(){var t=r.reset();return fetch(g()+"/api/v2/session/event",{method:"POST",body:JSON.stringify({event:"playerHistory",parameters:t}),headers:{"Content-Type":"application/json","X-Feed-SDK":"1.103.0 js"}})}},{key:"toObject",value:function(){return{state:this._state,activePlay:this._activePlay,uuid:this._uuid,metadataTimeoutIsNull:null===this._metadataTimeout,tryingToPlay:this._tryingToPlay,elapsed:this._elapsed,retries:this._retries}}},{key:"toString",value:function(){return JSON.stringify(this.toString())}}]),t}();return{Speaker:ut,Session:G,Player:dt,Listener:H,PlayerView:pt,SimulcastPlayer:gt,log:r,version:"1.103.0",resetClientId:function(){m?_=null:a("cid"),v=null},getClientId:b,setBaseUrl:y,resumable:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:4e3,e=K(t);if(2===e.length){var i=I(e,2),n=i[0],s=i[1],a=new dt({persisted:n,elapsed:s});return a}return null}}}(); diff --git a/html/manual.html b/html/manual.html index d8070f95..b59bb6d1 100644 --- a/html/manual.html +++ b/html/manual.html @@ -42,22 +42,43 @@
+
+ +
+