Files
pgsql-jellyfin/publish_test/wwwroot/node_modules.jellyfin-apiclient.bundle.js
2026-07-08 13:13:46 -04:00

2 lines
86 KiB
JavaScript

/*! For license information please see node_modules.jellyfin-apiclient.bundle.js.LICENSE.txt */
(self.webpackChunk=self.webpackChunk||[]).push([[94048],{92600:function(e){self,e.exports=function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};function r(e,t){if(!e)throw new Error("obj cannot be null!");e._callbacks=e._callbacks||{};var r=e._callbacks[t];return r||(e._callbacks[t]=[],r=e._callbacks[t]),r}e.d(t,{default:function(){return de}});var n={on:function(e,t,n){r(e,t).push(n)},off:function(e,t,n){var i=r(e,t),o=i.indexOf(n);-1!==o&&i.splice(o,1)},trigger:function(e,t){var n={type:t},i=[];i.push(n);for(var o=arguments[2]||[],a=0,s=o.length;a<s;a++)i.push(o[a]);r(e,t).slice(0).forEach((function(t){t.apply(e,i)}))}};function i(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function o(e){console.log(e)}function a(e){var t=e.cache;t&&t.put("data",new Response(JSON.stringify(e.localData))).catch(o)}function s(e){this.cache=e,this.localData={}}var u=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);try{self&&self.caches&&caches.open("embydata").then(s.bind(this))}catch(e){console.log("Error opening cache: ".concat(e))}}var t,r,n;return t=e,n=[{key:"getInstance",value:function(){return e.instance||(e.instance=new e),e.instance}}],(r=[{key:"setItem",value:function(e,t){localStorage.setItem(e,t);var r=this.localData;r&&r[e]!==t&&(r[e]=t,a(this))}},{key:"getItem",value:function(e){return localStorage.getItem(e)}},{key:"removeItem",value:function(e){localStorage.removeItem(e);var t=this.localData;t&&(t[e]=null,delete t[e],a(this))}}])&&i(t.prototype,r),n&&i(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}().getInstance();var l=function(){function e(t){var r=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._fulfilled=!1,this._promise=new Promise((function(e,n){r._promiseResolve=e,r._promiseReject=n,r.reset(t)}))}var t,r;return t=e,(r=[{key:"promise",value:function(){return this._promise}},{key:"reset",value:function(e){var t=this;this._fulfilled||(clearTimeout(this._timer),this._timer=setTimeout((function(){return t.resolve()}),e))}},{key:"resolve",value:function(){this._fulfilled||(clearTimeout(this._timer),this._fulfilled=!0,this._promiseResolve())}},{key:"reject",value:function(){this._fulfilled||(clearTimeout(this._timer),this._fulfilled=!0,this._promiseReject())}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function c(){c=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",a=n.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function u(e,t,r,n){var i=t&&t.prototype instanceof f?t:f,o=Object.create(i.prototype),a=new U(n||[]);return o._invoke=function(e,t,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return{value:void 0,done:!0}}for(r.method=i,r.arg=o;;){var a=r.delegate;if(a){var s=k(a,r);if(s){if(s===d)continue;return s}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=l(e,t,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===d)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}(e,r,a),o}function l(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d={};function f(){}function v(){}function g(){}var y={};s(y,i,(function(){return this}));var p=Object.getPrototypeOf,m=p&&p(p(b([])));m&&m!==t&&r.call(m,i)&&(y=m);var S=g.prototype=f.prototype=Object.create(y);function I(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function n(i,o,a,s){var u=l(e[i],e,o);if("throw"!==u.type){var c=u.arg,d=c.value;return d&&"object"==h(d)&&r.call(d,"__await")?t.resolve(d.__await).then((function(e){n("next",e,a,s)}),(function(e){n("throw",e,a,s)})):t.resolve(d).then((function(e){c.value=e,a(c)}),(function(e){return n("throw",e,a,s)}))}s(u.arg)}var i;this._invoke=function(e,r){function o(){return new t((function(t,i){n(e,r,t,i)}))}return i=i?i.then(o,o):o()}}function k(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,k(e,t),"throw"===t.method))return d;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var n=l(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,d;var i=n.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,d):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,d)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function U(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function b(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,o=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return o.next=o}}return{next:O}}function O(){return{value:void 0,done:!0}}return v.prototype=g,s(S,"constructor",g),s(g,"constructor",v),v.displayName=s(g,a,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===v||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,g):(e.__proto__=g,s(e,a,"GeneratorFunction")),e.prototype=Object.create(S),e},e.awrap=function(e){return{__await:e}},I(w.prototype),s(w.prototype,o,(function(){return this})),e.AsyncIterator=w,e.async=function(t,r,n,i,o){void 0===o&&(o=Promise);var a=new w(u(t,r,n,i),o);return e.isGeneratorFunction(r)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},I(S),s(S,a,"Generator"),s(S,i,(function(){return this})),s(S,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function r(){for(;t.length;){var n=t.pop();if(n in e)return r.value=n,r.done=!1,r}return r.done=!0,r}},e.values=b,U.prototype={constructor:U,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(P),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return a.type="throw",a.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var s=r.call(o,"catchLoc"),u=r.call(o,"finallyLoc");if(s&&u){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(s){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=e,a.arg=t,o?(this.method="next",this.next=o.finallyLoc,d):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),d},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),d}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;P(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:b(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),d}},e}function h(e){return h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h(e)}function d(e,t,r,n,i,o,a){try{var s=e[o](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,i)}function f(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function a(e){d(o,n,i,a,s,"next",e)}function s(e){d(o,n,i,a,s,"throw",e)}a(void 0)}))}}var v={timeupdate:1e4,volumechange:3e3};function g(e){p(e),e.accessToken()&&!1!==e.enableAutomaticBitrateDetection&&(e.detectTimeout=setTimeout(y.bind(e),6e3))}function y(){this.detectTimeout=null,this.accessToken()&&this.detectBitrate()}function p(e){e.detectTimeout&&(clearTimeout(e.detectTimeout),e.detectTimeout=null)}function m(e,t,r){var n=new RegExp(t,"ig");return e.replace(n,r)}function S(e,t,r){n.trigger(e,"requestfail",[{url:t,status:r.status,errorCode:r.headers?r.headers.get("X-Application-Error-Code"):null}])}function I(e){var t=[];for(var r in e){var n=e[r];null!=n&&""!==n&&t.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(n)))}return t.join("&")}function w(e,t,r){return new Promise((function(n,i){var o=setTimeout(i,r);(t=t||{}).credentials="same-origin",fetch(e,t).then((function(e){clearTimeout(o),n(e)})).catch((function(e){clearTimeout(o),i(e)}))}))}function k(e){var t=e.headers||{};"json"===e.dataType&&(t.accept="application/json");var r={headers:t,method:e.type,credentials:"same-origin"},n=e.contentType;return e.data&&("string"==typeof e.data?r.body=e.data:(r.body=I(e.data),n=n||"application/x-www-form-urlencoded; charset=UTF-8")),n&&(t["Content-Type"]=n),e.timeout?w(e.url,r,e.timeout):fetch(e.url,r)}function T(e,t){return P.apply(this,arguments)}function P(){return(P=f(c().mark((function e(t,r){return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof t.reportPlaybackProgressReset){e.next=3;break}return e.next=3,t.reportPlaybackProgressReset(r);case 3:return t.lastPlaybackProgressReport=0,t.lastPlaybackProgressReportTicks=null,e.abrupt("return",Promise.resolve());case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var U=function(){function e(t,r,n,i,o){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("Must supply a serverAddress");console.debug("ApiClient serverAddress: ".concat(t)),console.debug("ApiClient appName: ".concat(r)),console.debug("ApiClient appVersion: ".concat(n)),console.debug("ApiClient deviceName: ".concat(i)),console.debug("ApiClient deviceId: ".concat(o)),this._serverInfo={},this._serverAddress=t,this._deviceId=o,this._deviceName=i,this._appName=r,this._appVersion=n,this._loggedIn=!1}var t,r,i,o;return t=e,r=[{key:"appName",value:function(){return this._appName}},{key:"setRequestHeaders",value:function(e){var t=this.serverInfo(),r=this._appName,n=t.AccessToken,i=[];r&&i.push('Client="'.concat(r,'"')),this._deviceName&&i.push('Device="'.concat(this._deviceName,'"')),this._deviceId&&i.push('DeviceId="'.concat(this._deviceId,'"')),this._appVersion&&i.push('Version="'.concat(this._appVersion,'"')),n&&i.push('Token="'.concat(n,'"')),i.length&&(e.Authorization="MediaBrowser ".concat(i.join(", ")))}},{key:"appVersion",value:function(){return this._appVersion}},{key:"deviceName",value:function(){return this._deviceName}},{key:"deviceId",value:function(){return this._deviceId}},{key:"serverAddress",value:function(e){if(null!=e){if(0!==e.toLowerCase().indexOf("http"))throw new Error("Invalid url: ".concat(e));var t=e!==this._serverAddress;this._serverAddress=e,this.onNetworkChange(),t&&n.trigger(this,"serveraddresschanged")}return this._serverAddress}},{key:"onNetworkChange",value:function(){this.lastDetectedBitrate=0,this.lastDetectedBitrateTime=0,b(this,null),g(this)}},{key:"getUrl",value:function(e,t,r){if(!e)throw new Error("Url name cannot be empty");var n=r||this._serverAddress;if(!n)throw new Error("serverAddress is yet not set");return"/"!==e.charAt(0)&&(n+="/"),n+=e,t&&(t=I(t))&&(n+="?".concat(t)),n}},{key:"fetchWithFailover",value:function(e,t){console.log("Requesting ".concat(e.url)),e.timeout=3e4;var r=this;return k(e).then((function(t){return r.lastFetch=(new Date).getTime(),t.status<400?"json"===e.dataType||"application/json"===e.headers.accept?t.json():"text"===e.dataType||0===(t.headers.get("Content-Type")||"").toLowerCase().indexOf("text/")?t.text():t:(S(r,e.url,t),Promise.reject(t))})).catch((function(n){if(n?console.log("Request failed to ".concat(e.url," ").concat(n.toString())):console.log("Request timed out to ".concat(e.url)),n&&n.status||!t)throw console.log("Reporting request failure"),S(r,e.url,{}),n;console.log("Attempting reconnection");var i=r.serverAddress();return O(r).then((function(){return console.log("Reconnect succeeded"),e.url=e.url.replace(i,r.serverAddress()),r.fetchWithFailover(e,!1)})).catch((function(t){throw console.log("Reconnect failed"),S(r,e.url,{}),t}))}))}},{key:"fetch",value:function(e,t){if(!e)return Promise.reject("Request cannot be null");if(e.headers=e.headers||{},!1!==t&&this.setRequestHeaders(e.headers),!1===this.enableAutomaticNetworking||"GET"!==e.type){console.log("Requesting url without automatic networking: ".concat(e.url));var r=this;return k(e).then((function(t){return r.lastFetch=(new Date).getTime(),t.status<400?"json"===e.dataType||"application/json"===e.headers.accept?t.json():"text"===e.dataType||0===(t.headers.get("Content-Type")||"").toLowerCase().indexOf("text/")?t.text():t:(S(r,e.url,t),Promise.reject(t))})).catch((function(t){return S(r,e.url,{}),Promise.reject(t)}))}return this.fetchWithFailover(e,!0)}},{key:"setAuthenticationInfo",value:function(e,t){this._currentUser=null,this._loggedIn=!!t&&!!e,this._serverInfo.AccessToken=e,this._serverInfo.UserId=t,g(this)}},{key:"serverInfo",value:function(e){return e&&(this._serverInfo=e),this._serverInfo}},{key:"getCurrentUserId",value:function(){return this._loggedIn?this._serverInfo.UserId:null}},{key:"accessToken",value:function(){return this._loggedIn?this._serverInfo.AccessToken:null}},{key:"serverId",value:function(){return this.serverInfo().Id}},{key:"serverName",value:function(){return this.serverInfo().Name}},{key:"ajax",value:function(e,t){return e?this.fetch(e,t):Promise.reject("Request cannot be null")}},{key:"getCurrentUser",value:function(e){if(this._currentUser)return Promise.resolve(this._currentUser);var t=this.getCurrentUserId();if(!t)return Promise.reject();var r,n=this,i=this.getUser(t).then((function(e){return u.setItem("user-".concat(e.Id,"-").concat(e.ServerId),JSON.stringify(e)),n._currentUser=e,e})).catch((function(e){if(!e.status&&t&&n.accessToken()&&(r=E(n,t)))return Promise.resolve(r);throw e}));return!this.lastFetch&&!1!==e&&(r=E(n,t))?Promise.resolve(r):i}},{key:"isLoggedIn",value:function(){return this._loggedIn}},{key:"logout",value:function(){var e=this;p(this),this.closeWebSocket();var t=function(){var t=e.serverInfo();t&&t.UserId&&t.Id&&u.removeItem("user-".concat(t.UserId,"-").concat(t.Id)),e.setAuthenticationInfo(null,null)};if(this.accessToken()){var r=this.getUrl("Sessions/Logout");return this.ajax({type:"POST",url:r}).then(t,t)}return t(),Promise.resolve()}},{key:"authenticateUserByName",value:function(e,t){var r=this;if(!e)return Promise.reject();var n=this.getUrl("Users/authenticatebyname");return new Promise((function(i,o){var a={Username:e,Pw:t||""};r.ajax({type:"POST",url:n,data:JSON.stringify(a),dataType:"json",contentType:"application/json"}).then((function(e){var t=function(){g(r),i(e)};r.onAuthenticated?r.onAuthenticated(r,e).then(t):t()})).catch(o)}))}},{key:"quickConnect",value:function(e){var t=this;if(!e)return Promise.reject();var r=this.getUrl("Users/AuthenticateWithQuickConnect");return new Promise((function(n,i){var o={Secret:e};t.ajax({type:"POST",url:r,data:JSON.stringify(o),dataType:"json",contentType:"application/json"}).then((function(e){var r=function(){g(t),n(e)};t.onAuthenticated?t.onAuthenticated(t,e).then(r):r()})).catch((function(){throw new Error("quickConnect: error authenticating with the server")}))}))}},{key:"getQuickConnect",value:function(e){var t=this.getUrl("/QuickConnect/"+e);return this.getJSON(t)}},{key:"ensureWebSocket",value:function(){if(!this.isWebSocketOpenOrConnecting()&&this.isWebSocketSupported())try{this.openWebSocket()}catch(e){console.log("Error opening web socket: ".concat(e))}}},{key:"openWebSocket",value:function(){var e=this.accessToken();if(!e)throw new Error("Cannot open web socket without access token.");var t=this.getUrl("socket");t=m(t,"emby/socket","embywebsocket"),t=m(t,"https:","wss:"),t=m(t,"http:","ws:"),t+="?api_key=".concat(e),t+="&deviceId=".concat(this.deviceId()),console.log("opening web socket with url: ".concat(t));var r,i,o=new WebSocket(t);o.onmessage=j.bind(this),o.onopen=L.bind(this),o.onerror=C.bind(this),r=this,(i=o).onclose=function(){console.log("web socket closed"),x(r),r._webSocket===i&&(console.log("nulling out web socket"),r._webSocket=null),setTimeout((function(){n.trigger(r,"websocketclose")}),0)},this._webSocket=o}},{key:"closeWebSocket",value:function(){var e=this._webSocket;e&&e.readyState===WebSocket.OPEN&&e.close()}},{key:"sendWebSocketMessage",value:function(e,t){console.log("Sending web socket message: ".concat(e));var r={MessageType:e};t&&(r.Data=t),r=JSON.stringify(r),this._webSocket.send(r)}},{key:"sendMessage",value:function(e,t){this.isWebSocketOpen()&&this.sendWebSocketMessage(e,t)}},{key:"isMessageChannelOpen",value:function(){return this.isWebSocketOpen()}},{key:"isWebSocketOpen",value:function(){var e=this._webSocket;return!!e&&e.readyState===WebSocket.OPEN}},{key:"isWebSocketOpenOrConnecting",value:function(){var e=this._webSocket;return!!e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)}},{key:"get",value:function(e){return this.ajax({type:"GET",url:e})}},{key:"getJSON",value:function(e,t){return this.fetch({url:e,type:"GET",dataType:"json",headers:{accept:"application/json"}},t)}},{key:"updateServerInfo",value:function(e,t){if(null==e)throw new Error("server cannot be null");if(this.serverInfo(e),!t)throw new Error("serverUrl cannot be null. serverInfo: ".concat(JSON.stringify(e)));console.log("Setting server address to ".concat(t)),this.serverAddress(t)}},{key:"isWebSocketSupported",value:function(){try{return null!=WebSocket}catch(e){return!1}}},{key:"clearAuthenticationInfo",value:function(){this.setAuthenticationInfo(null,null)}},{key:"encodeName",value:function(e){var t=I({name:e=(e=(e=e.split("/").join("-")).split("&").join("-")).split("?").join("-")});return t.substring(t.indexOf("=")+1).replace("'","%27")}},{key:"getServerTime",value:function(){var e=this.getUrl("GetUTCTime");return this.ajax({type:"GET",url:e})}},{key:"getDownloadSpeed",value:function(e){var t=this;return new Promise((function(r,n){var i=t.getUrl("Playback/BitrateTest",{Size:e});console.log("Requesting ".concat(i));var o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType="blob",o.timeout=5e3;var a,s={"Cache-Control":"no-cache, no-store"};for(var u in t.setRequestHeaders(s),s)o.setRequestHeader(u,s[u]);o.onreadystatechange=function(){o.readyState==XMLHttpRequest.HEADERS_RECEIVED&&(a=performance.now())},o.onload=function(){if(o.status<400){var t=.001*(performance.now()-a),i=o.response.size,s=i/t,u=Math.round(8*s);console.debug("BitrateTest ".concat(i," bytes loaded (").concat(e," requested) in ").concat(t," seconds -> ").concat(u," bps")),r(u)}else n("BitrateTest failed with ".concat(o.status," status"))},o.onabort=function(){n("BitrateTest abort")},o.onerror=function(){n("BitrateTest error")},o.ontimeout=function(){n("BitrateTest timeout")},o.send(null)}))}},{key:"detectBitrate",value:function(e){if(!e&&this.lastDetectedBitrate&&(new Date).getTime()-(this.lastDetectedBitrateTime||0)<=36e5)return Promise.resolve(this.lastDetectedBitrate);var t=this;return this.getEndpointInfo().then((function(e){return D(t,e)}),(function(e){return D(t,{})}))}},{key:"getItem",value:function(e,t){if(!t)throw new Error("null itemId");var r=e?this.getUrl("Users/".concat(e,"/Items/").concat(t)):this.getUrl("Items/".concat(t));return this.getJSON(r)}},{key:"getRootFolder",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Users/".concat(e,"/Items/Root"));return this.getJSON(t)}},{key:"getNotificationSummary",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Notifications/".concat(e,"/Summary"));return this.getJSON(t)}},{key:"getNotifications",value:function(e,t){if(!e)throw new Error("null userId");var r=this.getUrl("Notifications/".concat(e),t||{});return this.getJSON(r)}},{key:"markNotificationsRead",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null idList");var n=r?"Read":"Unread",i={UserId:e,Ids:t.join(",")},o=this.getUrl("Notifications/".concat(e,"/").concat(n),i);return this.ajax({type:"POST",url:o})}},{key:"getRemoteImageProviders",value:function(e){if(!e)throw new Error("null options");var t=M(this,e),r=this.getUrl("".concat(t,"/RemoteImages/Providers"),e);return this.getJSON(r)}},{key:"getAvailableRemoteImages",value:function(e){if(!e)throw new Error("null options");var t=M(this,e),r=this.getUrl("".concat(t,"/RemoteImages"),e);return this.getJSON(r)}},{key:"downloadRemoteImage",value:function(e){if(!e)throw new Error("null options");var t=M(this,e),r=this.getUrl("".concat(t,"/RemoteImages/Download"),e);return this.ajax({type:"POST",url:r})}},{key:"getRecordingFolders",value:function(e){var t=this.getUrl("LiveTv/Recordings/Folders",{userId:e});return this.getJSON(t)}},{key:"getLiveTvInfo",value:function(e){var t=this.getUrl("LiveTv/Info",e||{});return this.getJSON(t)}},{key:"getLiveTvGuideInfo",value:function(e){var t=this.getUrl("LiveTv/GuideInfo",e||{});return this.getJSON(t)}},{key:"getLiveTvChannel",value:function(e,t){if(!e)throw new Error("null id");var r={};t&&(r.userId=t);var n=this.getUrl("LiveTv/Channels/".concat(e),r);return this.getJSON(n)}},{key:"getLiveTvChannels",value:function(e){var t=this.getUrl("LiveTv/Channels",e||{});return this.getJSON(t)}},{key:"getLiveTvPrograms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.channelIds&&e.channelIds.length>1800?this.ajax({type:"POST",url:this.getUrl("LiveTv/Programs"),data:JSON.stringify(e),contentType:"application/json",dataType:"json"}):this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs",e),dataType:"json"})}},{key:"getLiveTvRecommendedPrograms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.ajax({type:"GET",url:this.getUrl("LiveTv/Programs/Recommended",e),dataType:"json"})}},{key:"getLiveTvRecordings",value:function(e){var t=this.getUrl("LiveTv/Recordings",e||{});return this.getJSON(t)}},{key:"getLiveTvRecordingSeries",value:function(e){var t=this.getUrl("LiveTv/Recordings/Series",e||{});return this.getJSON(t)}},{key:"getLiveTvRecordingGroups",value:function(e){var t=this.getUrl("LiveTv/Recordings/Groups",e||{});return this.getJSON(t)}},{key:"getLiveTvRecordingGroup",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/Recordings/Groups/".concat(e));return this.getJSON(t)}},{key:"getLiveTvRecording",value:function(e,t){if(!e)throw new Error("null id");var r={};t&&(r.userId=t);var n=this.getUrl("LiveTv/Recordings/".concat(e),r);return this.getJSON(n)}},{key:"getLiveTvProgram",value:function(e,t){if(!e)throw new Error("null id");var r={};t&&(r.userId=t);var n=this.getUrl("LiveTv/Programs/".concat(e),r);return this.getJSON(n)}},{key:"deleteLiveTvRecording",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/Recordings/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"cancelLiveTvTimer",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/Timers/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"getLiveTvTimers",value:function(e){var t=this.getUrl("LiveTv/Timers",e||{});return this.getJSON(t)}},{key:"getLiveTvTimer",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/Timers/".concat(e));return this.getJSON(t)}},{key:"getNewLiveTvTimerDefaults",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("LiveTv/Timers/Defaults",e);return this.getJSON(t)}},{key:"createLiveTvTimer",value:function(e){if(!e)throw new Error("null item");var t=this.getUrl("LiveTv/Timers");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updateLiveTvTimer",value:function(e){if(!e)throw new Error("null item");var t=this.getUrl("LiveTv/Timers/".concat(e.Id));return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"resetLiveTvTuner",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/Tuners/".concat(e,"/Reset"));return this.ajax({type:"POST",url:t})}},{key:"getLiveTvSeriesTimers",value:function(e){var t=this.getUrl("LiveTv/SeriesTimers",e||{});return this.getJSON(t)}},{key:"getLiveTvSeriesTimer",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/SeriesTimers/".concat(e));return this.getJSON(t)}},{key:"cancelLiveTvSeriesTimer",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("LiveTv/SeriesTimers/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"createLiveTvSeriesTimer",value:function(e){if(!e)throw new Error("null item");var t=this.getUrl("LiveTv/SeriesTimers");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updateLiveTvSeriesTimer",value:function(e){if(!e)throw new Error("null item");var t=this.getUrl("LiveTv/SeriesTimers/".concat(e.Id));return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"getRegistrationInfo",value:function(e){var t=this.getUrl("Registrations/".concat(e));return this.getJSON(t)}},{key:"getSystemInfo",value:function(e){var t=this.getUrl("System/Info"),r=this;return this.getJSON(t).then((function(e){return r.setSystemInfo(e),Promise.resolve(e)}))}},{key:"getSyncStatus",value:function(){var e=this.getUrl("Sync/"+itemId+"/Status");return this.ajax({url:e,type:"POST",dataType:"json",contentType:"application/json",data:JSON.stringify({TargetId:this.deviceId()})})}},{key:"getPublicSystemInfo",value:function(){var e=this.getUrl("System/Info/Public"),t=this;return this.getJSON(e).then((function(e){return t.setSystemInfo(e),Promise.resolve(e)}))}},{key:"getInstantMixFromItem",value:function(e,t){var r=this.getUrl("Items/".concat(e,"/InstantMix"),t);return this.getJSON(r)}},{key:"getEpisodes",value:function(e,t){var r=this.getUrl("Shows/".concat(e,"/Episodes"),t);return this.getJSON(r)}},{key:"getDisplayPreferences",value:function(e,t,r){var n=this.getUrl("DisplayPreferences/".concat(e),{userId:t,client:r});return this.getJSON(n)}},{key:"updateDisplayPreferences",value:function(e,t,r,n){var i=this.getUrl("DisplayPreferences/".concat(e),{userId:r,client:n});return this.ajax({type:"POST",url:i,data:JSON.stringify(t),contentType:"application/json"})}},{key:"getSeasons",value:function(e,t){var r=this.getUrl("Shows/".concat(e,"/Seasons"),t);return this.getJSON(r)}},{key:"getSimilarItems",value:function(e,t){var r=this.getUrl("Items/".concat(e,"/Similar"),t);return this.getJSON(r)}},{key:"getCultures",value:function(){var e=this.getUrl("Localization/cultures");return this.getJSON(e)}},{key:"getCountries",value:function(){var e=this.getUrl("Localization/countries");return this.getJSON(e)}},{key:"getPlaybackInfo",value:function(e,t,r){var n={DeviceProfile:r};return this.ajax({url:this.getUrl("Items/".concat(e,"/PlaybackInfo"),t),type:"POST",data:JSON.stringify(n),contentType:"application/json",dataType:"json"})}},{key:"getLiveStreamMediaInfo",value:function(e){var t={LiveStreamId:e};return this.ajax({url:this.getUrl("LiveStreams/MediaInfo"),type:"POST",data:JSON.stringify(t),contentType:"application/json",dataType:"json"})}},{key:"getIntros",value:function(e){return this.getJSON(this.getUrl("Users/".concat(this.getCurrentUserId(),"/Items/").concat(e,"/Intros")))}},{key:"getDirectoryContents",value:function(e,t){if(!e)throw new Error("null path");if("string"!=typeof e)throw new Error("invalid path");(t=t||{}).path=e;var r=this.getUrl("Environment/DirectoryContents",t);return this.getJSON(r)}},{key:"getNetworkShares",value:function(e){if(!e)throw new Error("null path");var t={};t.path=e;var r=this.getUrl("Environment/NetworkShares",t);return this.getJSON(r)}},{key:"getParentPath",value:function(e){if(!e)throw new Error("null path");var t={};t.path=e;var r=this.getUrl("Environment/ParentPath",t);return this.ajax({type:"GET",url:r,dataType:"text"})}},{key:"getDrives",value:function(){var e=this.getUrl("Environment/Drives");return this.getJSON(e)}},{key:"getNetworkDevices",value:function(){var e=this.getUrl("Environment/NetworkDevices");return this.getJSON(e)}},{key:"cancelPackageInstallation",value:function(e){if(!e)throw new Error("null installationId");var t=this.getUrl("Packages/Installing/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"refreshItem",value:function(e,t){if(!e)throw new Error("null itemId");var r=this.getUrl("Items/".concat(e,"/Refresh"),t||{});return this.ajax({type:"POST",url:r})}},{key:"installPlugin",value:function(e,t,r){if(!e)throw new Error("null name");var n={AssemblyGuid:t};r&&(n.version=r);var i=this.getUrl("Packages/Installed/".concat(e),n);return this.ajax({type:"POST",url:i})}},{key:"restartServer",value:function(){var e=this.getUrl("System/Restart");return this.ajax({type:"POST",url:e})}},{key:"shutdownServer",value:function(){var e=this.getUrl("System/Shutdown");return this.ajax({type:"POST",url:e})}},{key:"getPackageInfo",value:function(e,t){if(!e)throw new Error("null name");var r={AssemblyGuid:t},n=this.getUrl("Packages/".concat(e),r);return this.getJSON(n)}},{key:"getVirtualFolders",value:function(){var e="Library/VirtualFolders";return e=this.getUrl(e),this.getJSON(e)}},{key:"getPhysicalPaths",value:function(){var e=this.getUrl("Library/PhysicalPaths");return this.getJSON(e)}},{key:"getServerConfiguration",value:function(){var e=this.getUrl("System/Configuration");return this.getJSON(e)}},{key:"getDevicesOptions",value:function(){var e=this.getUrl("System/Configuration/devices");return this.getJSON(e)}},{key:"deleteDevice",value:function(e){var t=this.getUrl("Devices",{Id:e});return this.ajax({type:"DELETE",url:t})}},{key:"getContentUploadHistory",value:function(){var e=this.getUrl("Devices/CameraUploads",{DeviceId:this.deviceId()});return this.getJSON(e)}},{key:"getNamedConfiguration",value:function(e){var t=this.getUrl("System/Configuration/".concat(e));return this.getJSON(t)}},{key:"getScheduledTasks",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("ScheduledTasks",e);return this.getJSON(t)}},{key:"startScheduledTask",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("ScheduledTasks/Running/".concat(e));return this.ajax({type:"POST",url:t})}},{key:"getScheduledTask",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("ScheduledTasks/".concat(e));return this.getJSON(t)}},{key:"getNextUpEpisodes",value:function(e){var t=this.getUrl("Shows/NextUp",e);return this.getJSON(t)}},{key:"stopScheduledTask",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("ScheduledTasks/Running/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"getPluginConfiguration",value:function(e){if(!e)throw new Error("null Id");var t=this.getUrl("Plugins/".concat(e,"/Configuration"));return this.getJSON(t)}},{key:"getAvailablePlugins",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.PackageType="UserInstalled";var t=this.getUrl("Packages",e);return this.getJSON(t)}},{key:"uninstallPlugin",value:function(e){if(!e)throw new Error("null Id");var t=this.getUrl("Plugins/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"uninstallPluginByVersion",value:function(e,t){if(!e)throw new Error("null Id");if(!t)throw new Error("null Version");var r=this.getUrl("Plugins/".concat(e,"/").concat(t));return this.ajax({type:"DELETE",url:r})}},{key:"enablePlugin",value:function(e,t){if(!e)throw new Error("null Id");if(!t)throw new Error("null Id");var r=this.getUrl("Plugins/".concat(e,"/").concat(t,"/Enable"));return this.ajax({type:"POST",url:r})}},{key:"disablePlugin",value:function(e,t){if(!e)throw new Error("null Id");if(!t)throw new Error("null Version");var r=this.getUrl("Plugins/".concat(e,"/").concat(t,"/Disable"));return this.ajax({type:"POST",url:r})}},{key:"removeVirtualFolder",value:function(e,t){if(!e)throw new Error("null name");var r="Library/VirtualFolders";return r=this.getUrl(r,{refreshLibrary:!!t,name:e}),this.ajax({type:"DELETE",url:r})}},{key:"addVirtualFolder",value:function(e,t,r,n){if(!e)throw new Error("null name");var i={};t&&(i.collectionType=t),i.refreshLibrary=!!r,i.name=e;var o="Library/VirtualFolders";return o=this.getUrl(o,i),this.ajax({type:"POST",url:o,data:JSON.stringify({LibraryOptions:n}),contentType:"application/json"})}},{key:"updateVirtualFolderOptions",value:function(e,t){if(!e)throw new Error("null name");var r="Library/VirtualFolders/LibraryOptions";return r=this.getUrl(r),this.ajax({type:"POST",url:r,data:JSON.stringify({Id:e,LibraryOptions:t}),contentType:"application/json"})}},{key:"renameVirtualFolder",value:function(e,t,r){if(!e)throw new Error("null name");var n="Library/VirtualFolders/Name";return n=this.getUrl(n,{refreshLibrary:!!r,newName:t,name:e}),this.ajax({type:"POST",url:n})}},{key:"addMediaPath",value:function(e,t,r,n){if(!e)throw new Error("null virtualFolderName");if(!t)throw new Error("null mediaPath");var i="Library/VirtualFolders/Paths",o={Path:t};return r&&(o.NetworkPath=r),i=this.getUrl(i,{refreshLibrary:!!n}),this.ajax({type:"POST",url:i,data:JSON.stringify({Name:e,PathInfo:o}),contentType:"application/json"})}},{key:"updateMediaPath",value:function(e,t){if(!e)throw new Error("null virtualFolderName");if(!t)throw new Error("null pathInfo");var r="Library/VirtualFolders/Paths/Update";return r=this.getUrl(r),this.ajax({type:"POST",url:r,data:JSON.stringify({Name:e,PathInfo:t}),contentType:"application/json"})}},{key:"removeMediaPath",value:function(e,t,r){if(!e)throw new Error("null virtualFolderName");if(!t)throw new Error("null mediaPath");var n="Library/VirtualFolders/Paths";return n=this.getUrl(n,{refreshLibrary:!!r,path:t,name:e}),this.ajax({type:"DELETE",url:n})}},{key:"deleteUser",value:function(e){if(!e)throw new Error("null id");var t=this.getUrl("Users/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"deleteUserImage",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null imageType");var n=this.getUrl("Users/".concat(e,"/Images/").concat(t));return null!=r&&(n+="/".concat(r)),this.ajax({type:"DELETE",url:n})}},{key:"deleteItemImage",value:function(e,t,r){if(!t)throw new Error("null imageType");var n=this.getUrl("Items/".concat(e,"/Images"));return n+="/".concat(t),null!=r&&(n+="/".concat(r)),this.ajax({type:"DELETE",url:n})}},{key:"deleteItem",value:function(e){if(!e)throw new Error("null itemId");var t=this.getUrl("Items/".concat(e));return this.ajax({type:"DELETE",url:t})}},{key:"stopActiveEncodings",value:function(e){var t={deviceId:this.deviceId()};e&&(t.PlaySessionId=e);var r=this.getUrl("Videos/ActiveEncodings",t);return this.ajax({type:"DELETE",url:r})}},{key:"reportCapabilities",value:function(e){var t=this.getUrl("Sessions/Capabilities/Full");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updateItemImageIndex",value:function(e,t,r,n){if(!t)throw new Error("null imageType");var i={newIndex:n},o=this.getUrl("Items/".concat(e,"/Images/").concat(t,"/").concat(r,"/Index"),i);return this.ajax({type:"POST",url:o})}},{key:"getItemImageInfos",value:function(e){var t=this.getUrl("Items/".concat(e,"/Images"));return this.getJSON(t)}},{key:"getCriticReviews",value:function(e,t){if(!e)throw new Error("null itemId");var r=this.getUrl("Items/".concat(e,"/CriticReviews"),t);return this.getJSON(r)}},{key:"getItemDownloadUrl",value:function(e){if(!e)throw new Error("itemId cannot be empty");var t="Items/".concat(e,"/Download");return this.getUrl(t,{api_key:this.accessToken()})}},{key:"getSessions",value:function(e){var t=this.getUrl("Sessions",e);return this.getJSON(t)}},{key:"uploadUserImage",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null imageType");if(!r)throw new Error("File must be an image.");if(!r.type.startsWith("image/"))throw new Error("File must be an image.");var n=this;return new Promise((function(i,o){var a=new FileReader;a.onerror=function(){o()},a.onabort=function(){o()},a.onload=function(a){var s=a.target.result.split(",")[1],u=n.getUrl("Users/".concat(e,"/Images/").concat(t));n.ajax({type:"POST",url:u,data:s,contentType:r.type}).then(i,o)},a.readAsDataURL(r)}))}},{key:"uploadItemImage",value:function(e,t,r){if(!e)throw new Error("null itemId");if(!t)throw new Error("null imageType");if(!r)throw new Error("File must be an image.");if(!r.type.startsWith("image/"))throw new Error("File must be an image.");var n=this.getUrl("Items/".concat(e,"/Images"));n+="/".concat(t);var i=this;return new Promise((function(e,t){var o=new FileReader;o.onerror=function(){t()},o.onabort=function(){t()},o.onload=function(o){var a=o.target.result.split(",")[1];i.ajax({type:"POST",url:n,data:a,contentType:r.type}).then(e,t)},o.readAsDataURL(r)}))}},{key:"uploadItemSubtitle",value:function(e,t,r,n){var i=this;if(!e)throw new SyntaxError("Missing itemId");if(!t)throw new SyntaxError("Missing language");if("boolean"!=typeof r)throw new TypeError("Parameter isForced must be a boolean.");if(!n)throw new SyntaxError("File must be a subtitle file.");var o=n.name.substring(n.name.lastIndexOf(".")+1).toLowerCase();if(!["sub","srt","vtt","ass","ssa"].includes(o))throw new Error("Invalid subtitle format.");var a=this.getUrl("Videos/".concat(e,"/Subtitles"));return new Promise((function(e,s){var u=new FileReader;u.onerror=function(){s()},u.onabort=function(){s()},u.onload=function(n){var u=n.target.result.split(",")[1];i.ajax({type:"POST",url:a,contentType:"application/json",data:JSON.stringify({language:t,format:o,isForced:r,data:u})}).then(e,s)},u.readAsDataURL(n)}))}},{key:"getInstalledPlugins",value:function(){var e=this.getUrl("Plugins",{});return this.getJSON(e)}},{key:"getUser",value:function(e){if(!e)throw new Error("Must supply a userId");var t=this.getUrl("Users/".concat(e));return this.getJSON(t)}},{key:"getStudio",value:function(e,t){if(!e)throw new Error("null name");var r={};t&&(r.userId=t);var n=this.getUrl("Studios/".concat(this.encodeName(e)),r);return this.getJSON(n)}},{key:"getGenre",value:function(e,t){if(!e)throw new Error("null name");var r={};t&&(r.userId=t);var n=this.getUrl("Genres/".concat(this.encodeName(e)),r);return this.getJSON(n)}},{key:"getMusicGenre",value:function(e,t){if(!e)throw new Error("null name");var r={};t&&(r.userId=t);var n=this.getUrl("MusicGenres/".concat(this.encodeName(e)),r);return this.getJSON(n)}},{key:"getArtist",value:function(e,t){if(!e)throw new Error("null name");var r={};t&&(r.userId=t);var n=this.getUrl("Artists/".concat(this.encodeName(e)),r);return this.getJSON(n)}},{key:"getPerson",value:function(e,t){if(!e)throw new Error("null name");var r={};t&&(r.userId=t);var n=this.getUrl("Persons/".concat(this.encodeName(e)),r);return this.getJSON(n)}},{key:"getPublicUsers",value:function(){var e=this.getUrl("users/public");return this.ajax({type:"GET",url:e,dataType:"json"},!1)}},{key:"getUsers",value:function(e){var t=this.getUrl("users",e||{});return this.getJSON(t)}},{key:"getParentalRatings",value:function(){var e=this.getUrl("Localization/ParentalRatings");return this.getJSON(e)}},{key:"getDefaultImageQuality",value:function(e){return"backdrop"===e.toLowerCase()?80:90}},{key:"getUserImageUrl",value:function(e,t){if(!e)throw new Error("null userId");t=t||{};var r="Users/".concat(e,"/Images/").concat(t.type);return null!=t.index&&(r+="/".concat(t.index)),_(this,t),delete t.type,delete t.index,this.getUrl(r,t)}},{key:"getImageUrl",value:function(e,t){if(!e)throw new Error("itemId cannot be empty");t=t||{};var r="Items/".concat(e,"/Images/").concat(t.type);return null!=t.index&&(r+="/".concat(t.index)),t.quality=t.quality||this.getDefaultImageQuality(t.type),this.normalizeImageOptions&&this.normalizeImageOptions(t),delete t.type,delete t.index,this.getUrl(r,t)}},{key:"getScaledImageUrl",value:function(e,t){if(!e)throw new Error("itemId cannot be empty");t=t||{};var r="Items/".concat(e,"/Images/").concat(t.type);return null!=t.index&&(r+="/".concat(t.index)),_(this,t),delete t.type,delete t.index,delete t.minScale,this.getUrl(r,t)}},{key:"getThumbImageUrl",value:function(e,t){if(!e)throw new Error("null item");return(t=t||{}).imageType="thumb",e.ImageTags&&e.ImageTags.Thumb?(t.tag=e.ImageTags.Thumb,this.getImageUrl(e.Id,t)):e.ParentThumbItemId?(t.tag=e.ImageTags.ParentThumbImageTag,this.getImageUrl(e.ParentThumbItemId,t)):null}},{key:"updateUserPassword",value:function(e,t,r){if(!e)return Promise.reject();var n=this.getUrl("Users/".concat(e,"/Password"));return this.ajax({type:"POST",url:n,data:JSON.stringify({CurrentPw:t||"",NewPw:r}),contentType:"application/json"})}},{key:"updateEasyPassword",value:function(e,t){if(e){var r=this.getUrl("Users/".concat(e,"/EasyPassword"));return this.ajax({type:"POST",url:r,data:JSON.stringify({NewPw:t}),contentType:"application/json"})}Promise.reject()}},{key:"resetUserPassword",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Users/".concat(e,"/Password"));return this.ajax({type:"POST",url:t,data:JSON.stringify({resetPassword:!0}),contentType:"application/json"})}},{key:"resetEasyPassword",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Users/".concat(e,"/EasyPassword"));return this.ajax({type:"POST",url:t,data:JSON.stringify({resetPassword:!0}),contentType:"application/json"})}},{key:"updateServerConfiguration",value:function(e){if(!e)throw new Error("null configuration");var t=this.getUrl("System/Configuration");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updateNamedConfiguration",value:function(e,t){if(!t)throw new Error("null configuration");var r=this.getUrl("System/Configuration/".concat(e));return this.ajax({type:"POST",url:r,data:JSON.stringify(t),contentType:"application/json"})}},{key:"updateItem",value:function(e){if(!e)throw new Error("null item");var t=this.getUrl("Items/".concat(e.Id));return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updatePluginSecurityInfo",value:function(e){var t=this.getUrl("Plugins/SecurityInfo");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"createUser",value:function(e){var t=this.getUrl("Users/New");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json",headers:{accept:"application/json"}})}},{key:"updateUser",value:function(e){if(!e)throw new Error("null user");var t=this.getUrl("Users/".concat(e.Id));return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"updateUserPolicy",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null policy");var r=this.getUrl("Users/".concat(e,"/Policy"));return this.ajax({type:"POST",url:r,data:JSON.stringify(t),contentType:"application/json"})}},{key:"updateUserConfiguration",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null configuration");var r=this.getUrl("Users/".concat(e,"/Configuration"));return this.ajax({type:"POST",url:r,data:JSON.stringify(t),contentType:"application/json"})}},{key:"updateScheduledTaskTriggers",value:function(e,t){if(!e)throw new Error("null id");if(!t)throw new Error("null triggers");var r=this.getUrl("ScheduledTasks/".concat(e,"/Triggers"));return this.ajax({type:"POST",url:r,data:JSON.stringify(t),contentType:"application/json"})}},{key:"updatePluginConfiguration",value:function(e,t){if(!e)throw new Error("null Id");if(!t)throw new Error("null configuration");var r=this.getUrl("Plugins/".concat(e,"/Configuration"));return this.ajax({type:"POST",url:r,data:JSON.stringify(t),contentType:"application/json"})}},{key:"getAncestorItems",value:function(e,t){if(!e)throw new Error("null itemId");var r={};t&&(r.userId=t);var n=this.getUrl("Items/".concat(e,"/Ancestors"),r);return this.getJSON(n)}},{key:"getItems",value:function(e,t){var r;return r="string"===h(e).toString().toLowerCase()?this.getUrl("Users/".concat(e,"/Items"),t):this.getUrl("Items",t),this.getJSON(r)}},{key:"getResumableItems",value:function(e,t){return this.isMinServerVersion("3.2.33")?this.getJSON(this.getUrl("Users/".concat(e,"/Items/Resume"),t)):this.getItems(e,Object.assign({SortBy:"DatePlayed",SortOrder:"Descending",Filters:"IsResumable",Recursive:!0,CollapseBoxSetItems:!1,ExcludeLocationTypes:"Virtual"},t))}},{key:"getMovieRecommendations",value:function(e){return this.getJSON(this.getUrl("Movies/Recommendations",e))}},{key:"getUpcomingEpisodes",value:function(e){return this.getJSON(this.getUrl("Shows/Upcoming",e))}},{key:"getUserViews",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,r=this.getUrl("Users/".concat(t||this.getCurrentUserId(),"/Views"),e);return this.getJSON(r)}},{key:"getArtists",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("Artists",t);return this.getJSON(r)}},{key:"getAlbumArtists",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("Artists/AlbumArtists",t);return this.getJSON(r)}},{key:"getGenres",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("Genres",t);return this.getJSON(r)}},{key:"getMusicGenres",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("MusicGenres",t);return this.getJSON(r)}},{key:"getPeople",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("Persons",t);return this.getJSON(r)}},{key:"getStudios",value:function(e,t){if(!e)throw new Error("null userId");(t=t||{}).userId=e;var r=this.getUrl("Studios",t);return this.getJSON(r)}},{key:"getLocalTrailers",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var r=this.getUrl("Users/".concat(e,"/Items/").concat(t,"/LocalTrailers"));return this.getJSON(r)}},{key:"getAdditionalVideoParts",value:function(e,t){if(!t)throw new Error("null itemId");var r={};e&&(r.userId=e);var n=this.getUrl("Videos/".concat(t,"/AdditionalParts"),r);return this.getJSON(n)}},{key:"getThemeMedia",value:function(e,t,r){if(!t)throw new Error("null itemId");var n={};e&&(n.userId=e),n.InheritFromParent=r||!1;var i=this.getUrl("Items/".concat(t,"/ThemeMedia"),n);return this.getJSON(i)}},{key:"getSearchHints",value:function(e){var t=this.getUrl("Search/Hints",e),r=this.serverId();return this.getJSON(t).then((function(e){return e.SearchHints.forEach((function(e){e.ServerId=r})),e}))}},{key:"getSpecialFeatures",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var r=this.getUrl("Users/".concat(e,"/Items/").concat(t,"/SpecialFeatures"));return this.getJSON(r)}},{key:"getDateParamValue",value:function(e){return e.toISOString()}},{key:"markPlayed",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var n={};r&&(n.DatePlayed=this.getDateParamValue(r));var i=this.getUrl("Users/".concat(e,"/PlayedItems/").concat(t),n);return this.ajax({type:"POST",url:i,dataType:"json"})}},{key:"markUnplayed",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var r=this.getUrl("Users/".concat(e,"/PlayedItems/").concat(t));return this.ajax({type:"DELETE",url:r,dataType:"json"})}},{key:"updateFavoriteStatus",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var n=this.getUrl("Users/".concat(e,"/FavoriteItems/").concat(t)),i=r?"POST":"DELETE";return this.ajax({type:i,url:n,dataType:"json"})}},{key:"updateUserItemRating",value:function(e,t,r){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var n=this.getUrl("Users/".concat(e,"/Items/").concat(t,"/Rating"),{likes:r});return this.ajax({type:"POST",url:n,dataType:"json"})}},{key:"getItemCounts",value:function(e){var t={};e&&(t.userId=e);var r=this.getUrl("Items/Counts",t);return this.getJSON(r)}},{key:"clearUserItemRating",value:function(e,t){if(!e)throw new Error("null userId");if(!t)throw new Error("null itemId");var r=this.getUrl("Users/".concat(e,"/Items/").concat(t,"/Rating"));return this.ajax({type:"DELETE",url:r,dataType:"json"})}},{key:"reportPlaybackStart",value:(o=f(c().mark((function e(t){var r;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}throw new Error("null options");case 2:return e.next=4,T(this,!1);case 4:return p(this),r=this.getUrl("Sessions/Playing"),e.abrupt("return",this.ajax({type:"POST",data:JSON.stringify(t),contentType:"application/json",url:r}));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"reportPlaybackProgress",value:function(e){var t=this;if(!e)throw new Error("null options");var r=e.EventName||"timeupdate",n=v[r]||0,i=(new Date).getTime()-(this.lastPlaybackProgressReport||0),o=e.PositionTicks;if(i<n&&"timeupdate"===r&&null!=o){var a=1e4*i+(this.lastPlaybackProgressReportTicks||0);Math.abs(o-a)>=5e7&&(n=0)}var s=Math.max(0,n-i);if(this.lastPlaybackProgressOptions=e,this.reportPlaybackProgressPromiseDelay)return n<this.reportPlaybackProgressTimeout&&(this.reportPlaybackProgressTimeout=n,this.reportPlaybackProgressPromiseDelay.reset(s)),this.reportPlaybackProgressPromise;var u=new l(s),c=!1,h=u.promise().catch((function(){c=!0})).then((function(){return c?Promise.resolve():function(){t.lastPlaybackProgressReport=(new Date).getTime(),t.lastPlaybackProgressReportTicks=t.lastPlaybackProgressOptions.PositionTicks;var e=t.getUrl("Sessions/Playing/Progress");return t.ajax({type:"POST",data:JSON.stringify(t.lastPlaybackProgressOptions),contentType:"application/json",url:e})}()})).finally((function(){delete t.lastPlaybackProgressOptions,delete t.reportPlaybackProgressTimeout,delete t.reportPlaybackProgressPromise,delete t.reportPlaybackProgressPromiseDelay,delete t.reportPlaybackProgressReset}));return this.reportPlaybackProgressTimeout=n,this.reportPlaybackProgressPromise=h,this.reportPlaybackProgressPromiseDelay=u,this.reportPlaybackProgressReset=function(e){return e?u.resolve():u.reject(),h},h}},{key:"reportOfflineActions",value:function(e){if(!e)throw new Error("null actions");var t=this.getUrl("Sync/OfflineActions");return this.ajax({type:"POST",data:JSON.stringify(e),contentType:"application/json",url:t})}},{key:"syncData",value:function(e){if(!e)throw new Error("null data");var t=this.getUrl("Sync/Data");return this.ajax({type:"POST",data:JSON.stringify(e),contentType:"application/json",url:t,dataType:"json"})}},{key:"getReadySyncItems",value:function(e){if(!e)throw new Error("null deviceId");var t=this.getUrl("Sync/Items/Ready",{TargetId:e});return this.getJSON(t)}},{key:"reportSyncJobItemTransferred",value:function(e){if(!e)throw new Error("null syncJobItemId");var t=this.getUrl("Sync/JobItems/".concat(e,"/Transferred"));return this.ajax({type:"POST",url:t})}},{key:"cancelSyncItems",value:function(e,t){if(!e)throw new Error("null itemIds");var r=this.getUrl("Sync/".concat(t||this.deviceId(),"/Items"),{ItemIds:e.join(",")});return this.ajax({type:"DELETE",url:r})}},{key:"reportPlaybackStopped",value:(i=f(c().mark((function e(t){var r;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}throw new Error("null options");case 2:return e.next=4,T(this,!1);case 4:return g(this),r=this.getUrl("Sessions/Playing/Stopped"),e.abrupt("return",this.ajax({type:"POST",data:JSON.stringify(t),contentType:"application/json",url:r}));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"sendPlayCommand",value:function(e,t){if(!e)throw new Error("null sessionId");if(!t)throw new Error("null options");var r=this.getUrl("Sessions/".concat(e,"/Playing"),t);return this.ajax({type:"POST",url:r})}},{key:"sendCommand",value:function(e,t){if(!e)throw new Error("null sessionId");if(!t)throw new Error("null command");var r={type:"POST",url:this.getUrl("Sessions/".concat(e,"/Command"))};return r.data=JSON.stringify(t),r.contentType="application/json",this.ajax(r)}},{key:"sendMessageCommand",value:function(e,t){if(!e)throw new Error("null sessionId");if(!t)throw new Error("null options");var r={type:"POST",url:this.getUrl("Sessions/".concat(e,"/Message"))};return r.data=JSON.stringify(t),r.contentType="application/json",this.ajax(r)}},{key:"sendPlayStateCommand",value:function(e,t,r){if(!e)throw new Error("null sessionId");if(!t)throw new Error("null command");var n=this.getUrl("Sessions/".concat(e,"/Playing/").concat(t),r||{});return this.ajax({type:"POST",url:n})}},{key:"getSyncPlayGroups",value:function(){var e=this.getUrl("SyncPlay/List");return this.ajax({type:"GET",url:e})}},{key:"createSyncPlayGroup",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/New");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"joinSyncPlayGroup",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Join");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"leaveSyncPlayGroup",value:function(){var e=this.getUrl("SyncPlay/Leave");return this.ajax({type:"POST",url:e})}},{key:"sendSyncPlayPing",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Ping");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlaySetNewQueue",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/SetNewQueue");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlaySetPlaylistItem",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/SetPlaylistItem");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayRemoveFromPlaylist",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/RemoveFromPlaylist");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayMovePlaylistItem",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/MovePlaylistItem");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayQueue",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Queue");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayUnpause",value:function(){var e=this.getUrl("SyncPlay/Unpause");return this.ajax({type:"POST",url:e})}},{key:"requestSyncPlayPause",value:function(){var e=this.getUrl("SyncPlay/Pause");return this.ajax({type:"POST",url:e})}},{key:"requestSyncPlaySeek",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Seek");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayNextItem",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/NextItem");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayPreviousItem",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/PreviousItem");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlaySetRepeatMode",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/SetRepeatMode");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlaySetShuffleMode",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/SetShuffleMode");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayBuffering",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Buffering");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlayReady",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Ready");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"requestSyncPlaySetIgnoreWait",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/SetIgnoreWait");return this.ajax({type:"POST",url:t,data:JSON.stringify(e),contentType:"application/json"})}},{key:"createPackageReview",value:function(e){var t=this.getUrl("Packages/Reviews/".concat(e.id),e);return this.ajax({type:"POST",url:t})}},{key:"getPackageReviews",value:function(e,t,r,n){if(!e)throw new Error("null packageId");var i={};t&&(i.MinRating=t),r&&(i.MaxRating=r),n&&(i.Limit=n);var o=this.getUrl("Packages/".concat(e,"/Reviews"),i);return this.getJSON(o)}},{key:"getSavedEndpointInfo",value:function(){return this._endPointInfo}},{key:"getEndpointInfo",value:function(){var e=this._endPointInfo;if(e)return Promise.resolve(e);var t=this;return this.getJSON(this.getUrl("System/Endpoint")).then((function(e){return b(t,e),e}))}},{key:"getLatestItems",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.getJSON(this.getUrl("Users/".concat(this.getCurrentUserId(),"/Items/Latest"),e))}},{key:"getFilters",value:function(e){return this.getJSON(this.getUrl("Items/Filters2",e))}},{key:"setSystemInfo",value:function(e){this._serverVersion=e.Version}},{key:"serverVersion",value:function(){return this._serverVersion}},{key:"isMinServerVersion",value:function(e){var t=this.serverVersion();return!!t&&function(e,t){e=e.split("."),t=t.split(".");for(var r=0,n=Math.max(e.length,t.length);r<n;r++){var i=parseInt(e[r]||"0"),o=parseInt(t[r]||"0");if(i<o)return-1;if(i>o)return 1}return 0}(t,e)>=0}},{key:"handleMessageReceived",value:function(e){A(this,e)}}],r&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function b(e,t){e._endPointInfo=t}function O(e,t){return(t=t||0)>=20?Promise.reject():function(e){var t=[],r=[],n=e.serverInfo();return n.LocalAddress&&-1===r.indexOf(n.LocalAddress)&&(t.push({url:n.LocalAddress,timeout:0}),r.push(t[t.length-1].url)),n.ManualAddress&&-1===r.indexOf(n.ManualAddress)&&(t.push({url:n.ManualAddress,timeout:100}),r.push(t[t.length-1].url)),n.RemoteAddress&&-1===r.indexOf(n.RemoteAddress)&&(t.push({url:n.RemoteAddress,timeout:200}),r.push(t[t.length-1].url)),console.log("tryReconnect: "+r.join("|")),new Promise((function(r,n){var i={};i.numAddresses=t.length,i.rejects=0,t.map((function(t){setTimeout((function(){i.resolved||function(e,t,r,n,i){console.log("getTryConnectPromise "+t),w(e.getUrl("system/info/public",null,t),{method:"GET",accept:"application/json"},15e3).then((function(){r.resolved||(r.resolved=!0,console.log("Reconnect succeeded to "+t),e.serverAddress(t),n())}),(function(){r.resolved||(console.log("Reconnect failed to "+t),r.rejects++,r.rejects>=r.numAddresses&&i())}))}(e,t.url,i,r,n)}),t.timeout)}))}))}(e).catch((function(r){return console.log("error in tryReconnectInternal: "+(r||"")),new Promise((function(r,n){setTimeout((function(){O(e,t+1).then(r,n)}),500)}))}))}function E(e,t){var r=e.serverId();if(!r)return null;var n=u.getItem("user-".concat(t,"-").concat(r));return n?JSON.parse(n):null}function j(e){A(this,e=JSON.parse(e.data))}var N={};function A(e,t){var r,i,o=t.MessageId;if(o){if(N[o])return;N[o]=!0}"UserDeleted"===t.MessageType?e._currentUser=null:"UserUpdated"===t.MessageType||"UserConfigurationUpdated"===t.MessageType?t.Data.Id===e.getCurrentUserId()&&(e._currentUser=null):"KeepAlive"===t.MessageType?console.debug("Received KeepAlive from server."):"ForceKeepAlive"===t.MessageType&&(console.debug("Received ForceKeepAlive from server. Timeout is ".concat(t.Data," seconds.")),e.sendWebSocketMessage("KeepAlive"),r=e,i=t.Data,x(r),r.keepAliveInterval=setInterval((function(){r.sendWebSocketMessage("KeepAlive")}),1e3*i*.5),r.keepAliveInterval),n.trigger(e,"message",[t])}function x(e){console.debug("Clearing KeepAlive for",e._webSocket),e.keepAliveInterval&&(clearInterval(e.keepAliveInterval),e.keepAliveInterval=null)}function L(){console.log("web socket connection opened"),n.trigger(this,"websocketopen")}function C(){x(this),n.trigger(this,"websocketerror")}function J(e,t){if(!t)return e.lastDetectedBitrate?e.lastDetectedBitrate:Promise.reject();var r=Math.min(Math.round(.7*t),2147483647);if(e.getMaxBandwidth){var n=e.getMaxBandwidth();n&&(r=Math.min(r,n))}return e.lastDetectedBitrate=r,e.lastDetectedBitrateTime=(new Date).getTime(),r}function R(e,t,r,n){if(r>=t.length)return J(e,n);var i=t[r];return e.getDownloadSpeed(i.bytes).then((function(n){return n<i.threshold?J(e,n):R(e,t,r+1,n)}),(function(){return J(e,n)}))}function D(e,t){return R(e,[{bytes:5e5,threshold:5e5},{bytes:1e6,threshold:2e7},{bytes:3e6,threshold:5e7}],0).then((function(r){return t.IsInNetwork&&(r=Math.max(r||0,14e7),e.lastDetectedBitrate=r,e.lastDetectedBitrateTime=(new Date).getTime()),r}))}function M(e,t){var r;return t.artist?(r="Artists/".concat(e.encodeName(t.artist)),delete t.artist):t.person?(r="Persons/".concat(e.encodeName(t.person)),delete t.person):t.genre?(r="Genres/".concat(e.encodeName(t.genre)),delete t.genre):t.musicGenre?(r="MusicGenres/".concat(e.encodeName(t.musicGenre)),delete t.musicGenre):t.studio?(r="Studios/".concat(e.encodeName(t.studio)),delete t.studio):(r="Items/".concat(t.itemId),delete t.itemId),r}function _(e,t){var r=window&&window.devicePixelRatio||1;r&&(t.minScale&&(r=Math.max(t.minScale,r)),t.width&&(t.width=Math.round(t.width*r)),t.height&&(t.height=Math.round(t.height*r)),t.maxWidth&&(t.maxWidth=Math.round(t.maxWidth*r)),t.maxHeight&&(t.maxHeight=Math.round(t.maxHeight*r)),t.fillWidth&&(t.fillWidth=Math.round(t.fillWidth*r)),t.fillHeight&&(t.fillHeight=Math.round(t.fillHeight*r))),t.quality=t.quality||e.getDefaultImageQuality(t.type),e.normalizeImageOptions&&e.normalizeImageOptions(t)}var F=U;function V(e){return V="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},V(e)}function G(e,t){return G=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},G(e,t)}function B(e){return B=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},B(e)}var q="local:",W="localview:";function H(e){return X(e,q)}function z(e){return X(e,W)}function Q(e){return"localview"===e}function K(e){var t=Y(e,q);return Y(t,W)}function X(e,t){return!!(e&&t&&e.length>t.length&&0===e.indexOf(t))}function Y(e,t){return X(e,t)?e.slice(t.length):e}function Z(e){return e?H(e)?e:"local:".concat(e):null}function $(e){e.Id=Z(e.Id),e.SeriesId=Z(e.SeriesId),e.SeasonId=Z(e.SeasonId),e.AlbumId=Z(e.AlbumId),e.ParentId=Z(e.ParentId),e.ParentThumbItemId=Z(e.ParentThumbItemId),e.ParentPrimaryImageItemId=Z(e.ParentPrimaryImageItemId),e.PrimaryImageItemId=Z(e.PrimaryImageItemId),e.ParentLogoItemId=Z(e.ParentLogoItemId),e.ParentBackdropItemId=Z(e.ParentBackdropItemId),e.ParentBackdropImageTags=null}function ee(e,t,r){return e.getLocalFolders(t,r).then((function(r){var n=null;return r.length>0&&(n={Name:e.downloadsTitleText||"Downloads",ServerId:t,Id:"localview",Type:"localview",IsFolder:!0}),Promise.resolve(n)}))}var te=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&G(e,t)}(a,e);var t,r,n,i,o=(n=a,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=B(n);if(i){var r=B(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===V(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function a(e,t,r,n,i,s,u){var l;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),(l=o.call(this,e,t,r,n,i,s)).localAssetManager=u,l}return t=a,(r=[{key:"getPlaybackInfo",value:function(e,t,r){var n=function(){return F.prototype.getPlaybackInfo.call(i,e,t,r)};if(H(e))return this.localAssetManager.getLocalItem(this.serverId(),K(e)).then((function(e){return{MediaSources:e.Item.MediaSources.map((function(e){return e.SupportsDirectPlay=!0,e.SupportsDirectStream=!1,e.SupportsTranscoding=!1,e.IsLocal=!0,e}))}}),n);var i=this;return this.localAssetManager.getLocalItem(this.serverId(),e).then((function(o){if(o){var a=o.Item.MediaSources.map((function(e){return e.SupportsDirectPlay=!0,e.SupportsDirectStream=!1,e.SupportsTranscoding=!1,e.IsLocal=!0,e}));return i.localAssetManager.fileExists(o.LocalPath).then((function(n){if(n){var o={MediaSources:a};return Promise.resolve(o)}return F.prototype.getPlaybackInfo.call(i,e,t,r)}),n)}return F.prototype.getPlaybackInfo.call(i,e,t,r)}),n)}},{key:"getItems",value:function(e,t){var r,n=this.serverInfo();if(n&&"localview"===t.ParentId)return this.getLocalFolders(n.Id,e).then((function(e){var t={Items:e,TotalRecordCount:e.length};return Promise.resolve(t)}));if(n&&t&&(H(t.ParentId)||H(t.SeriesId)||H(t.SeasonId)||z(t.ParentId)||H(t.AlbumIds)))return this.localAssetManager.getViewItems(n.Id,e,t).then((function(e){e.forEach((function(e){$(e)}));var t={Items:e,TotalRecordCount:e.length};return Promise.resolve(t)}));if(t&&t.ExcludeItemIds&&t.ExcludeItemIds.length){var i=t.ExcludeItemIds.split(",");for(r=0;r<i.length;r++)if(H(i[r]))return Promise.resolve({Items:[],TotalRecordCount:0})}else if(t&&t.Ids&&t.Ids.length){var o=t.Ids.split(","),a=!1;for(r=0;r<o.length;r++)H(o[r])&&(a=!0);if(a)return this.localAssetManager.getItemsFromIds(n.Id,o).then((function(e){e.forEach((function(e){$(e)}));var t={Items:e,TotalRecordCount:e.length};return Promise.resolve(t)}))}return F.prototype.getItems.call(this,e,t)}},{key:"getUserViews",value:function(e,t){var r=this;e=e||{};var n=F.prototype.getUserViews.call(r,e,t);return e.enableLocalView?n.then((function(e){var n=r.serverInfo();return n?ee(r,n.Id,t).then((function(t){return t&&(e.Items.push(t),e.TotalRecordCount++),Promise.resolve(e)})):Promise.resolve(e)})):n}},{key:"getItem",value:function(e,t){if(!t)throw new Error("null itemId");var r;return t&&(t=t.toString()),Q(t)&&(r=this.serverInfo())?ee(this,r.Id,e):z(t)&&(r=this.serverInfo())?this.getLocalFolders(r.Id,e).then((function(e){var r=e.filter((function(e){return e.Id===t}));return r.length>0?Promise.resolve(r[0]):Promise.reject()})):H(t)&&(r=this.serverInfo())?this.localAssetManager.getLocalItem(r.Id,K(t)).then((function(e){return $(e.Item),Promise.resolve(e.Item)})):F.prototype.getItem.call(this,e,t)}},{key:"getLocalFolders",value:function(e){var t=this.serverInfo();return e=e||t.UserId,this.localAssetManager.getViews(t.Id,e)}},{key:"getNextUpEpisodes",value:function(e){return e.SeriesId&&H(e.SeriesId)?Promise.resolve({Items:[],TotalRecordCount:0}):F.prototype.getNextUpEpisodes.call(this,e)}},{key:"getSeasons",value:function(e,t){return H(e)?(t.SeriesId=e,t.IncludeItemTypes="Season",this.getItems(this.getCurrentUserId(),t)):F.prototype.getSeasons.call(this,e,t)}},{key:"getEpisodes",value:function(e,t){return H(t.SeasonId)||H(t.seasonId)||H(e)?(t.SeriesId=e,t.IncludeItemTypes="Episode",this.getItems(this.getCurrentUserId(),t)):F.prototype.getEpisodes.call(this,e,t)}},{key:"getLatestOfflineItems",value:function(e){e.SortBy="DateCreated",e.SortOrder="Descending";var t=this.serverInfo();return t?this.localAssetManager.getViewItems(t.Id,null,e).then((function(e){return e.forEach((function(e){$(e)})),Promise.resolve(e)})):Promise.resolve([])}},{key:"getThemeMedia",value:function(e,t,r){return z(t)||H(t)||Q(t)?Promise.reject():F.prototype.getThemeMedia.call(this,e,t,r)}},{key:"getSpecialFeatures",value:function(e,t){return H(t)?Promise.resolve([]):F.prototype.getSpecialFeatures.call(this,e,t)}},{key:"getSimilarItems",value:function(e,t){return H(e)?Promise.resolve({Items:[],TotalRecordCount:0}):F.prototype.getSimilarItems.call(this,e,t)}},{key:"updateFavoriteStatus",value:function(e,t,r){return H(t)?Promise.resolve():F.prototype.updateFavoriteStatus.call(this,e,t,r)}},{key:"getScaledImageUrl",value:function(e,t){if(H(e)||t&&t.itemid&&H(t.itemid)){var r=this.serverInfo(),n=K(e);return this.localAssetManager.getImageUrl(r.Id,n,t)}return F.prototype.getScaledImageUrl.call(this,e,t)}},{key:"reportPlaybackStart",value:function(e){if(!e)throw new Error("null options");return H(e.ItemId)?Promise.resolve():F.prototype.reportPlaybackStart.call(this,e)}},{key:"reportPlaybackProgress",value:function(e){if(!e)throw new Error("null options");if(H(e.ItemId)){var t=this.serverInfo();if(t){var r=this;return this.localAssetManager.getLocalItem(t.Id,K(e.ItemId)).then((function(t){var n=t.Item;return"Video"===n.MediaType||"AudioBook"===n.Type?(n.UserData=n.UserData||{},n.UserData.PlaybackPositionTicks=e.PositionTicks,n.UserData.PlayedPercentage=Math.min(n.RunTimeTicks?(e.PositionTicks||0)/n.RunTimeTicks*100:0,100),r.localAssetManager.addOrUpdateLocalItem(t)):Promise.resolve()}))}return Promise.resolve()}return F.prototype.reportPlaybackProgress.call(this,e)}},{key:"reportPlaybackStopped",value:function(e){if(!e)throw new Error("null options");if(H(e.ItemId)){var t=this.serverInfo(),r={Date:(new Date).getTime(),ItemId:K(e.ItemId),PositionTicks:e.PositionTicks,ServerId:t.Id,Type:0,UserId:this.getCurrentUserId()};return this.localAssetManager.recordUserAction(r)}return F.prototype.reportPlaybackStopped.call(this,e)}},{key:"getIntros",value:function(e){return H(e)?Promise.resolve({Items:[],TotalRecordCount:0}):F.prototype.getIntros.call(this,e)}},{key:"getInstantMixFromItem",value:function(e,t){return H(e)?Promise.resolve({Items:[],TotalRecordCount:0}):F.prototype.getInstantMixFromItem.call(this,e,t)}},{key:"getItemDownloadUrl",value:function(e){if(H(e)){var t=this.serverInfo();if(t)return this.localAssetManager.getLocalItem(t.Id,K(e)).then((function(e){return Promise.resolve(e.LocalPath)}))}return F.prototype.getItemDownloadUrl.call(this,e)}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),a}(F);function re(e,t){switch(t){case 0:return e.LocalAddress;case 2:return e.ManualAddress;case 1:return e.RemoteAddress;default:return e.ManualAddress||e.LocalAddress||e.RemoteAddress}}function ne(e,t){t({State:"Unavailable"})}function ie(e,t){e.Name=t.ServerName,t.Id&&(e.Id=t.Id),t.LocalAddress&&(e.LocalAddress=t.LocalAddress)}function oe(e,t){return"".concat(e,"/").concat(t)}function ae(e){if(!e)throw new Error("Request cannot be null");return e.headers=e.headers||{},console.log("ConnectionManager requesting url: ".concat(e.url)),function(e){var t=e.headers||{};"json"===e.dataType&&(t.accept="application/json");var r,n,i,o={headers:t,method:e.type,credentials:"same-origin"},a=e.contentType;return e.data&&("string"==typeof e.data?o.body=e.data:(o.body=function(e){var t=[];for(var r in e){var n=e[r];null!=n&&""!==n&&t.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(n)))}return t.join("&")}(e.data),a=a||"application/x-www-form-urlencoded; charset=UTF-8")),a&&(t["Content-Type"]=a),e.timeout?(r=e.url,n=o,i=e.timeout,console.log("fetchWithTimeout: timeoutMs: ".concat(i,", url: ").concat(r)),new Promise((function(e,t){var o=setTimeout(t,i);(n=n||{}).credentials="same-origin",fetch(r,n).then((function(t){clearTimeout(o),console.log("fetchWithTimeout: succeeded connecting to url: ".concat(r)),e(t)}),(function(e){clearTimeout(o),console.log("fetchWithTimeout: timed out connecting to url: ".concat(r)),t()}))}))):fetch(e.url,o)}(e).then((function(t){return console.log("ConnectionManager response status: ".concat(t.status,", url: ").concat(e.url)),t.status<400?"json"===e.dataType||"application/json"===e.headers.accept?t.json():t:Promise.reject(t)}),(function(t){throw console.log("ConnectionManager request failed to url: ".concat(e.url)),t}))}function se(e,t,r){var n=new RegExp(t,"ig");return e.replace(n,r)}function ue(e){return e=se(e=e.trim(),"Http:","http:"),se(e,"Https:","https:")}function le(e,t){return(e||"").toLowerCase()===(t||"").toLowerCase()}var ce=function(){function e(t,r,i,o,a,s){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),console.log("Begin ConnectionManager constructor");var u=this;function l(e,r,n,i){var o=t.credentials(),a=o.Servers.filter((function(e){return e.Id===r.ServerId})),s=a.length?a[0]:e.serverInfo();return!1!==n.updateDateLastAccessed&&(s.DateLastAccessed=(new Date).getTime()),s.Id=r.ServerId,i?(s.UserId=r.User.Id,s.AccessToken=r.AccessToken):(s.UserId=null,s.AccessToken=null),t.addOrUpdateServer(o.Servers,s),t.credentials(o),e.enableAutomaticBitrateDetection=n.enableAutomaticBitrateDetection,e.serverInfo(s),e.setAuthenticationInfo(r.AccessToken,r.User.Id),c(e,n),h(s,e.serverAddress(),r.User)}function c(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!1!==t.reportCapabilities&&e.reportCapabilities(s),e.enableAutomaticBitrateDetection=t.enableAutomaticBitrateDetection,!1!==t.enableWebSocket&&(console.log("calling apiClient.ensureWebSocket"),e.ensureWebSocket())}function h(e,t,r){return u._getOrAddApiClient(e,t),(u.onLocalUserSignedIn?u.onLocalUserSignedIn.call(u,r):Promise.resolve()).then((function(){n.trigger(u,"localusersignedin",[r])}))}function d(e){var t={serverId:(e.serverInfo()||{}).Id};return e.logout().then((function(){n.trigger(u,"localusersignedout",[t])}),(function(){n.trigger(u,"localusersignedout",[t])}))}function f(e){if(e.Address&&e.EndpointAddress){var t=e.EndpointAddress.split(":")[0],r=e.Address.split(":");if(r.length>1){var n=r[r.length-1];isNaN(parseInt(n))||(t+=":".concat(n))}return ue(t)}return null}function v(e,r,i,o,a,s){var l=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{},d=t.credentials();if(!1===l.enableAutoLogin)e.UserId=null,e.AccessToken=null;else if(e.AccessToken&&a)return void function(e,t){return ae({type:"GET",url:oe(t,"System/Info"),dataType:"json",headers:{"X-MediaBrowser-Token":e.AccessToken}}).then((function(t){return ie(e,t),Promise.resolve()}),(function(){return e.UserId=null,e.AccessToken=null,Promise.resolve()}))}(e,o).then((function(){v(e,r,i,o,!1,s,l)}));ie(e,r),e.LastConnectionMode=i,!1!==l.updateDateLastAccessed&&(e.DateLastAccessed=(new Date).getTime()),t.addOrUpdateServer(d.Servers,e),t.credentials(d);var f={Servers:[]};f.ApiClient=u._getOrAddApiClient(e,o),f.ApiClient.setSystemInfo(r),f.SystemInfo=r,f.State=e.AccessToken&&!1!==l.enableAutoLogin?"SignedIn":"ServerSignIn",f.Servers.push(e),f.ApiClient.enableAutomaticBitrateDetection=l.enableAutomaticBitrateDetection,f.ApiClient.updateServerInfo(e,o),f.ApiClient.setAuthenticationInfo(e.AccessToken,e.UserId);var g=function(){s(f),n.trigger(u,"connected",[f])};"SignedIn"===f.State?(c(f.ApiClient,l),f.ApiClient.getCurrentUser().then((function(t){h(e,o,t).then(g,g)}),g)):g()}function g(e,t){var r={ManualAddress:e,LastConnectionMode:2};return u.connectToServer(r,t).then((function(e){return"Unavailable"===e.State?Promise.reject():e}))}this._apiClients=[],u._minServerVersion="3.2.33",u.appVersion=function(){return i},u.appName=function(){return r},u.capabilities=function(){return s},u.deviceId=function(){return a},u.credentialProvider=function(){return t},u.getServerInfo=function(e){return t.credentials().Servers.filter((function(t){return t.Id===e}))[0]},u.getLastUsedServer=function(){var e=t.credentials().Servers;return e.sort((function(e,t){return(t.DateLastAccessed||0)-(e.DateLastAccessed||0)})),e.length?e[0]:null},u.addApiClient=function(e){u._apiClients.push(e);var r=t.credentials().Servers.filter((function(t){return le(t.ManualAddress,e.serverAddress())||le(t.LocalAddress,e.serverAddress())||le(t.RemoteAddress,e.serverAddress())})),i=r.length?r[0]:e.serverInfo();if(i.DateLastAccessed=(new Date).getTime(),i.LastConnectionMode=2,i.ManualAddress=e.serverAddress(),e.manualAddressOnly&&(i.manualAddressOnly=!0),e.serverInfo(i),e.onAuthenticated=function(e,t){return l(e,t,{},!0)},!r.length){var o=t.credentials();o.Servers=[i],t.credentials(o)}n.trigger(u,"apiclientcreated",[e])},u.clearData=function(){console.log("connection manager clearing data");var e=t.credentials();e.Servers=[],t.credentials(e)},u._getOrAddApiClient=function(e,t){var s=u.getApiClient(e.Id);return s||(s=new F(t,r,i,o,a),u._apiClients.push(s),s.serverInfo(e),s.onAuthenticated=function(e,t){return l(e,t,{},!0)},n.trigger(u,"apiclientcreated",[s])),console.log("returning instance from getOrAddApiClient"),s},u.getOrCreateApiClient=function(e){var r=t.credentials().Servers.filter((function(t){return le(t.Id,e)}));if(!r.length)throw new Error("Server not found: ".concat(e));var n=r[0];return u._getOrAddApiClient(n,re(n,n.LastConnectionMode))},u.user=function(e){return new Promise((function(t,r){var n;e&&e.getCurrentUserId()&&e&&e.getCurrentUserId()&&e.getCurrentUser().then((function(e){var r=function(e){return e&&e.PrimaryImageTag?{url:u.getApiClient(e).getUserImageUrl(e.Id,{tag:e.PrimaryImageTag,type:"Primary"}),supportsParams:!0}:{url:null,supportsParams:!1}}(n=e);t({localUser:n,name:n?n.Name:null,imageUrl:r.url,supportsImageParams:r.supportsParams})}))}))},u.logout=function(){for(var e=[],r=0,n=u._apiClients.length;r<n;r++){var i=u._apiClients[r];i.accessToken()&&e.push(d(i))}return Promise.all(e).then((function(){for(var e=t.credentials().Servers.filter((function(e){return"Guest"!==e.UserLinkType})),r=0,n=e.length;r<n;r++){var i=e[r];i.UserId=null,i.AccessToken=null,i.ExchangeToken=null}}))},u.getSavedServers=function(){var e=t.credentials().Servers.slice(0);return e.sort((function(e,t){return(t.DateLastAccessed||0)-(e.DateLastAccessed||0)})),e},u.getAvailableServers=function(){console.log("Begin getAvailableServers");var e=t.credentials();return Promise.all([new Promise((function(e,t){var r=function(t){var r=t.map((function(e){var t={Id:e.Id,LocalAddress:f(e)||e.Address,Name:e.Name};return t.LastConnectionMode=t.ManualAddress?2:0,t}));e(r)};window&&window.NativeShell&&"function"==typeof window.NativeShell.findServers?window.NativeShell.findServers(1e3).then(r,(function(){r([])})):e([])}))]).then((function(r){var n=r[0],i=e.Servers.slice(0);return function(e,t,r){for(var n=0,i=r.length;n<i;n++)e.addOrUpdateServer(t,r[n])}(t,i,n),i.sort((function(e,t){return(t.DateLastAccessed||0)-(e.DateLastAccessed||0)})),e.Servers=i,t.credentials(e),i}))},u.connectToServers=function(e,t){console.log("Begin connectToServers, with ".concat(e.length," servers"));var r=e.length?e[0]:null;return r?u.connectToServer(r,t).then((function(e){return"Unavailable"===e.State&&(e.State="ServerSelection"),console.log("resolving connectToServers with result.State: "+e.State),e})):Promise.resolve({Servers:e,State:"ServerSelection"})},u.connectToServer=function(e,t){return console.log("begin connectToServer"),new Promise((function(r,n){var i,o,a;t=t||{},(i=e,o=[],a=[],!i.manualAddressOnly&&i.LocalAddress&&-1===a.indexOf(i.LocalAddress)&&(o.push({url:i.LocalAddress,mode:0,timeout:0}),a.push(o[o.length-1].url)),i.ManualAddress&&-1===a.indexOf(i.ManualAddress)&&(o.push({url:i.ManualAddress,mode:2,timeout:100}),a.push(o[o.length-1].url)),!i.manualAddressOnly&&i.RemoteAddress&&-1===a.indexOf(i.RemoteAddress)&&(o.push({url:i.RemoteAddress,mode:1,timeout:200}),a.push(o[o.length-1].url)),console.log("tryReconnect: "+a.join("|")),new Promise((function(e,t){var r={};r.numAddresses=o.length,r.rejects=0,o.map((function(n){setTimeout((function(){r.resolved||function(e,t,r,n,i){console.log("getTryConnectPromise "+e),ae({url:oe(e,"system/info/public"),timeout:2e4,type:"GET",dataType:"json"}).then((function(i){r.resolved||(r.resolved=!0,console.log("Reconnect succeeded to "+e),n({url:e,connectionMode:t,data:i}))}),(function(){console.log("Reconnect failed to "+e),r.resolved||(r.rejects++,r.rejects>=r.numAddresses&&i())}))}(n.url,n.mode,r,e,t)}),n.timeout)}))}))).then((function(n){var i=n.url,o=n.connectionMode;n=n.data,1===function(e,t){e=e.split("."),t=t.split(".");for(var r=0,n=Math.max(e.length,t.length);r<n;r++){var i=parseInt(e[r]||"0"),o=parseInt(t[r]||"0");if(i<o)return-1;if(i>o)return 1}return 0}(u.minServerVersion(),n.Version)?(console.log("minServerVersion requirement not met. Server version: "+n.Version),r({State:"ServerUpdateNeeded",Servers:[e]})):e.Id&&n.Id!==e.Id?(console.log("http request succeeded, but found a different server Id than what was expected"),ne(0,r)):v(e,n,o,i,!0,r,t)}),(function(){ne(0,r)}))}))},u.connectToAddress=function(e,t){if(!e)return Promise.reject();e=ue(e);var r=[];/^[^:]+:\/\//.test(e)?r.push(e):(r.push("https://".concat(e)),r.push("http://".concat(e)));var n=0;return g(r[n],t).catch((function e(){return console.log("connectToAddress ".concat(r[n]," failed")),++n<r.length?g(r[n],t).catch(e):Promise.resolve({State:"Unavailable"})}))},u.deleteServer=function(e){if(!e)throw new Error("null serverId");var r=t.credentials().Servers.filter((function(t){return t.Id===e}));return r=r.length?r[0]:null,new Promise((function(n,i){if(!r.ConnectServerId)return(o=t.credentials()).Servers=o.Servers.filter((function(t){return t.Id!==e})),t.credentials(o),void n();var o}))}}var t,r;return t=e,(r=[{key:"connect",value:function(e){var t=this;return console.log("Begin connect"),this.getAvailableServers().then((function(r){return t.connectToServers(r,e)}))}},{key:"handleMessageReceived",value:function(e){var t=e.ServerId;if(t){var r=this.getApiClient(t);if(r){if("string"==typeof e.Data)try{e.Data=JSON.parse(e.Data)}catch(e){console.log("unable to parse json content: "+e)}r.handleMessageReceived(e)}}}},{key:"getApiClients",value:function(){for(var e=this.getSavedServers(),t=0,r=e.length;t<r;t++){var n=e[t];n.Id&&this._getOrAddApiClient(n,re(n,n.LastConnectionMode))}return this._apiClients}},{key:"getApiClient",value:function(e){if(!e)throw new Error("item or serverId cannot be null");return e.ServerId&&(e=e.ServerId),this._apiClients.filter((function(t){var r=t.serverInfo();return!r||r.Id===e}))[0]}},{key:"minServerVersion",value:function(e){return e&&(this._minServerVersion=e),this._minServerVersion}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();var he=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.key=t||"jellyfin_credentials",this.appStorage=u,this._credentials=function(e,t){var r=e.getItem(t)||"{}";console.log("Stored JSON credentials: ".concat(r));var n=JSON.parse(r);return n.Servers=n.Servers||[],n}(this.appStorage,this.key)}var t,r;return t=e,(r=[{key:"clear",value:function(){this._credentials=null,this.appStorage.removeItem(this.key)}},{key:"credentials",value:function(e){return e&&function(e,t){t?(e._credentials=t,e.appStorage.setItem(e.key,JSON.stringify(t))):e.clear(),n.trigger(e,"credentialsupdated")}(this,e),this._credentials}},{key:"addOrUpdateServer",value:function(e,t){if(!t.Id)throw new Error("Server.Id cannot be null or empty");var r=e.filter((function(e){return e.Id===t.Id}))[0];return r?(r.DateLastAccessed=Math.max(r.DateLastAccessed||0,t.DateLastAccessed||0),r.UserLinkType=t.UserLinkType,t.AccessToken&&(r.AccessToken=t.AccessToken,r.UserId=t.UserId),t.ExchangeToken&&(r.ExchangeToken=t.ExchangeToken),t.RemoteAddress&&(r.RemoteAddress=t.RemoteAddress),t.ManualAddress&&(r.ManualAddress=t.ManualAddress),t.LocalAddress&&(r.LocalAddress=t.LocalAddress),t.Name&&(r.Name=t.Name),null!=t.LastConnectionMode&&(r.LastConnectionMode=t.LastConnectionMode),t.ConnectServerId&&(r.ConnectServerId=t.ConnectServerId),r):(e.push(t),t)}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}(),de={ApiClient:F,ApiClientCore:te,AppStorage:u,ConnectionManager:ce,Credentials:he,Events:n};return t.default}()}}]);