diff --git a/dashboard-ui/bower_components/emby-apiclient/connectionmanager.js b/dashboard-ui/bower_components/emby-apiclient/connectionmanager.js index 0982f44989..ae7484b0b1 100644 --- a/dashboard-ui/bower_components/emby-apiclient/connectionmanager.js +++ b/dashboard-ui/bower_components/emby-apiclient/connectionmanager.js @@ -1 +1 @@ -define(["events","apiclient","appStorage"],function(events,apiClientFactory,appStorage){"use strict";function paramsToString(params){var values=[];for(var key in params){var value=params[key];null!==value&&void 0!==value&&""!==value&&values.push(encodeURIComponent(key)+"="+encodeURIComponent(value))}return values.join("&")}function resolveFailure(instance,resolve){resolve({State:ConnectionState.Unavailable,ConnectUser:instance.connectUser()})}function mergeServers(credentialProvider,list1,list2){for(var i=0,length=list2.length;ibVal)return 1}return 0}var defaultTimeout=2e4,ConnectionState={Unavailable:0,ServerSelection:1,ServerSignIn:2,SignedIn:3,ConnectSignIn:4,ServerUpdateNeeded:5},ConnectionMode={Local:0,Remote:1,Manual:2},ServerInfo={getServerAddress:function(server,mode){switch(mode){case ConnectionMode.Local:return server.LocalAddress;case ConnectionMode.Manual:return server.ManualAddress;case ConnectionMode.Remote:return server.RemoteAddress;default:return server.ManualAddress||server.LocalAddress||server.RemoteAddress}}},ConnectionManager=function(credentialProvider,appName,appVersion,deviceName,deviceId,capabilities,devicePixelRatio){function onConnectUserSignIn(user){appStorage.removeItem("lastLocalServerId"),connectUser=user,events.trigger(self,"connectusersignedin",[user])}function onAuthenticated(apiClient,result,options,saveCredentials){var credentials=credentialProvider.credentials(),servers=credentials.Servers.filter(function(s){return s.Id===result.ServerId}),server=servers.length?servers[0]:apiClient.serverInfo();return options.updateDateLastAccessed!==!1&&(server.DateLastAccessed=(new Date).getTime()),server.Id=result.ServerId,saveCredentials?(server.UserId=result.User.Id,server.AccessToken=result.AccessToken):(server.UserId=null,server.AccessToken=null),credentialProvider.addOrUpdateServer(credentials.Servers,server),credentialProvider.credentials(credentials),apiClient.serverInfo(server),afterConnected(apiClient,options),onLocalUserSignIn(server,server.LastConnectionMode,result.User)}function afterConnected(apiClient,options){options=options||{},options.reportCapabilities!==!1&&apiClient.reportCapabilities(capabilities),apiClient.enableAutomaticBitrateDetection=options.enableAutomaticBitrateDetection,options.enableWebSocket!==!1&&(console.log("calling apiClient.ensureWebSocket"),apiClient.ensureWebSocket())}function onLocalUserSignIn(server,connectionMode,user){self.connectUserId()?appStorage.removeItem("lastLocalServerId"):appStorage.setItem("lastLocalServerId",server.Id),self._getOrAddApiClient(server,connectionMode);var promise=self.onLocalUserSignedIn?self.onLocalUserSignedIn.call(self,user):Promise.resolve();return promise.then(function(){events.trigger(self,"localusersignedin",[user])})}function ensureConnectUser(credentials){return connectUser&&connectUser.Id===credentials.ConnectUserId?Promise.resolve():credentials.ConnectUserId&&credentials.ConnectAccessToken?(connectUser=null,getConnectUser(credentials.ConnectUserId,credentials.ConnectAccessToken).then(function(user){return onConnectUserSignIn(user),Promise.resolve()},function(){return Promise.resolve()})):Promise.resolve()}function getConnectUser(userId,accessToken){if(!userId)throw new Error("null userId");if(!accessToken)throw new Error("null accessToken");var url="https://connect.emby.media/service/user?id="+userId;return ajax({type:"GET",url:url,dataType:"json",headers:{"X-Application":appName+"/"+appVersion,"X-Connect-UserToken":accessToken}})}function addAuthenticationInfoFromConnect(server,connectionMode,credentials){if(!server.ExchangeToken)throw new Error("server.ExchangeToken cannot be null");if(!credentials.ConnectUserId)throw new Error("credentials.ConnectUserId cannot be null");var url=ServerInfo.getServerAddress(server,connectionMode);url=getEmbyServerUrl(url,"Connect/Exchange?format=json&ConnectUserId="+credentials.ConnectUserId);var auth='MediaBrowser Client="'+appName+'", Device="'+deviceName+'", DeviceId="'+deviceId+'", Version="'+appVersion+'"';return ajax({type:"GET",url:url,dataType:"json",headers:{"X-MediaBrowser-Token":server.ExchangeToken,"X-Emby-Authorization":auth}}).then(function(auth){return server.UserId=auth.LocalUserId,server.AccessToken=auth.AccessToken,auth},function(){return server.UserId=null,server.AccessToken=null,Promise.reject()})}function validateAuthentication(server,connectionMode){var url=ServerInfo.getServerAddress(server,connectionMode);return ajax({type:"GET",url:getEmbyServerUrl(url,"System/Info"),dataType:"json",headers:{"X-MediaBrowser-Token":server.AccessToken}}).then(function(systemInfo){return updateServerInfo(server,systemInfo),server.UserId?ajax({type:"GET",url:getEmbyServerUrl(url,"users/"+server.UserId),dataType:"json",headers:{"X-MediaBrowser-Token":server.AccessToken}}).then(function(user){return onLocalUserSignIn(server,connectionMode,user),Promise.resolve()},function(){return server.UserId=null,server.AccessToken=null,Promise.resolve()}):Promise.resolve()},function(){return server.UserId=null,server.AccessToken=null,Promise.resolve()})}function getImageUrl(localUser){if(connectUser&&connectUser.ImageUrl)return{url:connectUser.ImageUrl};if(localUser&&localUser.PrimaryImageTag){var apiClient=self.getApiClient(localUser),url=apiClient.getUserImageUrl(localUser.Id,{tag:localUser.PrimaryImageTag,type:"Primary"});return{url:url,supportsParams:!0}}return{url:null,supportsParams:!1}}function logoutOfServer(apiClient){var serverInfo=apiClient.serverInfo()||{},logoutInfo={serverId:serverInfo.Id};return apiClient.logout().then(function(){events.trigger(self,"localusersignedout",[logoutInfo])},function(){events.trigger(self,"localusersignedout",[logoutInfo])})}function getConnectServers(credentials){if(console.log("Begin getConnectServers"),!credentials.ConnectAccessToken||!credentials.ConnectUserId)return Promise.resolve([]);var url="https://connect.emby.media/service/servers?userId="+credentials.ConnectUserId;return ajax({type:"GET",url:url,dataType:"json",headers:{"X-Application":appName+"/"+appVersion,"X-Connect-UserToken":credentials.ConnectAccessToken}}).then(function(servers){return servers.map(function(i){return{ExchangeToken:i.AccessKey,ConnectServerId:i.Id,Id:i.SystemId,Name:i.Name,RemoteAddress:i.Url,LocalAddress:i.LocalAddress,UserLinkType:"guest"===(i.UserType||"").toLowerCase()?"Guest":"LinkedUser"}})},function(){return credentials.Servers.slice(0).filter(function(s){return s.ExchangeToken})})}function filterServers(servers,connectServers){return servers.filter(function(server){return!server.ExchangeToken||connectServers.filter(function(connectServer){return server.Id===connectServer.Id}).length>0})}function findServers(){return new Promise(function(resolve,reject){var onFinish=function(foundServers){var servers=foundServers.map(function(foundServer){var info={Id:foundServer.Id,LocalAddress:convertEndpointAddressToManualAddress(foundServer)||foundServer.Address,Name:foundServer.Name};return info.LastConnectionMode=info.ManualAddress?ConnectionMode.Manual:ConnectionMode.Local,info});resolve(servers)};require(["serverdiscovery"],function(serverDiscovery){serverDiscovery.findServers(1e3).then(onFinish,function(){onFinish([])})})})}function convertEndpointAddressToManualAddress(info){if(info.Address&&info.EndpointAddress){var address=info.EndpointAddress.split(":")[0],parts=info.Address.split(":");if(parts.length>1){var portString=parts[parts.length-1];isNaN(parseInt(portString))||(address+=":"+portString)}return normalizeAddress(address)}return null}function testNextConnectionMode(tests,index,server,options,resolve){if(index>=tests.length)return console.log("Tested all connection modes. Failing server connection."),void resolveFailure(self,resolve);var mode=tests[index],address=ServerInfo.getServerAddress(server,mode),enableRetry=!1,skipTest=!1,timeout=defaultTimeout;return mode===ConnectionMode.Local?(enableRetry=!0,timeout=8e3,stringEqualsIgnoreCase(address,server.ManualAddress)&&(console.log("skipping LocalAddress test because it is the same as ManualAddress"),skipTest=!0)):mode===ConnectionMode.Manual&&stringEqualsIgnoreCase(address,server.LocalAddress)&&(enableRetry=!0,timeout=8e3),skipTest||!address?(console.log("skipping test at index "+index),void testNextConnectionMode(tests,index+1,server,options,resolve)):(console.log("testing connection mode "+mode+" with server "+server.Name),void tryConnect(address,timeout).then(function(result){1===compareVersions(self.minServerVersion(),result.Version)?(console.log("minServerVersion requirement not met. Server version: "+result.Version),resolve({State:ConnectionState.ServerUpdateNeeded,Servers:[server]})):result.Id!==server.Id?(console.log("http request succeeded, but found a different server Id than what was expected"),resolveFailure(self,resolve)):(console.log("calling onSuccessfulConnection with connection mode "+mode+" with server "+server.Name),onSuccessfulConnection(server,result,mode,options,resolve))},function(){console.log("test failed for connection mode "+mode+" with server "+server.Name),enableRetry?testNextConnectionMode(tests,index+1,server,options,resolve):testNextConnectionMode(tests,index+1,server,options,resolve)}))}function onSuccessfulConnection(server,systemInfo,connectionMode,options,resolve){var credentials=credentialProvider.credentials();options=options||{},credentials.ConnectAccessToken&&options.enableAutoLogin!==!1?ensureConnectUser(credentials).then(function(){server.ExchangeToken?addAuthenticationInfoFromConnect(server,connectionMode,credentials).then(function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)},function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}):afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}):afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}function afterConnectValidated(server,credentials,systemInfo,connectionMode,verifyLocalAuthentication,options,resolve){if(options=options||{},options.enableAutoLogin===!1)server.UserId=null,server.AccessToken=null;else if(verifyLocalAuthentication&&server.AccessToken&&options.enableAutoLogin!==!1)return void validateAuthentication(server,connectionMode).then(function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!1,options,resolve)});updateServerInfo(server,systemInfo),server.LastConnectionMode=connectionMode,options.updateDateLastAccessed!==!1&&(server.DateLastAccessed=(new Date).getTime()),credentialProvider.addOrUpdateServer(credentials.Servers,server),credentialProvider.credentials(credentials);var result={Servers:[]};result.ApiClient=self._getOrAddApiClient(server,connectionMode),result.ApiClient.setSystemInfo(systemInfo),result.State=server.AccessToken&&options.enableAutoLogin!==!1?ConnectionState.SignedIn:ConnectionState.ServerSignIn,result.Servers.push(server),result.ApiClient.updateServerInfo(server,connectionMode),result.State===ConnectionState.SignedIn&&afterConnected(result.ApiClient,options),resolve(result),events.trigger(self,"connected",[result])}function addAppInfoToConnectRequest(request){request.headers=request.headers||{},request.headers["X-Application"]=appName+"/"+appVersion}function exchangePin(pinInfo){if(!pinInfo)throw new Error("pinInfo cannot be null");var request={type:"POST",url:getConnectUrl("pin/authenticate"),data:{deviceId:pinInfo.DeviceId,pin:pinInfo.Pin},dataType:"json"};return addAppInfoToConnectRequest(request),ajax(request)}console.log("Begin ConnectionManager constructor");var self=this;this._apiClients=[];var connectUser;self.connectUser=function(){return connectUser},self._minServerVersion="3.2.22",self.appVersion=function(){return appVersion},self.appName=function(){return appName},self.capabilities=function(){return capabilities},self.deviceId=function(){return deviceId},self.credentialProvider=function(){return credentialProvider},self.connectUserId=function(){return credentialProvider.credentials().ConnectUserId},self.connectToken=function(){return credentialProvider.credentials().ConnectAccessToken},self.getServerInfo=function(id){var servers=credentialProvider.credentials().Servers;return servers.filter(function(s){return s.Id===id})[0]},self.getLastUsedServer=function(){var servers=credentialProvider.credentials().Servers;return servers.sort(function(a,b){return(b.DateLastAccessed||0)-(a.DateLastAccessed||0)}),servers.length?servers[0]:null},self.getLastUsedApiClient=function(){var servers=credentialProvider.credentials().Servers;if(servers.sort(function(a,b){return(b.DateLastAccessed||0)-(a.DateLastAccessed||0)}),!servers.length)return null;var server=servers[0];return self._getOrAddApiClient(server,server.LastConnectionMode)},self.addApiClient=function(apiClient){self._apiClients.push(apiClient);var existingServers=credentialProvider.credentials().Servers.filter(function(s){return stringEqualsIgnoreCase(s.ManualAddress,apiClient.serverAddress())||stringEqualsIgnoreCase(s.LocalAddress,apiClient.serverAddress())||stringEqualsIgnoreCase(s.RemoteAddress,apiClient.serverAddress())}),existingServer=existingServers.length?existingServers[0]:{};if(existingServer.DateLastAccessed=(new Date).getTime(),existingServer.LastConnectionMode=ConnectionMode.Manual,existingServer.ManualAddress=apiClient.serverAddress(),apiClient.serverInfo(existingServer),apiClient.onAuthenticated=function(instance,result){return onAuthenticated(instance,result,{},!0)},!existingServers.length){var credentials=credentialProvider.credentials();credentials.Servers=[existingServer],credentialProvider.credentials(credentials)}events.trigger(self,"apiclientcreated",[apiClient]),existingServer.Id||apiClient.getPublicSystemInfo().then(function(systemInfo){var credentials=credentialProvider.credentials();existingServer.Id=systemInfo.Id,apiClient.serverInfo(existingServer),credentials.Servers=[existingServer],credentialProvider.credentials(credentials)})},self.clearData=function(){console.log("connection manager clearing data"),connectUser=null;var credentials=credentialProvider.credentials();credentials.ConnectAccessToken=null,credentials.ConnectUserId=null,credentials.Servers=[],credentialProvider.credentials(credentials)},self._getOrAddApiClient=function(server,connectionMode){var apiClient=self.getApiClient(server.Id);if(!apiClient){var url=ServerInfo.getServerAddress(server,connectionMode);apiClient=new apiClientFactory(url,appName,appVersion,deviceName,deviceId,devicePixelRatio),self._apiClients.push(apiClient),apiClient.serverInfo(server),apiClient.onAuthenticated=function(instance,result){return onAuthenticated(instance,result,{},!0)},events.trigger(self,"apiclientcreated",[apiClient])}return console.log("returning instance from getOrAddApiClient"),apiClient},self.getOrCreateApiClient=function(serverId){var credentials=credentialProvider.credentials(),servers=credentials.Servers.filter(function(s){return stringEqualsIgnoreCase(s.Id,serverId)});if(!servers.length)throw new Error("Server not found: "+serverId);var server=servers[0];return self._getOrAddApiClient(server,server.LastConnectionMode)},self.user=function(apiClient){return new Promise(function(resolve,reject){function onLocalUserDone(e){var image=getImageUrl(localUser);resolve({localUser:localUser,name:connectUser?connectUser.Name:localUser?localUser.Name:null,imageUrl:image.url,supportsImageParams:image.supportsParams})}function onEnsureConnectUserDone(){apiClient&&apiClient.getCurrentUserId()?apiClient.getCurrentUser().then(function(u){localUser=u,onLocalUserDone()},onLocalUserDone):onLocalUserDone()}var localUser,credentials=credentialProvider.credentials();!credentials.ConnectUserId||!credentials.ConnectAccessToken||apiClient&&apiClient.getCurrentUserId()?onEnsureConnectUserDone():ensureConnectUser(credentials).then(onEnsureConnectUserDone,onEnsureConnectUserDone)})},self.logout=function(){console.log("begin connectionManager loguot");for(var promises=[],i=0,length=self._apiClients.length;ibVal)return 1}return 0}var defaultTimeout=2e4,ConnectionState={Unavailable:0,ServerSelection:1,ServerSignIn:2,SignedIn:3,ConnectSignIn:4,ServerUpdateNeeded:5},ConnectionMode={Local:0,Remote:1,Manual:2},ServerInfo={getServerAddress:function(server,mode){switch(mode){case ConnectionMode.Local:return server.LocalAddress;case ConnectionMode.Manual:return server.ManualAddress;case ConnectionMode.Remote:return server.RemoteAddress;default:return server.ManualAddress||server.LocalAddress||server.RemoteAddress}}},ConnectionManager=function(credentialProvider,appName,appVersion,deviceName,deviceId,capabilities,devicePixelRatio){function onConnectUserSignIn(user){appStorage.removeItem("lastLocalServerId"),connectUser=user,events.trigger(self,"connectusersignedin",[user])}function onAuthenticated(apiClient,result,options,saveCredentials){var credentials=credentialProvider.credentials(),servers=credentials.Servers.filter(function(s){return s.Id===result.ServerId}),server=servers.length?servers[0]:apiClient.serverInfo();return options.updateDateLastAccessed!==!1&&(server.DateLastAccessed=(new Date).getTime()),server.Id=result.ServerId,saveCredentials?(server.UserId=result.User.Id,server.AccessToken=result.AccessToken):(server.UserId=null,server.AccessToken=null),credentialProvider.addOrUpdateServer(credentials.Servers,server),credentialProvider.credentials(credentials),apiClient.serverInfo(server),afterConnected(apiClient,options),onLocalUserSignIn(server,server.LastConnectionMode,result.User)}function afterConnected(apiClient,options){options=options||{},options.reportCapabilities!==!1&&apiClient.reportCapabilities(capabilities),apiClient.enableAutomaticBitrateDetection=options.enableAutomaticBitrateDetection,options.enableWebSocket!==!1&&(console.log("calling apiClient.ensureWebSocket"),apiClient.ensureWebSocket())}function onLocalUserSignIn(server,connectionMode,user){self.connectUserId()?appStorage.removeItem("lastLocalServerId"):appStorage.setItem("lastLocalServerId",server.Id),self._getOrAddApiClient(server,connectionMode);var promise=self.onLocalUserSignedIn?self.onLocalUserSignedIn.call(self,user):Promise.resolve();return promise.then(function(){events.trigger(self,"localusersignedin",[user])})}function ensureConnectUser(credentials){return connectUser&&connectUser.Id===credentials.ConnectUserId?Promise.resolve():credentials.ConnectUserId&&credentials.ConnectAccessToken?(connectUser=null,getConnectUser(credentials.ConnectUserId,credentials.ConnectAccessToken).then(function(user){return onConnectUserSignIn(user),Promise.resolve()},function(){return Promise.resolve()})):Promise.resolve()}function getConnectUser(userId,accessToken){if(!userId)throw new Error("null userId");if(!accessToken)throw new Error("null accessToken");var url="https://connect.emby.media/service/user?id="+userId;return ajax({type:"GET",url:url,dataType:"json",headers:{"X-Application":appName+"/"+appVersion,"X-Connect-UserToken":accessToken}})}function addAuthenticationInfoFromConnect(server,connectionMode,credentials){if(!server.ExchangeToken)throw new Error("server.ExchangeToken cannot be null");if(!credentials.ConnectUserId)throw new Error("credentials.ConnectUserId cannot be null");var url=ServerInfo.getServerAddress(server,connectionMode);url=getEmbyServerUrl(url,"Connect/Exchange?format=json&ConnectUserId="+credentials.ConnectUserId);var auth='MediaBrowser Client="'+appName+'", Device="'+deviceName+'", DeviceId="'+deviceId+'", Version="'+appVersion+'"';return ajax({type:"GET",url:url,dataType:"json",headers:{"X-MediaBrowser-Token":server.ExchangeToken,"X-Emby-Authorization":auth}}).then(function(auth){return server.UserId=auth.LocalUserId,server.AccessToken=auth.AccessToken,auth},function(){return server.UserId=null,server.AccessToken=null,Promise.reject()})}function validateAuthentication(server,connectionMode){var url=ServerInfo.getServerAddress(server,connectionMode);return ajax({type:"GET",url:getEmbyServerUrl(url,"System/Info"),dataType:"json",headers:{"X-MediaBrowser-Token":server.AccessToken}}).then(function(systemInfo){return updateServerInfo(server,systemInfo),server.UserId?ajax({type:"GET",url:getEmbyServerUrl(url,"users/"+server.UserId),dataType:"json",headers:{"X-MediaBrowser-Token":server.AccessToken}}).then(function(user){return onLocalUserSignIn(server,connectionMode,user),Promise.resolve()},function(){return server.UserId=null,server.AccessToken=null,Promise.resolve()}):Promise.resolve()},function(){return server.UserId=null,server.AccessToken=null,Promise.resolve()})}function getImageUrl(localUser){if(connectUser&&connectUser.ImageUrl)return{url:connectUser.ImageUrl};if(localUser&&localUser.PrimaryImageTag){var apiClient=self.getApiClient(localUser),url=apiClient.getUserImageUrl(localUser.Id,{tag:localUser.PrimaryImageTag,type:"Primary"});return{url:url,supportsParams:!0}}return{url:null,supportsParams:!1}}function logoutOfServer(apiClient){var serverInfo=apiClient.serverInfo()||{},logoutInfo={serverId:serverInfo.Id};return apiClient.logout().then(function(){events.trigger(self,"localusersignedout",[logoutInfo])},function(){events.trigger(self,"localusersignedout",[logoutInfo])})}function getConnectServers(credentials){if(console.log("Begin getConnectServers"),!credentials.ConnectAccessToken||!credentials.ConnectUserId)return Promise.resolve([]);var url="https://connect.emby.media/service/servers?userId="+credentials.ConnectUserId;return ajax({type:"GET",url:url,dataType:"json",headers:{"X-Application":appName+"/"+appVersion,"X-Connect-UserToken":credentials.ConnectAccessToken}}).then(function(servers){return servers.map(function(i){return{ExchangeToken:i.AccessKey,ConnectServerId:i.Id,Id:i.SystemId,Name:i.Name,RemoteAddress:i.Url,LocalAddress:i.LocalAddress,UserLinkType:"guest"===(i.UserType||"").toLowerCase()?"Guest":"LinkedUser"}})},function(){return credentials.Servers.slice(0).filter(function(s){return s.ExchangeToken})})}function filterServers(servers,connectServers){return servers.filter(function(server){return!server.ExchangeToken||connectServers.filter(function(connectServer){return server.Id===connectServer.Id}).length>0})}function findServers(){return new Promise(function(resolve,reject){var onFinish=function(foundServers){var servers=foundServers.map(function(foundServer){var info={Id:foundServer.Id,LocalAddress:convertEndpointAddressToManualAddress(foundServer)||foundServer.Address,Name:foundServer.Name};return info.LastConnectionMode=info.ManualAddress?ConnectionMode.Manual:ConnectionMode.Local,info});resolve(servers)};require(["serverdiscovery"],function(serverDiscovery){serverDiscovery.findServers(1e3).then(onFinish,function(){onFinish([])})})})}function convertEndpointAddressToManualAddress(info){if(info.Address&&info.EndpointAddress){var address=info.EndpointAddress.split(":")[0],parts=info.Address.split(":");if(parts.length>1){var portString=parts[parts.length-1];isNaN(parseInt(portString))||(address+=":"+portString)}return normalizeAddress(address)}return null}function testNextConnectionMode(tests,index,server,options,resolve){if(index>=tests.length)return console.log("Tested all connection modes. Failing server connection."),void resolveFailure(self,resolve);var mode=tests[index],address=ServerInfo.getServerAddress(server,mode),enableRetry=!1,skipTest=!1,timeout=defaultTimeout;return mode===ConnectionMode.Local?(enableRetry=!0,timeout=8e3,stringEqualsIgnoreCase(address,server.ManualAddress)&&(console.log("skipping LocalAddress test because it is the same as ManualAddress"),skipTest=!0)):mode===ConnectionMode.Manual&&stringEqualsIgnoreCase(address,server.LocalAddress)&&(enableRetry=!0,timeout=8e3),skipTest||!address?(console.log("skipping test at index "+index),void testNextConnectionMode(tests,index+1,server,options,resolve)):(console.log("testing connection mode "+mode+" with server "+server.Name),void tryConnect(address,timeout).then(function(result){1===compareVersions(self.minServerVersion(),result.Version)?(console.log("minServerVersion requirement not met. Server version: "+result.Version),resolve({State:ConnectionState.ServerUpdateNeeded,Servers:[server]})):result.Id!==server.Id?(console.log("http request succeeded, but found a different server Id than what was expected"),resolveFailure(self,resolve)):(console.log("calling onSuccessfulConnection with connection mode "+mode+" with server "+server.Name),onSuccessfulConnection(server,result,mode,options,resolve))},function(){console.log("test failed for connection mode "+mode+" with server "+server.Name),enableRetry?testNextConnectionMode(tests,index+1,server,options,resolve):testNextConnectionMode(tests,index+1,server,options,resolve)}))}function onSuccessfulConnection(server,systemInfo,connectionMode,options,resolve){var credentials=credentialProvider.credentials();options=options||{},credentials.ConnectAccessToken&&options.enableAutoLogin!==!1?ensureConnectUser(credentials).then(function(){server.ExchangeToken?addAuthenticationInfoFromConnect(server,connectionMode,credentials).then(function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)},function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}):afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}):afterConnectValidated(server,credentials,systemInfo,connectionMode,!0,options,resolve)}function afterConnectValidated(server,credentials,systemInfo,connectionMode,verifyLocalAuthentication,options,resolve){if(options=options||{},options.enableAutoLogin===!1)server.UserId=null,server.AccessToken=null;else if(verifyLocalAuthentication&&server.AccessToken&&options.enableAutoLogin!==!1)return void validateAuthentication(server,connectionMode).then(function(){afterConnectValidated(server,credentials,systemInfo,connectionMode,!1,options,resolve)});updateServerInfo(server,systemInfo),server.LastConnectionMode=connectionMode,options.updateDateLastAccessed!==!1&&(server.DateLastAccessed=(new Date).getTime()),credentialProvider.addOrUpdateServer(credentials.Servers,server),credentialProvider.credentials(credentials);var result={Servers:[]};result.ApiClient=self._getOrAddApiClient(server,connectionMode),result.ApiClient.setSystemInfo(systemInfo),result.State=server.AccessToken&&options.enableAutoLogin!==!1?ConnectionState.SignedIn:ConnectionState.ServerSignIn,result.Servers.push(server),result.ApiClient.updateServerInfo(server,connectionMode),result.State===ConnectionState.SignedIn&&afterConnected(result.ApiClient,options),resolve(result),events.trigger(self,"connected",[result])}function addAppInfoToConnectRequest(request){request.headers=request.headers||{},request.headers["X-Application"]=appName+"/"+appVersion}function exchangePin(pinInfo){if(!pinInfo)throw new Error("pinInfo cannot be null");var request={type:"POST",url:getConnectUrl("pin/authenticate"),data:{deviceId:pinInfo.DeviceId,pin:pinInfo.Pin},dataType:"json"};return addAppInfoToConnectRequest(request),ajax(request)}console.log("Begin ConnectionManager constructor");var self=this;this._apiClients=[];var connectUser;self.connectUser=function(){return connectUser},self._minServerVersion="3.2.24",self.appVersion=function(){return appVersion},self.appName=function(){return appName},self.capabilities=function(){return capabilities},self.deviceId=function(){return deviceId},self.credentialProvider=function(){return credentialProvider},self.connectUserId=function(){return credentialProvider.credentials().ConnectUserId},self.connectToken=function(){return credentialProvider.credentials().ConnectAccessToken},self.getServerInfo=function(id){var servers=credentialProvider.credentials().Servers;return servers.filter(function(s){return s.Id===id})[0]},self.getLastUsedServer=function(){var servers=credentialProvider.credentials().Servers;return servers.sort(function(a,b){return(b.DateLastAccessed||0)-(a.DateLastAccessed||0)}),servers.length?servers[0]:null},self.getLastUsedApiClient=function(){var servers=credentialProvider.credentials().Servers;if(servers.sort(function(a,b){return(b.DateLastAccessed||0)-(a.DateLastAccessed||0)}),!servers.length)return null;var server=servers[0];return self._getOrAddApiClient(server,server.LastConnectionMode)},self.addApiClient=function(apiClient){self._apiClients.push(apiClient);var existingServers=credentialProvider.credentials().Servers.filter(function(s){return stringEqualsIgnoreCase(s.ManualAddress,apiClient.serverAddress())||stringEqualsIgnoreCase(s.LocalAddress,apiClient.serverAddress())||stringEqualsIgnoreCase(s.RemoteAddress,apiClient.serverAddress())}),existingServer=existingServers.length?existingServers[0]:{};if(existingServer.DateLastAccessed=(new Date).getTime(),existingServer.LastConnectionMode=ConnectionMode.Manual,existingServer.ManualAddress=apiClient.serverAddress(),apiClient.serverInfo(existingServer),apiClient.onAuthenticated=function(instance,result){return onAuthenticated(instance,result,{},!0)},!existingServers.length){var credentials=credentialProvider.credentials();credentials.Servers=[existingServer],credentialProvider.credentials(credentials)}events.trigger(self,"apiclientcreated",[apiClient]),existingServer.Id||apiClient.getPublicSystemInfo().then(function(systemInfo){var credentials=credentialProvider.credentials();existingServer.Id=systemInfo.Id,apiClient.serverInfo(existingServer),credentials.Servers=[existingServer],credentialProvider.credentials(credentials)})},self.clearData=function(){console.log("connection manager clearing data"),connectUser=null;var credentials=credentialProvider.credentials();credentials.ConnectAccessToken=null,credentials.ConnectUserId=null,credentials.Servers=[],credentialProvider.credentials(credentials)},self._getOrAddApiClient=function(server,connectionMode){var apiClient=self.getApiClient(server.Id);if(!apiClient){var url=ServerInfo.getServerAddress(server,connectionMode);apiClient=new apiClientFactory(url,appName,appVersion,deviceName,deviceId,devicePixelRatio),self._apiClients.push(apiClient),apiClient.serverInfo(server),apiClient.onAuthenticated=function(instance,result){return onAuthenticated(instance,result,{},!0)},events.trigger(self,"apiclientcreated",[apiClient])}return console.log("returning instance from getOrAddApiClient"),apiClient},self.getOrCreateApiClient=function(serverId){var credentials=credentialProvider.credentials(),servers=credentials.Servers.filter(function(s){return stringEqualsIgnoreCase(s.Id,serverId)});if(!servers.length)throw new Error("Server not found: "+serverId);var server=servers[0];return self._getOrAddApiClient(server,server.LastConnectionMode)},self.user=function(apiClient){return new Promise(function(resolve,reject){function onLocalUserDone(e){var image=getImageUrl(localUser);resolve({localUser:localUser,name:connectUser?connectUser.Name:localUser?localUser.Name:null,imageUrl:image.url,supportsImageParams:image.supportsParams})}function onEnsureConnectUserDone(){apiClient&&apiClient.getCurrentUserId()?apiClient.getCurrentUser().then(function(u){localUser=u,onLocalUserDone()},onLocalUserDone):onLocalUserDone()}var localUser,credentials=credentialProvider.credentials();!credentials.ConnectUserId||!credentials.ConnectAccessToken||apiClient&&apiClient.getCurrentUserId()?onEnsureConnectUserDone():ensureConnectUser(credentials).then(onEnsureConnectUserDone,onEnsureConnectUserDone)})},self.logout=function(){console.log("begin connectionManager loguot");for(var promises=[],i=0,length=self._apiClients.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateCountries(select){return ApiClient.getCountries().then(function(allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateRefreshInterval(select){var html="";html+="",html+=[30,60,90].map(function(val){return""}).join(""),select.innerHTML=html}function embed(parent,contentType,libraryOptions){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET","components/libraryoptionseditor/libraryoptionseditor.template.html",!0),xhr.onload=function(e){var template=this.response;parent.innerHTML=globalize.translateDocument(template),populateRefreshInterval(parent.querySelector("#selectAutoRefreshInterval"));var promises=[populateLanguages(parent.querySelector("#selectLanguage")),populateCountries(parent.querySelector("#selectCountry"))];Promise.all(promises).then(function(){setContentType(parent,contentType),libraryOptions&&setLibraryOptions(parent,libraryOptions),resolve()})},xhr.send()})}function setContentType(parent,contentType){"homevideos"===contentType||"photos"===contentType?(parent.querySelector(".chkEnablePhotosContainer").classList.remove("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.add("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.add("hide"),parent.querySelector(".fldMetadataLanguage").classList.add("hide"),parent.querySelector(".fldMetadataCountry").classList.add("hide"),parent.querySelector(".fldAutoRefreshInterval").classList.add("hide")):(parent.querySelector(".chkEnablePhotosContainer").classList.add("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.remove("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.remove("hide"),parent.querySelector(".fldMetadataLanguage").classList.remove("hide"),parent.querySelector(".fldMetadataCountry").classList.remove("hide"),parent.querySelector(".fldAutoRefreshInterval").classList.remove("hide")),"photos"===contentType?parent.querySelector(".chkSaveLocalContainer").classList.add("hide"):parent.querySelector(".chkSaveLocalContainer").classList.remove("hide"),"tvshows"!==contentType&&"movies"!==contentType&&"homevideos"!==contentType&&"musicvideos"!==contentType&&"mixed"!==contentType&&contentType?parent.querySelector(".chapterSettingsSection").classList.add("hide"):parent.querySelector(".chapterSettingsSection").classList.remove("hide"),"tvshows"===contentType?(parent.querySelector(".chkImportMissingEpisodesContainer").classList.remove("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.remove("hide"),parent.querySelector(".fldSeasonZeroDisplayName").classList.remove("hide")):(parent.querySelector(".chkImportMissingEpisodesContainer").classList.add("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.add("hide"),parent.querySelector(".fldSeasonZeroDisplayName").classList.add("hide")),"games"===contentType||"books"===contentType?parent.querySelector(".chkEnableEmbeddedTitlesContainer").classList.add("hide"):parent.querySelector(".chkEnableEmbeddedTitlesContainer").classList.remove("hide")}function getLibraryOptions(parent){var options={EnableArchiveMediaFiles:!1,EnablePhotos:parent.querySelector(".chkEnablePhotos").checked,EnableRealtimeMonitor:parent.querySelector(".chkEnableRealtimeMonitor").checked,ExtractChapterImagesDuringLibraryScan:parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked,EnableChapterImageExtraction:parent.querySelector(".chkExtractChapterImages").checked,DownloadImagesInAdvance:parent.querySelector("#chkDownloadImagesInAdvance").checked,EnableInternetProviders:parent.querySelector("#chkEnableInternetProviders").checked,ImportMissingEpisodes:parent.querySelector("#chkImportMissingEpisodes").checked,SaveLocalMetadata:parent.querySelector("#chkSaveLocal").checked,EnableAutomaticSeriesGrouping:parent.querySelector(".chkAutomaticallyGroupSeries").checked,PreferredMetadataLanguage:parent.querySelector("#selectLanguage").value,MetadataCountryCode:parent.querySelector("#selectCountry").value,SeasonZeroDisplayName:parent.querySelector("#txtSeasonZeroName").value,AutomaticRefreshIntervalDays:parseInt(parent.querySelector("#selectAutoRefreshInterval").value),EnableEmbeddedTitles:parent.querySelector("#chkEnableEmbeddedTitles").checked};return options}function setLibraryOptions(parent,options){parent.querySelector("#selectLanguage").value=options.PreferredMetadataLanguage||"",parent.querySelector("#selectCountry").value=options.MetadataCountryCode||"",parent.querySelector("#selectAutoRefreshInterval").value=options.AutomaticRefreshIntervalDays||"0",parent.querySelector("#txtSeasonZeroName").value=options.SeasonZeroDisplayName||"",parent.querySelector(".chkEnablePhotos").checked=options.EnablePhotos,parent.querySelector(".chkEnableRealtimeMonitor").checked=options.EnableRealtimeMonitor,parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked=options.ExtractChapterImagesDuringLibraryScan,parent.querySelector(".chkExtractChapterImages").checked=options.EnableChapterImageExtraction,parent.querySelector("#chkDownloadImagesInAdvance").checked=options.DownloadImagesInAdvance,parent.querySelector("#chkEnableInternetProviders").checked=options.EnableInternetProviders,parent.querySelector("#chkSaveLocal").checked=options.SaveLocalMetadata,parent.querySelector("#chkImportMissingEpisodes").checked=options.ImportMissingEpisodes,parent.querySelector(".chkAutomaticallyGroupSeries").checked=options.EnableAutomaticSeriesGrouping,parent.querySelector("#chkEnableEmbeddedTitles").checked=options.EnableEmbeddedTitles}return{embed:embed,setContentType:setContentType,getLibraryOptions:getLibraryOptions,setLibraryOptions:setLibraryOptions}}); \ No newline at end of file +define(["globalize","emby-checkbox","emby-select","emby-input"],function(globalize){"use strict";function populateLanguages(select){return ApiClient.getCultures().then(function(languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateCountries(select){return ApiClient.getCountries().then(function(allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateRefreshInterval(select){var html="";html+="",html+=[30,60,90].map(function(val){return""}).join(""),select.innerHTML=html}function embed(parent,contentType,libraryOptions){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET","components/libraryoptionseditor/libraryoptionseditor.template.html",!0),xhr.onload=function(e){var template=this.response;parent.innerHTML=globalize.translateDocument(template),populateRefreshInterval(parent.querySelector("#selectAutoRefreshInterval"));var promises=[populateLanguages(parent.querySelector("#selectLanguage")),populateCountries(parent.querySelector("#selectCountry"))];Promise.all(promises).then(function(){setContentType(parent,contentType),libraryOptions&&setLibraryOptions(parent,libraryOptions),resolve()})},xhr.send()})}function setContentType(parent,contentType){"homevideos"===contentType||"photos"===contentType?(parent.querySelector(".chkEnablePhotosContainer").classList.remove("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.add("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.add("hide"),parent.querySelector(".fldMetadataLanguage").classList.add("hide"),parent.querySelector(".fldMetadataCountry").classList.add("hide"),parent.querySelector(".fldAutoRefreshInterval").classList.add("hide")):(parent.querySelector(".chkEnablePhotosContainer").classList.add("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.remove("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.remove("hide"),parent.querySelector(".fldMetadataLanguage").classList.remove("hide"),parent.querySelector(".fldMetadataCountry").classList.remove("hide"),parent.querySelector(".fldAutoRefreshInterval").classList.remove("hide")),"photos"===contentType?parent.querySelector(".chkSaveLocalContainer").classList.add("hide"):parent.querySelector(".chkSaveLocalContainer").classList.remove("hide"),"tvshows"!==contentType&&"movies"!==contentType&&"homevideos"!==contentType&&"musicvideos"!==contentType&&"mixed"!==contentType&&contentType?parent.querySelector(".chapterSettingsSection").classList.add("hide"):parent.querySelector(".chapterSettingsSection").classList.remove("hide"),"tvshows"===contentType?(parent.querySelector(".chkImportMissingEpisodesContainer").classList.remove("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.remove("hide"),parent.querySelector(".fldSeasonZeroDisplayName").classList.remove("hide"),parent.querySelector("#txtSeasonZeroName").setAttribute("required","required")):(parent.querySelector(".chkImportMissingEpisodesContainer").classList.add("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.add("hide"),parent.querySelector(".fldSeasonZeroDisplayName").classList.add("hide"),parent.querySelector("#txtSeasonZeroName").removeAttribute("required")),"games"===contentType||"books"===contentType?parent.querySelector(".chkEnableEmbeddedTitlesContainer").classList.add("hide"):parent.querySelector(".chkEnableEmbeddedTitlesContainer").classList.remove("hide")}function getLibraryOptions(parent){var options={EnableArchiveMediaFiles:!1,EnablePhotos:parent.querySelector(".chkEnablePhotos").checked,EnableRealtimeMonitor:parent.querySelector(".chkEnableRealtimeMonitor").checked,ExtractChapterImagesDuringLibraryScan:parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked,EnableChapterImageExtraction:parent.querySelector(".chkExtractChapterImages").checked,DownloadImagesInAdvance:parent.querySelector("#chkDownloadImagesInAdvance").checked,EnableInternetProviders:parent.querySelector("#chkEnableInternetProviders").checked,ImportMissingEpisodes:parent.querySelector("#chkImportMissingEpisodes").checked,SaveLocalMetadata:parent.querySelector("#chkSaveLocal").checked,EnableAutomaticSeriesGrouping:parent.querySelector(".chkAutomaticallyGroupSeries").checked,PreferredMetadataLanguage:parent.querySelector("#selectLanguage").value,MetadataCountryCode:parent.querySelector("#selectCountry").value,SeasonZeroDisplayName:parent.querySelector("#txtSeasonZeroName").value,AutomaticRefreshIntervalDays:parseInt(parent.querySelector("#selectAutoRefreshInterval").value),EnableEmbeddedTitles:parent.querySelector("#chkEnableEmbeddedTitles").checked};return options}function setLibraryOptions(parent,options){parent.querySelector("#selectLanguage").value=options.PreferredMetadataLanguage||"",parent.querySelector("#selectCountry").value=options.MetadataCountryCode||"",parent.querySelector("#selectAutoRefreshInterval").value=options.AutomaticRefreshIntervalDays||"0",parent.querySelector("#txtSeasonZeroName").value=options.SeasonZeroDisplayName||"",parent.querySelector(".chkEnablePhotos").checked=options.EnablePhotos,parent.querySelector(".chkEnableRealtimeMonitor").checked=options.EnableRealtimeMonitor,parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked=options.ExtractChapterImagesDuringLibraryScan,parent.querySelector(".chkExtractChapterImages").checked=options.EnableChapterImageExtraction,parent.querySelector("#chkDownloadImagesInAdvance").checked=options.DownloadImagesInAdvance,parent.querySelector("#chkEnableInternetProviders").checked=options.EnableInternetProviders,parent.querySelector("#chkSaveLocal").checked=options.SaveLocalMetadata,parent.querySelector("#chkImportMissingEpisodes").checked=options.ImportMissingEpisodes,parent.querySelector(".chkAutomaticallyGroupSeries").checked=options.EnableAutomaticSeriesGrouping,parent.querySelector("#chkEnableEmbeddedTitles").checked=options.EnableEmbeddedTitles}return{embed:embed,setContentType:setContentType,getLibraryOptions:getLibraryOptions,setLibraryOptions:setLibraryOptions}}); \ No newline at end of file