discord-jellyfin-bot/patches/jellyfin-apiclient+1.4.1.patch

13 lines
72 KiB
Diff

diff --git a/node_modules/jellyfin-apiclient/dist/jellyfin-apiclient.js b/node_modules/jellyfin-apiclient/dist/jellyfin-apiclient.js
index c2382cd..ae51ce1 100644
--- a/node_modules/jellyfin-apiclient/dist/jellyfin-apiclient.js
+++ b/node_modules/jellyfin-apiclient/dist/jellyfin-apiclient.js
@@ -1,2 +1,6 @@
+const fetch = require('node-fetch')
+const window = require('window')
+const WebSocket = require('ws');
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["jellyfin-apiclient"]=t():e["jellyfin-apiclient"]=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";function n(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}r.r(t);var i={on:function(e,t,r){n(e,t).push(r)},off:function(e,t,r){var i=n(e,t),o=i.indexOf(r);-1!==o&&i.splice(o,1)},trigger:function(e,t){var r={type:t},i=[];i.push(r);for(var o=arguments[2]||[],a=0,s=o.length;a<s;a++)i.push(o[a]);var u=n(e,t).slice(0);u.forEach((function(t){t.apply(e,i)}))}};function o(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 a(e){console.log(e)}function s(e){var t=e.cache;t&&t.put("data",new Response(JSON.stringify(e.localData))).catch(a)}function u(e){this.cache=e,this.localData={}}var l=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);try{self.caches&&caches.open("embydata").then(u.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,s(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],s(this))}}])&&o(t.prototype,r),n&&o(t,n),e}().getInstance();function c(e){return(c="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})(e)}function d(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)}}var h={timeupdate:1e4,volumechange:3e3};function v(e){g(e),e.accessToken()&&!1!==e.enableAutomaticBitrateDetection&&setTimeout(f.bind(e),6e3)}function f(){this.accessToken()&&this.detectBitrate()}function g(e){e.detectTimeout&&clearTimeout(e.detectTimeout)}function p(e,t,r){var n=new RegExp(t,"ig");return e.replace(n,r)}function y(e,t,r){i.trigger(e,"requestfail",[{url:t,status:r.status,errorCode:r.headers?r.headers.get("X-Application-Error-Code"):null}])}function m(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 I(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 S(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=m(e.data),n=n||"application/x-www-form-urlencoded; charset=UTF-8")),n&&(t["Content-Type"]=n),e.timeout?I(e.url,r,e.timeout):fetch(e.url,r)}function w(e){"function"==typeof e.reportPlaybackProgressCancel&&e.reportPlaybackProgressCancel()}function k(e,t){e._endPointInfo=t}function T(e,t){var r=e.serverId();if(!r)return null;var n=l.getItem("user-".concat(t,"-").concat(r));return n?JSON.parse(n):null}function P(e){b(this,e=JSON.parse(e.data))}var U={};function b(e,t){var r=t.MessageId;if(r){if(U[r])return;U[r]=!0}if("UserDeleted"===t.MessageType)e._currentUser=null;else if("UserUpdated"===t.MessageType||"UserConfigurationUpdated"===t.MessageType){t.Data.Id===e.getCurrentUserId()&&(e._currentUser=null)}else"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"),function(e,t){O(e),e.keepAliveInterval=setInterval((function(){e.sendWebSocketMessage("KeepAlive")}),1e3*t*.5),e.keepAliveInterval}(e,t.Data));i.trigger(e,"message",[t])}function O(e){console.debug("Clearing KeepAlive for",e),e.keepAliveInterval&&(clearInterval(e.keepAliveInterval),e.keepAliveInterval=null)}function E(){console.log("web socket connection opened"),i.trigger(this,"websocketopen")}function A(){O(this),i.trigger(this,"websocketerror")}function j(e,t){if(!t)return e.lastDetectedBitrate?e.lastDetectedBitrate:Promise.reject();var r=Math.round(.7*t);if(e.getMaxBandwidth){var n=e.getMaxBandwidth();n&&(r=Math.min(r,n))}return e.lastDetectedBitrate=r,e.lastDetectedBitrateTime=(new Date).getTime(),r}function N(e,t){if(t.IsInNetwork){return e.lastDetectedBitrate=14e7,e.lastDetectedBitrateTime=(new Date).getTime(),14e7}return function e(t,r,n,i){if(n>=r.length)return j(t,i);var o=r[n];return t.getDownloadSpeed(o.bytes).then((function(i){return i<o.threshold?j(t,i):e(t,r,n+1,i)}),(function(){return j(t,i)}))}(e,[{bytes:5e5,threshold:5e5},{bytes:1e6,threshold:2e7},{bytes:3e6,threshold:5e7}],0)}function L(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 x(e,t){var r=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.quality=t.quality||e.getDefaultImageQuality(t.type),e.normalizeImageOptions&&e.normalizeImageOptions(t)}var C=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}var t,r,n;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=[];if(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){var o="MediaBrowser ".concat(i.join(", "));e["X-Emby-Authorization"]=o}}},{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&&i.trigger(this,"serveraddresschanged")}return this._serverAddress}},{key:"onNetworkChange",value:function(){this.lastDetectedBitrate=0,this.lastDetectedBitrateTime=0,k(this,null),v(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=m(t))&&(n+="?".concat(t)),n}},{key:"fetchWithFailover",value:function(e,t){console.log("Requesting ".concat(e.url)),e.timeout=3e4;var r=this;return S(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:(y(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"),y(r,e.url,{}),n;console.log("Attempting reconnection");var i=r.serverAddress();return function e(t,r){return(r=r||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),I(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)}))}))}(t).catch((function(n){return console.log("error in tryReconnectInternal: "+(n||"")),new Promise((function(n,i){setTimeout((function(){e(t,r+1).then(n,i)}),500)}))}))}(r).then((function(){return console.log("Reconnect succeesed"),e.url=e.url.replace(i,r.serverAddress()),r.fetchWithFailover(e,!1)})).catch((function(t){throw console.log("Reconnect failed"),y(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 S(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:(y(r,e.url,t),Promise.reject(t))})).catch((function(t){return y(r,e.url,{}),Promise.reject(t)}))}return this.fetchWithFailover(e,!0)}},{key:"setAuthenticationInfo",value:function(e,t){this._currentUser=null,this._serverInfo.AccessToken=e,this._serverInfo.UserId=t,v(this)}},{key:"serverInfo",value:function(e){return e&&(this._serverInfo=e),this._serverInfo}},{key:"getCurrentUserId",value:function(){return this._serverInfo.UserId}},{key:"accessToken",value:function(){return this._serverInfo.AccessToken}},{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 l.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=T(n,t)))return Promise.resolve(r);throw e}));return!this.lastFetch&&!1!==e&&(r=T(n,t))?Promise.resolve(r):i}},{key:"isLoggedIn",value:function(){var e=this.serverInfo();return!!(e&&e.UserId&&e.AccessToken)}},{key:"logout",value:function(){var e=this;g(this),this.closeWebSocket();var t=function(){var t=e.serverInfo();t&&t.UserId&&t.Id&&l.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(){v(r),i(e)};r.onAuthenticated?r.onAuthenticated(r,e).then(t):t()})).catch(o)}))}},{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=p(t,"emby/socket","embywebsocket"),t=p(t,"https:","wss:"),t=p(t,"http:","ws:"),t+="?api_key=".concat(e),t+="&deviceId=".concat(this.deviceId()),console.log("opening web socket with url: ".concat(t));var r,n,o=new WebSocket(t);o.onmessage=P.bind(this),o.onopen=E.bind(this),o.onerror=A.bind(this),r=this,(n=o).onclose=function(){console.log("web socket closed"),O(n),r._webSocket===n&&(console.log("nulling out web socket"),r._webSocket=null),setTimeout((function(){i.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=m({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.getUrl("Playback/BitrateTest",{Size:e}),r=(new Date).getTime();return this.ajax({type:"GET",url:t,timeout:5e3}).then((function(){var t=((new Date).getTime()-r)/1e3,n=e/t;return Math.round(8*n)}))}},{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 N(t,e)}),(function(e){return N(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=L(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=L(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=L(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:"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:"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:"image/".concat(r.name.substring(r.name.lastIndexOf(".")+1))}).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:"image/".concat(r.name.substring(r.name.lastIndexOf(".")+1))}).then(e,t)},o.readAsDataURL(r)}))}},{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)),x(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)),x(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:{NewPw:t}})}Promise.reject()}},{key:"resetUserPassword",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Users/".concat(e,"/Password")),r={resetPassword:!0};return this.ajax({type:"POST",url:t,data:r})}},{key:"resetEasyPassword",value:function(e){if(!e)throw new Error("null userId");var t=this.getUrl("Users/".concat(e,"/EasyPassword")),r={resetPassword:!0};return this.ajax({type:"POST",url:t,data:r})}},{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"===c(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){function t(e){return e<10?"0".concat(e):e}var r=e;return"".concat(r.getFullYear()).concat(t(r.getMonth()+1)).concat(t(r.getDate())).concat(t(r.getHours())).concat(t(r.getMinutes())).concat(t(r.getSeconds()))}},{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:function(e){if(!e)throw new Error("null options");this.lastPlaybackProgressReport=0,this.lastPlaybackProgressReportTicks=null,g(this),w(this);var t=this.getUrl("Sessions/Playing");return this.ajax({type:"POST",data:JSON.stringify(e),contentType:"application/json",url:t})}},{key:"reportPlaybackProgress",value:function(e){if(!e)throw new Error("null options");var t=e.EventName||"timeupdate",r=h[t]||0,n=(new Date).getTime()-(this.lastPlaybackProgressReport||0),i=e.PositionTicks;if(n<r&&"timeupdate"===t&&i){var o=1e4*n+(this.lastPlaybackProgressReportTicks||0);Math.abs(i-o)>=5e7&&(r=0)}if(r<(void 0!==this.reportPlaybackProgressTimeout?this.reportPlaybackProgressTimeout:1e6)&&w(this),this.lastPlaybackProgressOptions=e,this.reportPlaybackProgressPromise)return Promise.resolve();var a,s=this,u=!1,l=function(){s.reportPlaybackProgressPromise===a&&(delete s.lastPlaybackProgressOptions,delete s.reportPlaybackProgressTimeout,delete s.reportPlaybackProgressPromise,delete s.reportPlaybackProgressCancel)},c=Math.max(0,r-n);return a=new Promise((function(e,t){return setTimeout(e,c)})).then((function(){return u?Promise.resolve():function(e){if(l(),!e)throw new Error("null options");s.lastPlaybackProgressReport=(new Date).getTime(),s.lastPlaybackProgressReportTicks=e.PositionTicks;var t=s.getUrl("Sessions/Playing/Progress");return s.ajax({type:"POST",data:JSON.stringify(e),contentType:"application/json",url:t})}(s.lastPlaybackProgressOptions)})).finally((function(){l()})),this.reportPlaybackProgressTimeout=r,this.reportPlaybackProgressPromise=a,this.reportPlaybackProgressCancel=function(){u=!0,l()},a}},{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:function(e){if(!e)throw new Error("null options");this.lastPlaybackProgressReport=0,this.lastPlaybackProgressReportTicks=null,v(this),w(this);var t=this.getUrl("Sessions/Playing/Stopped");return this.ajax({type:"POST",data:JSON.stringify(e),contentType:"application/json",url:t})}},{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=this.getUrl("SyncPlay/New");return this.ajax({type:"POST",url:e})}},{key:"joinSyncPlayGroup",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=this.getUrl("SyncPlay/Join",e);return this.ajax({type:"POST",url:t})}},{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",e);return this.ajax({type:"POST",url:t})}},{key:"requestSyncPlayStart",value:function(){var e=this.getUrl("SyncPlay/Play");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",e);return this.ajax({type:"POST",url:t})}},{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 k(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){b(this,e)}}])&&d(t.prototype,r),n&&d(t,n),e}();function J(e){return(J="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})(e)}function R(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 D(e,t){return(D=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function M(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=F(e);if(t){var i=F(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return _(this,r)}}function _(e,t){return!t||"object"!==J(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function F(e){return(F=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function V(e){return q(e,"local:")}function G(e){return q(e,"localview:")}function B(e){return"localview"===e}function W(e){var t=H(e,"local:");return t=H(t,"localview:")}function q(e,t){return!!(e&&t&&e.length>t.length&&0===e.indexOf(t))}function H(e,t){return q(e,t)?e.substr(t.length):e}function z(e){return e?V(e)?e:"local:".concat(e):null}function K(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 Q(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 X=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}}),t&&D(e,t)}(o,e);var t,r,n,i=M(o);function o(e,t,r,n,a,s,u){var l;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,o),(l=i.call(this,e,t,r,n,a,s)).localAssetManager=u,l}return t=o,(r=[{key:"getPlaybackInfo",value:function(e,t,r){var n=function(){return C.prototype.getPlaybackInfo.call(i,e,t,r)};if(V(e))return this.localAssetManager.getLocalItem(this.serverId(),W(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 C.prototype.getPlaybackInfo.call(i,e,t,r)}),n)}return C.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&&(V(t.ParentId)||V(t.SeriesId)||V(t.SeasonId)||G(t.ParentId)||V(t.AlbumIds)))return this.localAssetManager.getViewItems(n.Id,e,t).then((function(e){e.forEach((function(e){K(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(V(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++)V(o[r])&&(a=!0);if(a)return this.localAssetManager.getItemsFromIds(n.Id,o).then((function(e){e.forEach((function(e){K(e)}));var t={Items:e,TotalRecordCount:e.length};return Promise.resolve(t)}))}return C.prototype.getItems.call(this,e,t)}},{key:"getUserViews",value:function(e,t){var r=this;e=e||{};var n=C.prototype.getUserViews.call(r,e,t);return e.enableLocalView?n.then((function(e){var n=r.serverInfo();return n?Q(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()),B(t)&&(r=this.serverInfo())?Q(this,r.Id,e):G(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()})):V(t)&&(r=this.serverInfo())?this.localAssetManager.getLocalItem(r.Id,W(t)).then((function(e){return K(e.Item),Promise.resolve(e.Item)})):C.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&&V(e.SeriesId)?Promise.resolve({Items:[],TotalRecordCount:0}):C.prototype.getNextUpEpisodes.call(this,e)}},{key:"getSeasons",value:function(e,t){return V(e)?(t.SeriesId=e,t.IncludeItemTypes="Season",this.getItems(this.getCurrentUserId(),t)):C.prototype.getSeasons.call(this,e,t)}},{key:"getEpisodes",value:function(e,t){return V(t.SeasonId)||V(t.seasonId)||V(e)?(t.SeriesId=e,t.IncludeItemTypes="Episode",this.getItems(this.getCurrentUserId(),t)):C.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){K(e)})),Promise.resolve(e)})):Promise.resolve([])}},{key:"getThemeMedia",value:function(e,t,r){return G(t)||V(t)||B(t)?Promise.reject():C.prototype.getThemeMedia.call(this,e,t,r)}},{key:"getSpecialFeatures",value:function(e,t){return V(t)?Promise.resolve([]):C.prototype.getSpecialFeatures.call(this,e,t)}},{key:"getSimilarItems",value:function(e,t){return V(e)?Promise.resolve({Items:[],TotalRecordCount:0}):C.prototype.getSimilarItems.call(this,e,t)}},{key:"updateFavoriteStatus",value:function(e,t,r){return V(t)?Promise.resolve():C.prototype.updateFavoriteStatus.call(this,e,t,r)}},{key:"getScaledImageUrl",value:function(e,t){if(V(e)||t&&t.itemid&&V(t.itemid)){var r=this.serverInfo(),n=W(e);return this.localAssetManager.getImageUrl(r.Id,n,t)}return C.prototype.getScaledImageUrl.call(this,e,t)}},{key:"reportPlaybackStart",value:function(e){if(!e)throw new Error("null options");return V(e.ItemId)?Promise.resolve():C.prototype.reportPlaybackStart.call(this,e)}},{key:"reportPlaybackProgress",value:function(e){if(!e)throw new Error("null options");if(V(e.ItemId)){var t=this.serverInfo();if(t){var r=this;return this.localAssetManager.getLocalItem(t.Id,W(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 C.prototype.reportPlaybackProgress.call(this,e)}},{key:"reportPlaybackStopped",value:function(e){if(!e)throw new Error("null options");if(V(e.ItemId)){var t=this.serverInfo(),r={Date:(new Date).getTime(),ItemId:W(e.ItemId),PositionTicks:e.PositionTicks,ServerId:t.Id,Type:0,UserId:this.getCurrentUserId()};return this.localAssetManager.recordUserAction(r)}return C.prototype.reportPlaybackStopped.call(this,e)}},{key:"getIntros",value:function(e){return V(e)?Promise.resolve({Items:[],TotalRecordCount:0}):C.prototype.getIntros.call(this,e)}},{key:"getInstantMixFromItem",value:function(e,t){return V(e)?Promise.resolve({Items:[],TotalRecordCount:0}):C.prototype.getInstantMixFromItem.call(this,e,t)}},{key:"getItemDownloadUrl",value:function(e){if(V(e)){var t=this.serverInfo();if(t)return this.localAssetManager.getLocalItem(t.Id,W(e)).then((function(e){return Promise.resolve(e.LocalPath)}))}return C.prototype.getItemDownloadUrl.call(this,e)}}])&&R(t.prototype,r),n&&R(t,n),o}(C);function Y(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)}}var Z=0,$=1,ee=2;function te(e,t){switch(t){case Z:return e.LocalAddress;case ee:return e.ManualAddress;case $:return e.RemoteAddress;default:return e.ManualAddress||e.LocalAddress||e.RemoteAddress}}function re(e,t){t({State:"Unavailable"})}function ne(e,t){e.Name=t.ServerName,t.Id&&(e.Id=t.Id),t.LocalAddress&&(e.LocalAddress=t.LocalAddress)}function ie(e,t){return"".concat(e,"/").concat(t)}function oe(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)}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)),oe(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:"),e=se(e,"Https:","https:")}function le(e,t){return(e||"").toLowerCase()===(t||"").toLowerCase()}var ce=function(){function e(t,r,n,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),c(e,n),d(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 d(e,t,r){return u._getOrAddApiClient(e,t),(u.onLocalUserSignedIn?u.onLocalUserSignedIn.call(u,r):Promise.resolve()).then((function(){i.trigger(u,"localusersignedin",[r])}))}function h(e,t){return ae({type:"GET",url:ie(t,"System/Info"),dataType:"json",headers:{"X-MediaBrowser-Token":e.AccessToken}}).then((function(t){return ne(e,t),Promise.resolve()}),(function(){return e.UserId=null,e.AccessToken=null,Promise.resolve()}))}function v(e){var t={serverId:(e.serverInfo()||{}).Id};return e.logout().then((function(){i.trigger(u,"localusersignedout",[t])}),(function(){i.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 g(e){var t=[],r=[];return!e.manualAddressOnly&&e.LocalAddress&&-1===r.indexOf(e.LocalAddress)&&(t.push({url:e.LocalAddress,mode:Z,timeout:0}),r.push(t[t.length-1].url)),e.ManualAddress&&-1===r.indexOf(e.ManualAddress)&&(t.push({url:e.ManualAddress,mode:ee,timeout:100}),r.push(t[t.length-1].url)),!e.manualAddressOnly&&e.RemoteAddress&&-1===r.indexOf(e.RemoteAddress)&&(t.push({url:e.RemoteAddress,mode:$,timeout:200}),r.push(t[t.length-1].url)),console.log("tryReconnect: "+r.join("|")),new Promise((function(e,r){var n={};n.numAddresses=t.length,n.rejects=0,t.map((function(t){setTimeout((function(){n.resolved||function(e,t,r,n,i){console.log("getTryConnectPromise "+e),ae({url:ie(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())}))}(t.url,t.mode,n,e,r)}),t.timeout)}))}))}function p(e,t){var r={ManualAddress:e,LastConnectionMode:ee};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 n},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())})),n=r.length?r[0]:e.serverInfo();if(n.DateLastAccessed=(new Date).getTime(),n.LastConnectionMode=ee,n.ManualAddress=e.serverAddress(),e.manualAddressOnly&&(n.manualAddressOnly=!0),e.serverInfo(n),e.onAuthenticated=function(e,t){return l(e,t,{},!0)},!r.length){var o=t.credentials();o.Servers=[n],t.credentials(o)}i.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 C(t,r,n,o,a),u._apiClients.push(s),s.serverInfo(e),s.onAuthenticated=function(e,t){return l(e,t,{},!0)},i.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,te(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(v(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?ee:Z,t}));e(r)};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,r){return console.log("begin connectToServer"),new Promise((function(n,o){r=r||{},g(e).then((function(o){var a=o.url,s=o.connectionMode;o=o.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(),o.Version)?(console.log("minServerVersion requirement not met. Server version: "+o.Version),n({State:"ServerUpdateNeeded",Servers:[e]})):e.Id&&o.Id!==e.Id?(console.log("http request succeeded, but found a different server Id than what was expected"),re(0,n)):function e(r,n,o,a,s,l){var v=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{},f=t.credentials();if(!1===v.enableAutoLogin)r.UserId=null,r.AccessToken=null;else if(r.AccessToken&&s)return void h(r,a).then((function(){e(r,n,o,a,!1,l,v)}));ne(r,n),r.LastConnectionMode=o,!1!==v.updateDateLastAccessed&&(r.DateLastAccessed=(new Date).getTime());t.addOrUpdateServer(f.Servers,r),t.credentials(f);var g={Servers:[]};g.ApiClient=u._getOrAddApiClient(r,a),g.ApiClient.setSystemInfo(n),g.State=r.AccessToken&&!1!==v.enableAutoLogin?"SignedIn":"ServerSignIn",g.Servers.push(r),g.ApiClient.enableAutomaticBitrateDetection=v.enableAutomaticBitrateDetection,g.ApiClient.updateServerInfo(r,a);var p=function(){l(g),i.trigger(u,"connected",[g])};"SignedIn"===g.State?(c(g.ApiClient,v),g.ApiClient.getCurrentUser().then((function(e){d(r,a,e).then(p,p)}),p)):p()}(e,o,s,a,!0,n,r)}),(function(){re(0,n)}))}))},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 p(r[n],t).catch((function e(){return console.log("connectToAddress ".concat(r[n]," failed")),++n<r.length?p(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,n;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,te(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}}])&&Y(t.prototype,r),n&&Y(t,n),e}();function de(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)}}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=l}var t,r,n;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(),i.trigger(e,"credentialsupdated")}(this,e),function(e,t){if(!e._credentials){var r=e.appStorage.getItem(e.key)||"{}";console.log("credentials initialized with: ".concat(r)),e._credentials=JSON.parse(r),e._credentials.Servers=e._credentials.Servers||[]}}(this),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)}}])&&de(t.prototype,r),n&&de(t,n),e}();t.default={ApiClient:C,ApiClientCore:X,AppStorage:l,ConnectionManager:ce,Credentials:he,Events:i}}]).default}));
//# sourceMappingURL=jellyfin-apiclient.js.map
\ No newline at end of file