diff --git a/dashboard-ui/bower_components/emby-webcomponents/chromecastplayer.js b/dashboard-ui/bower_components/emby-webcomponents/chromecastplayer.js index bb8d1df698..5d1fe87b9d 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/chromecastplayer.js +++ b/dashboard-ui/bower_components/emby-webcomponents/chromecastplayer.js @@ -1 +1 @@ -define(["appSettings","playbackManager","connectionManager","globalize","events","castSenderApiLoader"],function(appSettings,playbackManager,connectionManager,globalize,events,castSenderApiLoader){"use strict";function sendConnectionResult(isOk){var resolve=currentResolve,reject=currentReject;currentResolve=null,currentReject=null,isOk?resolve&&resolve():reject?reject():playbackManager.removeActivePlayer(PlayerName)}function alertText(text,title){require(["alert"],function(alert){alert({text:text,title:title})})}function chromecastPlayer(){function initializeChromecast(){castPlayer=new CastPlayer,document.dispatchEvent(new CustomEvent("chromecastloaded",{detail:{player:self}})),events.on(castPlayer,"connect",function(e){currentResolve?sendConnectionResult(!0):playbackManager.setActivePlayer(PlayerName,self.getCurrentTargetInfo()),console.log("cc: connect"),self.lastPlayerData=null}),events.on(castPlayer,"playbackstart",function(e,data){console.log("cc: playbackstart"),castPlayer.initializeCastPlayer();var state=self.getPlayerStateInternal(data);events.trigger(self,"playbackstart",[state])}),events.on(castPlayer,"playbackstop",function(e,data){console.log("cc: playbackstop");var state=self.getPlayerStateInternal(data);events.trigger(self,"playbackstop",[state]),self.lastPlayerData={}}),events.on(castPlayer,"playbackprogress",function(e,data){console.log("cc: positionchange");var state=self.getPlayerStateInternal(data);events.trigger(self,"timeupdate",[state])}),events.on(castPlayer,"volumechange",function(e,data){console.log("cc: volumechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"volumechange",[state])}),events.on(castPlayer,"repeatmodechange",function(e,data){console.log("cc: repeatmodechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"repeatmodechange",[state])}),events.on(castPlayer,"playstatechange",function(e,data){console.log("cc: playstatechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"pause",[state])})}function normalizeImages(state){if(state&&state.NowPlayingItem){var item=state.NowPlayingItem;item.ImageTags&&item.ImageTags.Primary||item.PrimaryImageTag&&(item.ImageTags=item.ImageTags||{},item.ImageTags.Primary=item.PrimaryImageTag),item.BackdropImageTag&&item.BackdropItemId===item.Id&&(item.BackdropImageTags=[item.BackdropImageTag]),item.BackdropImageTag&&item.BackdropItemId!==item.Id&&(item.ParentBackdropImageTags=[item.BackdropImageTag],item.ParentBackdropItemId=item.BackdropItemId)}}var castPlayer,self=this;self.name=PlayerName,self.type="mediaplayer",self.id="chromecast",self.isLocalPlayer=!1,self.getItemsForPlayback=function(query){var apiClient=ApiClient,userId=apiClient.getCurrentUserId();return query.Ids&&1===query.Ids.split(",").length?apiClient.getItem(userId,query.Ids.split(",")).then(function(item){return{Items:[item],TotalRecordCount:1}}):(query.Limit=query.Limit||100,query.ExcludeLocationTypes="Virtual",apiClient.getItems(userId,query))},self.play=function(options){return options.items?self.playWithCommand(options,"PlayNow"):self.getItemsForPlayback({Ids:options.ids.join(",")}).then(function(result){return options.items=result.Items,self.playWithCommand(options,"PlayNow")})},self.playWithCommand=function(options,command){if(!options.items){var apiClient=connectionManager.getApiClient(options.serverId);return apiClient.getItem(apiClient.getCurrentUserId(),options.ids[0]).then(function(item){return options.items=[item],self.playWithCommand(options,command)})}return castPlayer.loadMedia(options,command)},self.unpause=function(){castPlayer.sendMessage({options:{},command:"Unpause"})},self.playPause=function(){castPlayer.sendMessage({options:{},command:"PlayPause"})},self.pause=function(){castPlayer.sendMessage({options:{},command:"Pause"})},self.shuffle=function(item){var apiClient=connectionManager.getApiClient(item.ServerId),userId=apiClient.getCurrentUserId();apiClient.getItem(userId,item.Id).then(function(item){self.playWithCommand({items:[item]},"Shuffle")})},self.instantMix=function(item){var apiClient=connectionManager.getApiClient(item.ServerId),userId=apiClient.getCurrentUserId();apiClient.getItem(userId,item.Id).then(function(item){self.playWithCommand({items:[item]},"InstantMix")})},self.canPlayMediaType=function(mediaType){return mediaType=(mediaType||"").toLowerCase(),"audio"===mediaType||"video"===mediaType},self.canQueueMediaType=function(mediaType){return self.canPlayMediaType(mediaType)},self.queue=function(options){self.playWithCommand(options,"PlayLast")},self.queueNext=function(options){self.playWithCommand(options,"PlayNext")},self.stop=function(){return castPlayer.sendMessage({options:{},command:"Stop"})},self.displayContent=function(options){castPlayer.sendMessage({options:options,command:"DisplayContent"})},self.isPlaying=function(){var state=self.lastPlayerData||{};return null!=state.NowPlayingItem},self.isPlayingVideo=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},"Video"===state.MediaType},self.isPlayingAudio=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},"Audio"===state.MediaType},self.currentTime=function(val){if(null!=val)return self.seek(val);var state=self.lastPlayerData||{};return state=state.PlayState||{},state.PositionTicks},self.duration=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},state.RunTimeTicks},self.paused=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsPaused},self.isMuted=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsMuted},self.setMute=function(isMuted){isMuted?castPlayer.sendMessage({options:{},command:"Mute"}):castPlayer.sendMessage({options:{},command:"Unmute"})},self.getRepeatMode=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.RepeatMode},self.setRepeatMode=function(mode){castPlayer.sendMessage({options:{RepeatMode:mode},command:"SetRepeatMode"})},self.toggleMute=function(){castPlayer.sendMessage({options:{},command:"ToggleMute"})},self.getTargets=function(){var targets=[];return castPlayer.hasReceivers&&targets.push(self.getCurrentTargetInfo()),Promise.resolve(targets)},self.getCurrentTargetInfo=function(){var appName=null;return castPlayer.session&&castPlayer.session.receiver&&castPlayer.session.receiver.friendlyName&&(appName=castPlayer.session.receiver.friendlyName),{name:PlayerName,id:PlayerName,playerName:PlayerName,playableMediaTypes:["Audio","Video"],isLocalPlayer:!1,appName:PlayerName,deviceName:appName,supportedCommands:["VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","DisplayContent","SetRepeatMode","EndSession"]}},self.seek=function(position){position=parseInt(position),position/=1e7,castPlayer.sendMessage({options:{position:position},command:"Seek"})},self.audioTracks=function(){var state=self.lastPlayerData||{};state=state.NowPlayingItem||{};var streams=state.MediaStreams||[];return streams.filter(function(s){return"Audio"===s.Type})},self.setAudioStreamIndex=function(index){castPlayer.sendMessage({options:{index:index},command:"SetAudioStreamIndex"})},self.getAudioStreamIndex=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.AudioStreamIndex},self.subtitleTracks=function(){var state=self.lastPlayerData||{};state=state.NowPlayingItem||{};var streams=state.MediaStreams||[];return streams.filter(function(s){return"Subtitle"===s.Type})},self.getSubtitleStreamIndex=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.SubtitleStreamIndex},self.setSubtitleStreamIndex=function(index){castPlayer.sendMessage({options:{index:index},command:"SetSubtitleStreamIndex"})},self.getMaxStreamingBitrate=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.MaxStreamingBitrate},self.setMaxStreamingBitrate=function(options){castPlayer.sendMessage({options:options,command:"SetMaxStreamingBitrate"})},self.isFullscreen=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsFullscreen},self.toggleFullscreen=function(){},self.nextTrack=function(){castPlayer.sendMessage({options:{},command:"NextTrack"})},self.previousTrack=function(){castPlayer.sendMessage({options:{},command:"PreviousTrack"})},self.beginPlayerUpdates=function(){},self.endPlayerUpdates=function(){},self.getVolume=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},null==state.VolumeLevel?100:state.VolumeLevel},self.volumeDown=function(){castPlayer.sendMessage({options:{},command:"VolumeDown"})},self.endSession=function(){self.stop().then(function(){setTimeout(function(){castPlayer.stopApp()},1e3)})},self.volumeUp=function(){castPlayer.sendMessage({options:{},command:"VolumeUp"})},self.setVolume=function(vol){vol=Math.min(vol,100),vol=Math.max(vol,0),castPlayer.sendMessage({options:{volume:vol},command:"SetVolume"})},self.getPlaylist=function(){return Promise.resolve([])},self.getCurrentPlaylistItemId=function(){},self.setCurrentPlaylistItem=function(playlistItemId){return Promise.resolve()},self.removeFromPlaylist=function(playlistItemIds){return Promise.resolve()},self.getPlayerState=function(){return Promise.resolve(self.getPlayerStateInternal()||{})},self.lastPlayerData={},self.getPlayerStateInternal=function(data){var triggerStateChange=!1;return data&&!self.lastPlayerData&&(triggerStateChange=!0),data=data||self.lastPlayerData,self.lastPlayerData=data,normalizeImages(data),triggerStateChange&&events.trigger(self,"statechange",[data]),data},self.tryPair=function(target){return castPlayer.deviceState!==DEVICE_STATE.ACTIVE&&castPlayer.isInitialized?new Promise(function(resolve,reject){currentResolve=resolve,currentReject=reject,castPlayer.launchApp()}):(currentResolve=null,currentReject=null,Promise.reject())},castSenderApiLoader.load().then(initializeChromecast)}var currentResolve,currentReject,PlayerName="Chromecast",DEVICE_STATE={IDLE:0,ACTIVE:1,WARNING:2,ERROR:3},PLAYER_STATE={IDLE:"IDLE",LOADING:"LOADING",LOADED:"LOADED",PLAYING:"PLAYING",PAUSED:"PAUSED",STOPPED:"STOPPED",SEEKING:"SEEKING",ERROR:"ERROR"},applicationID="2D4B1DA3",messageNamespace="urn:x-cast:com.connectsdk",CastPlayer=function(){this.deviceState=DEVICE_STATE.IDLE,this.currentMediaSession=null,this.session=null,this.castPlayerState=PLAYER_STATE.IDLE,this.hasReceivers=!1,this.errorHandler=this.onError.bind(this),this.mediaStatusUpdateHandler=this.onMediaStatusUpdate.bind(this),this.initializeCastPlayer()};return CastPlayer.prototype.initializeCastPlayer=function(){var chrome=window.chrome;if(chrome){if(!chrome.cast||!chrome.cast.isAvailable)return void setTimeout(this.initializeCastPlayer.bind(this),1e3);var sessionRequest=new chrome.cast.SessionRequest(applicationID),apiConfig=new chrome.cast.ApiConfig(sessionRequest,this.sessionListener.bind(this),this.receiverListener.bind(this),"origin_scoped");console.log("chromecast.initialize"),chrome.cast.initialize(apiConfig,this.onInitSuccess.bind(this),this.errorHandler)}},CastPlayer.prototype.onInitSuccess=function(){this.isInitialized=!0,console.log("chromecast init success")},CastPlayer.prototype.onError=function(){console.log("chromecast error")},CastPlayer.prototype.sessionListener=function(e){this.session=e,this.session&&(console.log("sessionListener "+JSON.stringify(e)),this.session.media[0]&&this.onMediaDiscovered("activeSession",this.session.media[0]),this.onSessionConnected(e))},CastPlayer.prototype.messageListener=function(namespace,message){if("string"==typeof message&&(message=JSON.parse(message)),"playbackerror"===message.type){var errorCode=message.data;setTimeout(function(){alertText(globalize.translate("MessagePlaybackError"+errorCode),globalize.translate("HeaderPlaybackError"))},300)}else"connectionerror"===message.type?setTimeout(function(){alertText(globalize.translate("MessageChromecastConnectionError"),globalize.translate("HeaderError"))},300):message.type&&events.trigger(this,message.type,[message.data])},CastPlayer.prototype.receiverListener=function(e){"available"===e?(console.log("chromecast receiver found"),this.hasReceivers=!0):(console.log("chromecast receiver list empty"),this.hasReceivers=!1)},CastPlayer.prototype.sessionUpdateListener=function(isAlive){console.log("sessionUpdateListener alive: "+isAlive),isAlive||(this.session=null,this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,console.log("sessionUpdateListener: setting currentMediaSession to null"),this.currentMediaSession=null,sendConnectionResult(!1))},CastPlayer.prototype.launchApp=function(){console.log("chromecast launching app..."),chrome.cast.requestSession(this.onRequestSessionSuccess.bind(this),this.onLaunchError.bind(this))},CastPlayer.prototype.onRequestSessionSuccess=function(e){console.log("chromecast session success: "+e.sessionId),this.onSessionConnected(e)},CastPlayer.prototype.onSessionConnected=function(session){this.session=session,this.deviceState=DEVICE_STATE.ACTIVE,this.session.addMessageListener(messageNamespace,this.messageListener.bind(this)),this.session.addMediaListener(this.sessionMediaListener.bind(this)),this.session.addUpdateListener(this.sessionUpdateListener.bind(this)),events.trigger(this,"connect"),this.sendMessage({options:{},command:"Identify"})},CastPlayer.prototype.sessionMediaListener=function(e){console.log("sessionMediaListener"),this.currentMediaSession=e,this.currentMediaSession.addUpdateListener(this.mediaStatusUpdateHandler)},CastPlayer.prototype.onLaunchError=function(){console.log("chromecast launch error"),this.deviceState=DEVICE_STATE.ERROR,sendConnectionResult(!1)},CastPlayer.prototype.stopApp=function(){this.session&&this.session.stop(this.onStopAppSuccess.bind(this,"Session stopped"),this.errorHandler)},CastPlayer.prototype.onStopAppSuccess=function(message){console.log(message),this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,console.log("onStopAppSuccess: setting currentMediaSession to null"),this.currentMediaSession=null},CastPlayer.prototype.loadMedia=function(options,command){return this.session?(options.items=options.items.map(function(i){return{Id:i.Id,ServerId:i.ServerId,Name:i.Name,Type:i.Type,MediaType:i.MediaType,IsFolder:i.IsFolder}}),this.sendMessage({options:options,command:command})):(console.log("no session"),Promise.reject())},CastPlayer.prototype.sendMessage=function(message){var player=this,receiverName=null,session=player.session;session&&session.receiver&&session.receiver.friendlyName&&(receiverName=session.receiver.friendlyName);var apiClient=ApiClient;message=Object.assign(message,{userId:apiClient.getCurrentUserId(),deviceId:apiClient.deviceId(),accessToken:apiClient.accessToken(),serverAddress:apiClient.serverAddress(),serverId:apiClient.serverId(),receiverName:receiverName});var bitrateSetting=appSettings.maxChromecastBitrate();return bitrateSetting&&(message.maxBitrate=bitrateSetting),new Promise(function(resolve,reject){require(["chromecasthelpers"],function(chromecasthelpers){chromecasthelpers.getServerAddress(apiClient).then(function(serverAddress){message.serverAddress=serverAddress,player.sendMessageInternal(message).then(resolve,reject)},reject)})})},CastPlayer.prototype.sendMessageInternal=function(message){return message=JSON.stringify(message),this.session.sendMessage(messageNamespace,message,this.onPlayCommandSuccess.bind(this),this.errorHandler),Promise.resolve()},CastPlayer.prototype.onPlayCommandSuccess=function(){console.log("Message was sent to receiver ok.")},CastPlayer.prototype.onMediaDiscovered=function(how,mediaSession){console.log("chromecast new media session ID:"+mediaSession.mediaSessionId+" ("+how+")"),this.currentMediaSession=mediaSession,"loadMedia"===how&&(this.castPlayerState=PLAYER_STATE.PLAYING),"activeSession"===how&&(this.castPlayerState=mediaSession.playerState),this.currentMediaSession.addUpdateListener(this.mediaStatusUpdateHandler)},CastPlayer.prototype.onMediaStatusUpdate=function(e){e===!1&&(this.castPlayerState=PLAYER_STATE.IDLE),console.log("chromecast updating media: "+e)},CastPlayer.prototype.setReceiverVolume=function(mute,vol){return this.currentMediaSession?void(mute?this.session.setReceiverMuted(!0,this.mediaCommandSuccessCallback.bind(this),this.errorHandler):this.session.setReceiverVolumeLevel(vol||1,this.mediaCommandSuccessCallback.bind(this),this.errorHandler)):void console.log("this.currentMediaSession is null")},CastPlayer.prototype.mute=function(){this.setReceiverVolume(!0)},CastPlayer.prototype.mediaCommandSuccessCallback=function(info,e){console.log(info)},chromecastPlayer}); \ No newline at end of file +define(["appSettings","playbackManager","connectionManager","globalize","events","castSenderApiLoader"],function(appSettings,playbackManager,connectionManager,globalize,events,castSenderApiLoader){"use strict";function sendConnectionResult(isOk){var resolve=currentResolve,reject=currentReject;currentResolve=null,currentReject=null,isOk?resolve&&resolve():reject?reject():playbackManager.removeActivePlayer(PlayerName)}function alertText(text,title){require(["alert"],function(alert){alert({text:text,title:title})})}function chromecastPlayer(){function initializeChromecast(){castPlayer=new CastPlayer,document.dispatchEvent(new CustomEvent("chromecastloaded",{detail:{player:self}})),events.on(castPlayer,"connect",function(e){currentResolve?sendConnectionResult(!0):playbackManager.setActivePlayer(PlayerName,self.getCurrentTargetInfo()),console.log("cc: connect"),self.lastPlayerData=null}),events.on(castPlayer,"playbackstart",function(e,data){console.log("cc: playbackstart"),castPlayer.initializeCastPlayer();var state=self.getPlayerStateInternal(data);events.trigger(self,"playbackstart",[state])}),events.on(castPlayer,"playbackstop",function(e,data){console.log("cc: playbackstop");var state=self.getPlayerStateInternal(data);events.trigger(self,"playbackstop",[state]),self.lastPlayerData={}}),events.on(castPlayer,"playbackprogress",function(e,data){console.log("cc: positionchange");var state=self.getPlayerStateInternal(data);events.trigger(self,"timeupdate",[state])}),events.on(castPlayer,"volumechange",function(e,data){console.log("cc: volumechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"volumechange",[state])}),events.on(castPlayer,"repeatmodechange",function(e,data){console.log("cc: repeatmodechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"repeatmodechange",[state])}),events.on(castPlayer,"playstatechange",function(e,data){console.log("cc: playstatechange");var state=self.getPlayerStateInternal(data);events.trigger(self,"pause",[state])})}function normalizeImages(state){if(state&&state.NowPlayingItem){var item=state.NowPlayingItem;item.ImageTags&&item.ImageTags.Primary||item.PrimaryImageTag&&(item.ImageTags=item.ImageTags||{},item.ImageTags.Primary=item.PrimaryImageTag),item.BackdropImageTag&&item.BackdropItemId===item.Id&&(item.BackdropImageTags=[item.BackdropImageTag]),item.BackdropImageTag&&item.BackdropItemId!==item.Id&&(item.ParentBackdropImageTags=[item.BackdropImageTag],item.ParentBackdropItemId=item.BackdropItemId)}}var castPlayer,self=this;self.name=PlayerName,self.type="mediaplayer",self.id="chromecast",self.isLocalPlayer=!1,self.getItemsForPlayback=function(query){var apiClient=ApiClient,userId=apiClient.getCurrentUserId();return query.Ids&&1===query.Ids.split(",").length?apiClient.getItem(userId,query.Ids.split(",")).then(function(item){return{Items:[item],TotalRecordCount:1}}):(query.Limit=query.Limit||100,query.ExcludeLocationTypes="Virtual",query.EnableTotalRecordCount=!1,apiClient.getItems(userId,query))},self.play=function(options){return options.items?self.playWithCommand(options,"PlayNow"):self.getItemsForPlayback({Ids:options.ids.join(",")}).then(function(result){return options.items=result.Items,self.playWithCommand(options,"PlayNow")})},self.playWithCommand=function(options,command){if(!options.items){var apiClient=connectionManager.getApiClient(options.serverId);return apiClient.getItem(apiClient.getCurrentUserId(),options.ids[0]).then(function(item){return options.items=[item],self.playWithCommand(options,command)})}return castPlayer.loadMedia(options,command)},self.unpause=function(){castPlayer.sendMessage({options:{},command:"Unpause"})},self.playPause=function(){castPlayer.sendMessage({options:{},command:"PlayPause"})},self.pause=function(){castPlayer.sendMessage({options:{},command:"Pause"})},self.shuffle=function(item){var apiClient=connectionManager.getApiClient(item.ServerId),userId=apiClient.getCurrentUserId();apiClient.getItem(userId,item.Id).then(function(item){self.playWithCommand({items:[item]},"Shuffle")})},self.instantMix=function(item){var apiClient=connectionManager.getApiClient(item.ServerId),userId=apiClient.getCurrentUserId();apiClient.getItem(userId,item.Id).then(function(item){self.playWithCommand({items:[item]},"InstantMix")})},self.canPlayMediaType=function(mediaType){return mediaType=(mediaType||"").toLowerCase(),"audio"===mediaType||"video"===mediaType},self.canQueueMediaType=function(mediaType){return self.canPlayMediaType(mediaType)},self.queue=function(options){self.playWithCommand(options,"PlayLast")},self.queueNext=function(options){self.playWithCommand(options,"PlayNext")},self.stop=function(){return castPlayer.sendMessage({options:{},command:"Stop"})},self.displayContent=function(options){castPlayer.sendMessage({options:options,command:"DisplayContent"})},self.isPlaying=function(){var state=self.lastPlayerData||{};return null!=state.NowPlayingItem},self.isPlayingVideo=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},"Video"===state.MediaType},self.isPlayingAudio=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},"Audio"===state.MediaType},self.currentTime=function(val){if(null!=val)return self.seek(val);var state=self.lastPlayerData||{};return state=state.PlayState||{},state.PositionTicks},self.duration=function(){var state=self.lastPlayerData||{};return state=state.NowPlayingItem||{},state.RunTimeTicks},self.paused=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsPaused},self.isMuted=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsMuted},self.setMute=function(isMuted){isMuted?castPlayer.sendMessage({options:{},command:"Mute"}):castPlayer.sendMessage({options:{},command:"Unmute"})},self.getRepeatMode=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.RepeatMode},self.setRepeatMode=function(mode){castPlayer.sendMessage({options:{RepeatMode:mode},command:"SetRepeatMode"})},self.toggleMute=function(){castPlayer.sendMessage({options:{},command:"ToggleMute"})},self.getTargets=function(){var targets=[];return castPlayer.hasReceivers&&targets.push(self.getCurrentTargetInfo()),Promise.resolve(targets)},self.getCurrentTargetInfo=function(){var appName=null;return castPlayer.session&&castPlayer.session.receiver&&castPlayer.session.receiver.friendlyName&&(appName=castPlayer.session.receiver.friendlyName),{name:PlayerName,id:PlayerName,playerName:PlayerName,playableMediaTypes:["Audio","Video"],isLocalPlayer:!1,appName:PlayerName,deviceName:appName,supportedCommands:["VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","DisplayContent","SetRepeatMode","EndSession"]}},self.seek=function(position){position=parseInt(position),position/=1e7,castPlayer.sendMessage({options:{position:position},command:"Seek"})},self.audioTracks=function(){var state=self.lastPlayerData||{};state=state.NowPlayingItem||{};var streams=state.MediaStreams||[];return streams.filter(function(s){return"Audio"===s.Type})},self.setAudioStreamIndex=function(index){castPlayer.sendMessage({options:{index:index},command:"SetAudioStreamIndex"})},self.getAudioStreamIndex=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.AudioStreamIndex},self.subtitleTracks=function(){var state=self.lastPlayerData||{};state=state.NowPlayingItem||{};var streams=state.MediaStreams||[];return streams.filter(function(s){return"Subtitle"===s.Type})},self.getSubtitleStreamIndex=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.SubtitleStreamIndex},self.setSubtitleStreamIndex=function(index){castPlayer.sendMessage({options:{index:index},command:"SetSubtitleStreamIndex"})},self.getMaxStreamingBitrate=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.MaxStreamingBitrate},self.setMaxStreamingBitrate=function(options){castPlayer.sendMessage({options:options,command:"SetMaxStreamingBitrate"})},self.isFullscreen=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},state.IsFullscreen},self.toggleFullscreen=function(){},self.nextTrack=function(){castPlayer.sendMessage({options:{},command:"NextTrack"})},self.previousTrack=function(){castPlayer.sendMessage({options:{},command:"PreviousTrack"})},self.beginPlayerUpdates=function(){},self.endPlayerUpdates=function(){},self.getVolume=function(){var state=self.lastPlayerData||{};return state=state.PlayState||{},null==state.VolumeLevel?100:state.VolumeLevel},self.volumeDown=function(){castPlayer.sendMessage({options:{},command:"VolumeDown"})},self.endSession=function(){self.stop().then(function(){setTimeout(function(){castPlayer.stopApp()},1e3)})},self.volumeUp=function(){castPlayer.sendMessage({options:{},command:"VolumeUp"})},self.setVolume=function(vol){vol=Math.min(vol,100),vol=Math.max(vol,0),castPlayer.sendMessage({options:{volume:vol},command:"SetVolume"})},self.getPlaylist=function(){return Promise.resolve([])},self.getCurrentPlaylistItemId=function(){},self.setCurrentPlaylistItem=function(playlistItemId){return Promise.resolve()},self.removeFromPlaylist=function(playlistItemIds){return Promise.resolve()},self.getPlayerState=function(){return Promise.resolve(self.getPlayerStateInternal()||{})},self.lastPlayerData={},self.getPlayerStateInternal=function(data){var triggerStateChange=!1;return data&&!self.lastPlayerData&&(triggerStateChange=!0),data=data||self.lastPlayerData,self.lastPlayerData=data,normalizeImages(data),triggerStateChange&&events.trigger(self,"statechange",[data]),data},self.tryPair=function(target){return castPlayer.deviceState!==DEVICE_STATE.ACTIVE&&castPlayer.isInitialized?new Promise(function(resolve,reject){currentResolve=resolve,currentReject=reject,castPlayer.launchApp()}):(currentResolve=null,currentReject=null,Promise.reject())},castSenderApiLoader.load().then(initializeChromecast)}var currentResolve,currentReject,PlayerName="Chromecast",DEVICE_STATE={IDLE:0,ACTIVE:1,WARNING:2,ERROR:3},PLAYER_STATE={IDLE:"IDLE",LOADING:"LOADING",LOADED:"LOADED",PLAYING:"PLAYING",PAUSED:"PAUSED",STOPPED:"STOPPED",SEEKING:"SEEKING",ERROR:"ERROR"},applicationID="2D4B1DA3",messageNamespace="urn:x-cast:com.connectsdk",CastPlayer=function(){this.deviceState=DEVICE_STATE.IDLE,this.currentMediaSession=null,this.session=null,this.castPlayerState=PLAYER_STATE.IDLE,this.hasReceivers=!1,this.errorHandler=this.onError.bind(this),this.mediaStatusUpdateHandler=this.onMediaStatusUpdate.bind(this),this.initializeCastPlayer()};return CastPlayer.prototype.initializeCastPlayer=function(){var chrome=window.chrome;if(chrome){if(!chrome.cast||!chrome.cast.isAvailable)return void setTimeout(this.initializeCastPlayer.bind(this),1e3);var sessionRequest=new chrome.cast.SessionRequest(applicationID),apiConfig=new chrome.cast.ApiConfig(sessionRequest,this.sessionListener.bind(this),this.receiverListener.bind(this),"origin_scoped");console.log("chromecast.initialize"),chrome.cast.initialize(apiConfig,this.onInitSuccess.bind(this),this.errorHandler)}},CastPlayer.prototype.onInitSuccess=function(){this.isInitialized=!0,console.log("chromecast init success")},CastPlayer.prototype.onError=function(){console.log("chromecast error")},CastPlayer.prototype.sessionListener=function(e){this.session=e,this.session&&(console.log("sessionListener "+JSON.stringify(e)),this.session.media[0]&&this.onMediaDiscovered("activeSession",this.session.media[0]),this.onSessionConnected(e))},CastPlayer.prototype.messageListener=function(namespace,message){if("string"==typeof message&&(message=JSON.parse(message)),"playbackerror"===message.type){var errorCode=message.data;setTimeout(function(){alertText(globalize.translate("MessagePlaybackError"+errorCode),globalize.translate("HeaderPlaybackError"))},300)}else"connectionerror"===message.type?setTimeout(function(){alertText(globalize.translate("MessageChromecastConnectionError"),globalize.translate("HeaderError"))},300):message.type&&events.trigger(this,message.type,[message.data])},CastPlayer.prototype.receiverListener=function(e){"available"===e?(console.log("chromecast receiver found"),this.hasReceivers=!0):(console.log("chromecast receiver list empty"),this.hasReceivers=!1)},CastPlayer.prototype.sessionUpdateListener=function(isAlive){console.log("sessionUpdateListener alive: "+isAlive),isAlive||(this.session=null,this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,console.log("sessionUpdateListener: setting currentMediaSession to null"),this.currentMediaSession=null,sendConnectionResult(!1))},CastPlayer.prototype.launchApp=function(){console.log("chromecast launching app..."),chrome.cast.requestSession(this.onRequestSessionSuccess.bind(this),this.onLaunchError.bind(this))},CastPlayer.prototype.onRequestSessionSuccess=function(e){console.log("chromecast session success: "+e.sessionId),this.onSessionConnected(e)},CastPlayer.prototype.onSessionConnected=function(session){this.session=session,this.deviceState=DEVICE_STATE.ACTIVE,this.session.addMessageListener(messageNamespace,this.messageListener.bind(this)),this.session.addMediaListener(this.sessionMediaListener.bind(this)),this.session.addUpdateListener(this.sessionUpdateListener.bind(this)),events.trigger(this,"connect"),this.sendMessage({options:{},command:"Identify"})},CastPlayer.prototype.sessionMediaListener=function(e){console.log("sessionMediaListener"),this.currentMediaSession=e,this.currentMediaSession.addUpdateListener(this.mediaStatusUpdateHandler)},CastPlayer.prototype.onLaunchError=function(){console.log("chromecast launch error"),this.deviceState=DEVICE_STATE.ERROR,sendConnectionResult(!1)},CastPlayer.prototype.stopApp=function(){this.session&&this.session.stop(this.onStopAppSuccess.bind(this,"Session stopped"),this.errorHandler)},CastPlayer.prototype.onStopAppSuccess=function(message){console.log(message),this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,console.log("onStopAppSuccess: setting currentMediaSession to null"),this.currentMediaSession=null},CastPlayer.prototype.loadMedia=function(options,command){return this.session?(options.items=options.items.map(function(i){return{Id:i.Id,ServerId:i.ServerId,Name:i.Name,Type:i.Type,MediaType:i.MediaType,IsFolder:i.IsFolder}}),this.sendMessage({options:options,command:command})):(console.log("no session"),Promise.reject())},CastPlayer.prototype.sendMessage=function(message){var player=this,receiverName=null,session=player.session;session&&session.receiver&&session.receiver.friendlyName&&(receiverName=session.receiver.friendlyName);var apiClient=ApiClient;message=Object.assign(message,{userId:apiClient.getCurrentUserId(),deviceId:apiClient.deviceId(),accessToken:apiClient.accessToken(),serverAddress:apiClient.serverAddress(),serverId:apiClient.serverId(),receiverName:receiverName});var bitrateSetting=appSettings.maxChromecastBitrate();return bitrateSetting&&(message.maxBitrate=bitrateSetting),new Promise(function(resolve,reject){require(["chromecasthelpers"],function(chromecasthelpers){chromecasthelpers.getServerAddress(apiClient).then(function(serverAddress){message.serverAddress=serverAddress,player.sendMessageInternal(message).then(resolve,reject)},reject)})})},CastPlayer.prototype.sendMessageInternal=function(message){return message=JSON.stringify(message),this.session.sendMessage(messageNamespace,message,this.onPlayCommandSuccess.bind(this),this.errorHandler),Promise.resolve()},CastPlayer.prototype.onPlayCommandSuccess=function(){console.log("Message was sent to receiver ok.")},CastPlayer.prototype.onMediaDiscovered=function(how,mediaSession){console.log("chromecast new media session ID:"+mediaSession.mediaSessionId+" ("+how+")"),this.currentMediaSession=mediaSession,"loadMedia"===how&&(this.castPlayerState=PLAYER_STATE.PLAYING),"activeSession"===how&&(this.castPlayerState=mediaSession.playerState),this.currentMediaSession.addUpdateListener(this.mediaStatusUpdateHandler)},CastPlayer.prototype.onMediaStatusUpdate=function(e){e===!1&&(this.castPlayerState=PLAYER_STATE.IDLE),console.log("chromecast updating media: "+e)},CastPlayer.prototype.setReceiverVolume=function(mute,vol){return this.currentMediaSession?void(mute?this.session.setReceiverMuted(!0,this.mediaCommandSuccessCallback.bind(this),this.errorHandler):this.session.setReceiverVolumeLevel(vol||1,this.mediaCommandSuccessCallback.bind(this),this.errorHandler)):void console.log("this.currentMediaSession is null")},CastPlayer.prototype.mute=function(){this.setReceiverVolume(!0)},CastPlayer.prototype.mediaCommandSuccessCallback=function(info,e){console.log(info)},chromecastPlayer}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/collectioneditor/collectioneditor.js b/dashboard-ui/bower_components/emby-webcomponents/collectioneditor/collectioneditor.js index c69d963d35..5c9f66618a 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/collectioneditor/collectioneditor.js +++ b/dashboard-ui/bower_components/emby-webcomponents/collectioneditor/collectioneditor.js @@ -1 +1 @@ -define(["dialogHelper","loading","layoutManager","connectionManager","embyRouter","globalize","emby-checkbox","emby-input","paper-icon-button-light","emby-select","material-icons","css!./../formdialog","emby-button","emby-linkbutton"],function(dialogHelper,loading,layoutManager,connectionManager,embyRouter,globalize){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onSubmit(e){loading.show();var panel=parentWithClass(this,"dialog"),collectionId=panel.querySelector("#selectCollectionToAddTo").value,apiClient=connectionManager.getApiClient(currentServerId);return collectionId?addToCollection(apiClient,panel,collectionId):createCollection(apiClient,panel),e.preventDefault(),!1}function createCollection(apiClient,dlg){var url=apiClient.getUrl("Collections",{Name:dlg.querySelector("#txtNewCollectionName").value,IsLocked:!dlg.querySelector("#chkEnableInternetMetadata").checked,Ids:dlg.querySelector(".fldSelectedItemIds").value||""});apiClient.ajax({type:"POST",url:url,dataType:"json"}).then(function(result){loading.hide();var id=result.Id;dlg.submitted=!0,dialogHelper.close(dlg),redirectToCollection(apiClient,id)})}function redirectToCollection(apiClient,id){apiClient.getItem(apiClient.getCurrentUserId(),id).then(function(item){embyRouter.showItem(item)})}function addToCollection(apiClient,dlg,id){var url=apiClient.getUrl("Collections/"+id+"/Items",{Ids:dlg.querySelector(".fldSelectedItemIds").value||""});apiClient.ajax({type:"POST",url:url}).then(function(){loading.hide(),dlg.submitted=!0,dialogHelper.close(dlg),require(["toast"],function(toast){toast(globalize.translate("sharedcomponents#MessageItemsAdded"))})})}function triggerChange(select){select.dispatchEvent(new CustomEvent("change",{}))}function populateCollections(panel){loading.show();var select=panel.querySelector("#selectCollectionToAddTo");panel.querySelector(".newCollectionInfo").classList.add("hide");var options={Recursive:!0,IncludeItemTypes:"BoxSet",SortBy:"SortName"},apiClient=connectionManager.getApiClient(currentServerId);apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var html="";html+='",html+=result.Items.map(function(i){return'"}),select.innerHTML=html,select.value="",triggerChange(select),loading.hide()})}function getEditorHtml(){var html="";return html+='
',html+='
',html+='
',html+="
",html+=globalize.translate("sharedcomponents#NewCollectionHelp"),html+="
",html+='
',html+="
",html+="
",html+='
',html+='',html+="
",html+="
",html+='
',html+='
',html+='',html+='
'+globalize.translate("sharedcomponents#NewCollectionNameExample")+"
",html+="
",html+='",html+="
",html+='
',html+='",html+="
",html+='',html+="
",html+="
",html+="
"}function initEditor(content,items){if(content.querySelector("#selectCollectionToAddTo").addEventListener("change",function(){this.value?(content.querySelector(".newCollectionInfo").classList.add("hide"),content.querySelector("#txtNewCollectionName").removeAttribute("required")):(content.querySelector(".newCollectionInfo").classList.remove("hide"),content.querySelector("#txtNewCollectionName").setAttribute("required","required"))}),content.querySelector("form").addEventListener("submit",onSubmit),content.querySelector(".fldSelectedItemIds",content).value=items.join(","),items.length)content.querySelector(".fldSelectCollection").classList.remove("hide"),populateCollections(content);else{content.querySelector(".fldSelectCollection").classList.add("hide");var selectCollectionToAddTo=content.querySelector("#selectCollectionToAddTo");selectCollectionToAddTo.innerHTML="",selectCollectionToAddTo.value="",triggerChange(selectCollectionToAddTo)}}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function CollectionEditor(){}var currentServerId;return CollectionEditor.prototype.show=function(options){var items=options.items||{};currentServerId=options.serverId;var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="small";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="",title=items.length?globalize.translate("sharedcomponents#HeaderAddToCollection"):globalize.translate("sharedcomponents#NewCollection");return html+='
',html+='',html+='

',html+=title,html+="

",html+=''+globalize.translate("sharedcomponents#Help")+"",html+="
",html+=getEditorHtml(),dlg.innerHTML=html,initEditor(dlg,items),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg).then(function(){return layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),dlg.submitted?Promise.resolve():Promise.reject()})},CollectionEditor}); \ No newline at end of file +define(["dialogHelper","loading","layoutManager","connectionManager","embyRouter","globalize","emby-checkbox","emby-input","paper-icon-button-light","emby-select","material-icons","css!./../formdialog","emby-button","emby-linkbutton"],function(dialogHelper,loading,layoutManager,connectionManager,embyRouter,globalize){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onSubmit(e){loading.show();var panel=parentWithClass(this,"dialog"),collectionId=panel.querySelector("#selectCollectionToAddTo").value,apiClient=connectionManager.getApiClient(currentServerId);return collectionId?addToCollection(apiClient,panel,collectionId):createCollection(apiClient,panel),e.preventDefault(),!1}function createCollection(apiClient,dlg){var url=apiClient.getUrl("Collections",{Name:dlg.querySelector("#txtNewCollectionName").value,IsLocked:!dlg.querySelector("#chkEnableInternetMetadata").checked,Ids:dlg.querySelector(".fldSelectedItemIds").value||""});apiClient.ajax({type:"POST",url:url,dataType:"json"}).then(function(result){loading.hide();var id=result.Id;dlg.submitted=!0,dialogHelper.close(dlg),redirectToCollection(apiClient,id)})}function redirectToCollection(apiClient,id){apiClient.getItem(apiClient.getCurrentUserId(),id).then(function(item){embyRouter.showItem(item)})}function addToCollection(apiClient,dlg,id){var url=apiClient.getUrl("Collections/"+id+"/Items",{Ids:dlg.querySelector(".fldSelectedItemIds").value||""});apiClient.ajax({type:"POST",url:url}).then(function(){loading.hide(),dlg.submitted=!0,dialogHelper.close(dlg),require(["toast"],function(toast){toast(globalize.translate("sharedcomponents#MessageItemsAdded"))})})}function triggerChange(select){select.dispatchEvent(new CustomEvent("change",{}))}function populateCollections(panel){loading.show();var select=panel.querySelector("#selectCollectionToAddTo");panel.querySelector(".newCollectionInfo").classList.add("hide");var options={Recursive:!0,IncludeItemTypes:"BoxSet",SortBy:"SortName",EnableTotalRecordCount:!1},apiClient=connectionManager.getApiClient(currentServerId);apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var html="";html+='",html+=result.Items.map(function(i){return'"}),select.innerHTML=html,select.value="",triggerChange(select),loading.hide()})}function getEditorHtml(){var html="";return html+='
',html+='
',html+='
',html+="
",html+=globalize.translate("sharedcomponents#NewCollectionHelp"),html+="
",html+='
',html+="
",html+="
",html+='
',html+='',html+="
",html+="
",html+='
',html+='
',html+='',html+='
'+globalize.translate("sharedcomponents#NewCollectionNameExample")+"
",html+="
",html+='",html+="
",html+='
',html+='",html+="
",html+='',html+="
",html+="
",html+="
"}function initEditor(content,items){if(content.querySelector("#selectCollectionToAddTo").addEventListener("change",function(){this.value?(content.querySelector(".newCollectionInfo").classList.add("hide"),content.querySelector("#txtNewCollectionName").removeAttribute("required")):(content.querySelector(".newCollectionInfo").classList.remove("hide"),content.querySelector("#txtNewCollectionName").setAttribute("required","required"))}),content.querySelector("form").addEventListener("submit",onSubmit),content.querySelector(".fldSelectedItemIds",content).value=items.join(","),items.length)content.querySelector(".fldSelectCollection").classList.remove("hide"),populateCollections(content);else{content.querySelector(".fldSelectCollection").classList.add("hide");var selectCollectionToAddTo=content.querySelector("#selectCollectionToAddTo");selectCollectionToAddTo.innerHTML="",selectCollectionToAddTo.value="",triggerChange(selectCollectionToAddTo)}}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function CollectionEditor(){}var currentServerId;return CollectionEditor.prototype.show=function(options){var items=options.items||{};currentServerId=options.serverId;var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="small";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="",title=items.length?globalize.translate("sharedcomponents#HeaderAddToCollection"):globalize.translate("sharedcomponents#NewCollection");return html+='
',html+='',html+='

',html+=title,html+="

",html+=''+globalize.translate("sharedcomponents#Help")+"",html+="
",html+=getEditorHtml(),dlg.innerHTML=html,initEditor(dlg,items),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg).then(function(){return layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),dlg.submitted?Promise.resolve():Promise.reject()})},CollectionEditor}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/emby-scroller/emby-scroller.js b/dashboard-ui/bower_components/emby-webcomponents/emby-scroller/emby-scroller.js index c1d1880dcb..ebea41a559 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/emby-scroller/emby-scroller.js +++ b/dashboard-ui/bower_components/emby-webcomponents/emby-scroller/emby-scroller.js @@ -1 +1 @@ -define(["scroller","dom","layoutManager","inputManager","focusManager","registerElement"],function(scroller,dom,layoutManager,inputManager,focusManager){"use strict";function initCenterFocus(elem,scrollerInstance){dom.addEventListener(elem,"focus",function(e){var focused=focusManager.focusableParent(e.target);focused&&scrollerInstance.toCenter(focused)},{capture:!0,passive:!0})}function onInputCommand(e){var cmd=e.detail.command;"home"===cmd?(focusManager.focusFirst(this,"."+this.getAttribute("data-navcommands")),e.preventDefault(),e.stopPropagation()):"end"===cmd?(focusManager.focusLast(this,"."+this.getAttribute("data-navcommands")),e.preventDefault(),e.stopPropagation()):"pageup"===cmd?(focusManager.moveFocus(e.target,this,"."+this.getAttribute("data-navcommands"),-12),e.preventDefault(),e.stopPropagation()):"pagedown"===cmd&&(focusManager.moveFocus(e.target,this,"."+this.getAttribute("data-navcommands"),12),e.preventDefault(),e.stopPropagation())}function initHeadroom(elem){require(["headroom"],function(Headroom){var headroom=new Headroom([],{scroller:elem});headroom.init(),headroom.add(document.querySelector(".skinHeader")),elem.headroom=headroom})}var ScrollerProtoType=Object.create(HTMLDivElement.prototype);ScrollerProtoType.createdCallback=function(){this.classList.add("emby-scroller")},ScrollerProtoType.scrollToBeginning=function(){this.scroller&&this.scroller.slideTo(0,!0)},ScrollerProtoType.toStart=function(elem,immediate){this.scroller&&this.scroller.toStart(elem,immediate)},ScrollerProtoType.scrollToPosition=function(pos,immediate){this.scroller&&this.scroller.slideTo(pos,immediate)},ScrollerProtoType.getScrollPosition=function(){if(this.scroller)return this.scroller.getScrollPosition()},ScrollerProtoType.attachedCallback=function(){this.getAttribute("data-navcommands")&&inputManager.on(this,onInputCommand);var horizontal="false"!==this.getAttribute("data-horizontal"),slider=this.querySelector(".scrollSlider");horizontal&&(slider.style["white-space"]="nowrap");var bindHeader="true"===this.getAttribute("data-bindheader"),options={horizontal:horizontal,mouseDragging:1,mouseWheel:"false"!==this.getAttribute("data-mousewheel"),touchDragging:1,slidee:slider,scrollBy:200,speed:horizontal?300:270,elasticBounds:1,dragHandle:1,scrollWidth:5e6,autoImmediate:!0,skipSlideToWhenVisible:"true"===this.getAttribute("data-skipfocuswhenvisible"),dispatchScrollEvent:bindHeader||"true"===this.getAttribute("data-scrollevent")},self=this;self.scroller=new scroller(self,options),self.scroller.init(),layoutManager.tv&&self.getAttribute("data-centerfocus")&&initCenterFocus(self,self.scroller),bindHeader&&initHeadroom(self)},ScrollerProtoType.detachedCallback=function(){this.getAttribute("data-navcommands")&&inputManager.off(this,onInputCommand);var headroom=this.headroom;headroom&&(headroom.destroy(),this.headroom=null);var scrollerInstance=this.scroller;scrollerInstance&&(scrollerInstance.destroy(),this.scroller=null)},document.registerElement("emby-scroller",{prototype:ScrollerProtoType,extends:"div"})}); \ No newline at end of file +define(["scroller","dom","layoutManager","inputManager","focusManager","registerElement"],function(scroller,dom,layoutManager,inputManager,focusManager){"use strict";function initCenterFocus(elem,scrollerInstance){dom.addEventListener(elem,"focus",function(e){var focused=focusManager.focusableParent(e.target);focused&&scrollerInstance.toCenter(focused)},{capture:!0,passive:!0})}function onInputCommand(e){var cmd=e.detail.command;"home"===cmd?(focusManager.focusFirst(this,"."+this.getAttribute("data-navcommands")),e.preventDefault(),e.stopPropagation()):"end"===cmd?(focusManager.focusLast(this,"."+this.getAttribute("data-navcommands")),e.preventDefault(),e.stopPropagation()):"pageup"===cmd?(focusManager.moveFocus(e.target,this,"."+this.getAttribute("data-navcommands"),-12),e.preventDefault(),e.stopPropagation()):"pagedown"===cmd&&(focusManager.moveFocus(e.target,this,"."+this.getAttribute("data-navcommands"),12),e.preventDefault(),e.stopPropagation())}function initHeadroom(elem){require(["headroom"],function(Headroom){var headroom=new Headroom([],{scroller:elem});headroom.init(),headroom.add(document.querySelector(".skinHeader")),elem.headroom=headroom})}var ScrollerProtoType=Object.create(HTMLDivElement.prototype);ScrollerProtoType.createdCallback=function(){this.classList.add("emby-scroller")},ScrollerProtoType.scrollToBeginning=function(){this.scroller&&this.scroller.slideTo(0,!0)},ScrollerProtoType.toStart=function(elem,immediate){this.scroller&&this.scroller.toStart(elem,immediate)},ScrollerProtoType.toCenter=function(elem,immediate){this.scroller&&this.scroller.toCenter(elem,immediate)},ScrollerProtoType.scrollToPosition=function(pos,immediate){this.scroller&&this.scroller.slideTo(pos,immediate)},ScrollerProtoType.getScrollPosition=function(){if(this.scroller)return this.scroller.getScrollPosition()},ScrollerProtoType.getScrollSize=function(){if(this.scroller)return this.scroller.getScrollSize()},ScrollerProtoType.attachedCallback=function(){this.getAttribute("data-navcommands")&&inputManager.on(this,onInputCommand);var horizontal="false"!==this.getAttribute("data-horizontal"),slider=this.querySelector(".scrollSlider");horizontal&&(slider.style["white-space"]="nowrap");var bindHeader="true"===this.getAttribute("data-bindheader"),options={horizontal:horizontal,mouseDragging:1,mouseWheel:"false"!==this.getAttribute("data-mousewheel"),touchDragging:1,slidee:slider,scrollBy:200,speed:horizontal?300:270,elasticBounds:1,dragHandle:1,scrollWidth:"auto"===this.getAttribute("data-scrollsize")?null:5e6,autoImmediate:!0,skipSlideToWhenVisible:"true"===this.getAttribute("data-skipfocuswhenvisible"),dispatchScrollEvent:bindHeader||"true"===this.getAttribute("data-scrollevent")},self=this;self.scroller=new scroller(self,options),self.scroller.init(),layoutManager.tv&&self.getAttribute("data-centerfocus")&&initCenterFocus(self,self.scroller),bindHeader&&initHeadroom(self)},ScrollerProtoType.detachedCallback=function(){this.getAttribute("data-navcommands")&&inputManager.off(this,onInputCommand);var headroom=this.headroom;headroom&&(headroom.destroy(),this.headroom=null);var scrollerInstance=this.scroller;scrollerInstance&&(scrollerInstance.destroy(),this.scroller=null)},document.registerElement("emby-scroller",{prototype:ScrollerProtoType,extends:"div"})}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/focusmanager.js b/dashboard-ui/bower_components/emby-webcomponents/focusmanager.js index 43191dd120..bebbad9a27 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/focusmanager.js +++ b/dashboard-ui/bower_components/emby-webcomponents/focusmanager.js @@ -1 +1 @@ -define(["dom"],function(dom){"use strict";function pushScope(elem){scopes.push(elem)}function popScope(elem){scopes.length&&(scopes.length-=1)}function autoFocus(view,defaultToFirst,findAutoFocusElement){var element;return findAutoFocusElement!==!1&&(element=view.querySelector("*[autofocus]"))?(focus(element),element):defaultToFirst!==!1&&(element=getFocusableElements(view,1,"noautofocus")[0])?(focus(element),element):null}function focus(element){try{element.focus()}catch(err){console.log("Error in focusManager.autoFocus: "+err)}}function isFocusable(elem){return focusableTagNames.indexOf(elem.tagName)!==-1||!(!elem.classList||!elem.classList.contains("focusable"))}function focusableParent(elem){for(;!isFocusable(elem);)if(elem=elem.parentNode,!elem)return null;return elem}function isCurrentlyFocusableInternal(elem){return null!==elem.offsetParent}function isCurrentlyFocusable(elem){if(elem.disabled)return!1;if("-1"===elem.getAttribute("tabindex"))return!1;if("INPUT"===elem.tagName){var type=elem.type;if("range"===type)return!1}return isCurrentlyFocusableInternal(elem)}function getDefaultScope(){return scopes[0]||document.body}function getFocusableElements(parent,limit,excludeClass){for(var elems=(parent||getDefaultScope()).querySelectorAll(focusableQuery),focusableElements=[],i=0,length=elems.length;i=limit))break}return focusableElements}function isFocusContainer(elem,direction){if(focusableContainerTagNames.indexOf(elem.tagName)!==-1)return!0;var classList=elem.classList;if(classList.contains("focuscontainer"))return!0;if(0===direction){if(classList.contains("focuscontainer-x"))return!0;if(classList.contains("focuscontainer-left"))return!0}else if(1===direction){if(classList.contains("focuscontainer-x"))return!0;if(classList.contains("focuscontainer-right"))return!0}else if(2===direction){if(classList.contains("focuscontainer-y"))return!0}else if(3===direction){if(classList.contains("focuscontainer-y"))return!0;if(classList.contains("focuscontainer-down"))return!0}return!1}function getFocusContainer(elem,direction){for(;!isFocusContainer(elem,direction);)if(elem=elem.parentNode,!elem)return getDefaultScope();return elem}function getOffset(elem){var box;if(box=elem.getBoundingClientRect?elem.getBoundingClientRect():{top:0,left:0,width:0,height:0},null===box.right){var newBox={top:box.top,left:box.left,width:box.width,height:box.height};box=newBox,box.right=box.left+box.width,box.bottom=box.top+box.height}return box}function nav(activeElement,direction){activeElement=activeElement||document.activeElement,activeElement&&(activeElement=focusableParent(activeElement));var container=activeElement?getFocusContainer(activeElement,direction):getDefaultScope();if(!activeElement)return void autoFocus(container,!0,!1);for(var nearestElement,focusableContainer=dom.parentWithClass(activeElement,"focusable"),rect=getOffset(activeElement),point1x=parseFloat(rect.left)||0,point1y=parseFloat(rect.top)||0,point2x=parseFloat(point1x+rect.width-1)||point1x,point2y=parseFloat(point1y+rect.height-1)||point1y,sourceMidX=(Math.min,Math.max,rect.left+rect.width/2),sourceMidY=rect.top+rect.height/2,focusable=container.querySelectorAll(focusableQuery),maxDistance=1/0,minDistance=maxDistance,i=0,length=focusable.length;i=rect.left)continue;if(elementRect.right===rect.right)continue;break;case 1:if(elementRect.right<=rect.right)continue;if(elementRect.left===rect.left)continue;break;case 2:if(elementRect.top>=rect.top)continue;if(elementRect.bottom>=rect.bottom)continue;break;case 3:if(elementRect.bottom<=rect.bottom)continue;if(elementRect.top<=rect.top)continue}var distX,distY,x=elementRect.left,y=elementRect.top,x2=x+elementRect.width-1,y2=y+elementRect.height-1,intersectX=intersects(point1x,point2x,x,x2),intersectY=intersects(point1y,point2y,y,y2),midX=elementRect.left+elementRect.width/2,midY=elementRect.top+elementRect.height/2;switch(direction){case 0:distX=Math.abs(point1x-Math.min(point1x,x2)),distY=intersectY?0:Math.abs(sourceMidY-midY);break;case 1:distX=Math.abs(point2x-Math.max(point2x,x)),distY=intersectY?0:Math.abs(sourceMidY-midY);break;case 2:distY=Math.abs(point1y-Math.min(point1y,y2)),distX=intersectX?0:Math.abs(sourceMidX-midX);break;case 3:distY=Math.abs(point2y-Math.max(point2y,y)),distX=intersectX?0:Math.abs(sourceMidX-midX)}var dist=Math.sqrt(distX*distX+distY*distY);dist=a1&&b1<=a2||b2>=a1&&b2<=a2}function intersects(a1,a2,b1,b2){return intersectsInternal(a1,a2,b1,b2)||intersectsInternal(b1,b2,a1,a2)}function sendText(text){var elem=document.activeElement;elem.value=text}function focusFirst(container,focusableSelector){for(var elems=container.querySelectorAll(focusableSelector),i=0,length=elems.length;i=limit))break}return focusableElements}function isFocusContainer(elem,direction){if(focusableContainerTagNames.indexOf(elem.tagName)!==-1)return!0;var classList=elem.classList;if(classList.contains("focuscontainer"))return!0;if(0===direction){if(classList.contains("focuscontainer-x"))return!0;if(classList.contains("focuscontainer-left"))return!0}else if(1===direction){if(classList.contains("focuscontainer-x"))return!0;if(classList.contains("focuscontainer-right"))return!0}else if(2===direction){if(classList.contains("focuscontainer-y"))return!0}else if(3===direction){if(classList.contains("focuscontainer-y"))return!0;if(classList.contains("focuscontainer-down"))return!0}return!1}function getFocusContainer(elem,direction){for(;!isFocusContainer(elem,direction);)if(elem=elem.parentNode,!elem)return getDefaultScope();return elem}function getOffset(elem){var box;if(box=elem.getBoundingClientRect?elem.getBoundingClientRect():{top:0,left:0,width:0,height:0},null===box.right){var newBox={top:box.top,left:box.left,width:box.width,height:box.height};box=newBox,box.right=box.left+box.width,box.bottom=box.top+box.height}return box}function nav(activeElement,direction,container){if(activeElement=activeElement||document.activeElement,activeElement&&(activeElement=focusableParent(activeElement)),container=container||(activeElement?getFocusContainer(activeElement,direction):getDefaultScope()),!activeElement)return void autoFocus(container,!0,!1);for(var nearestElement,focusableContainer=dom.parentWithClass(activeElement,"focusable"),rect=getOffset(activeElement),point1x=parseFloat(rect.left)||0,point1y=parseFloat(rect.top)||0,point2x=parseFloat(point1x+rect.width-1)||point1x,point2y=parseFloat(point1y+rect.height-1)||point1y,sourceMidX=(Math.min,Math.max,rect.left+rect.width/2),sourceMidY=rect.top+rect.height/2,focusable=container.querySelectorAll(focusableQuery),maxDistance=1/0,minDistance=maxDistance,i=0,length=focusable.length;i=rect.left)continue;if(elementRect.right===rect.right)continue;break;case 1:if(elementRect.right<=rect.right)continue;if(elementRect.left===rect.left)continue;break;case 2:if(elementRect.top>=rect.top)continue;if(elementRect.bottom>=rect.bottom)continue;break;case 3:if(elementRect.bottom<=rect.bottom)continue;if(elementRect.top<=rect.top)continue}var distX,distY,x=elementRect.left,y=elementRect.top,x2=x+elementRect.width-1,y2=y+elementRect.height-1,intersectX=intersects(point1x,point2x,x,x2),intersectY=intersects(point1y,point2y,y,y2),midX=elementRect.left+elementRect.width/2,midY=elementRect.top+elementRect.height/2;switch(direction){case 0:distX=Math.abs(point1x-Math.min(point1x,x2)),distY=intersectY?0:Math.abs(sourceMidY-midY);break;case 1:distX=Math.abs(point2x-Math.max(point2x,x)),distY=intersectY?0:Math.abs(sourceMidY-midY);break;case 2:distY=Math.abs(point1y-Math.min(point1y,y2)),distX=intersectX?0:Math.abs(sourceMidX-midX);break;case 3:distY=Math.abs(point2y-Math.max(point2y,y)),distX=intersectX?0:Math.abs(sourceMidX-midX)}var dist=Math.sqrt(distX*distX+distY*distY);dist=a1&&b1<=a2||b2>=a1&&b2<=a2}function intersects(a1,a2,b1,b2){return intersectsInternal(a1,a2,b1,b2)||intersectsInternal(b1,b2,a1,a2)}function sendText(text){var elem=document.activeElement;elem.value=text}function focusFirst(container,focusableSelector){for(var elems=container.querySelectorAll(focusableSelector),i=0,length=elems.length;i.programCellInner{background-color:#555}.seriesTimerIcon,.timerIcon{color:#c33!important}.seriesTimerIcon-inactive{color:inherit!important;opacity:.7}.guideOptions{color:#eee;-webkit-flex-shrink:0;flex-shrink:0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}@media all and (max-width:50em),all and (max-height:37.5em){.tvGuideHeader{padding-left:0}}.guideRequiresUnlock{margin:1em auto;text-align:center;padding:1em;-webkit-flex-shrink:0;flex-shrink:0}.noRubberBanding{padding-bottom:100px}.guideDateTabsSlider{text-align:center}.guide-date-tab-button{color:#555!important;padding:.3em .7em!important;margin:0 .3em!important}.guide-date-tab-button.emby-tab-button-active{color:#52B54B!important;border-color:transparent!important}.guide-date-tab-button:focus{color:#52B54B!important}.guide-date-tab-button.emby-button-tv:focus{background-color:#52B54B!important;-webkit-border-radius:.15em!important;border-radius:.15em!important;color:#fff!important;-webkit-transform:none!important;transform:none!important} \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/guide/guide.js b/dashboard-ui/bower_components/emby-webcomponents/guide/guide.js index f55c5170a0..520b5327f4 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/guide/guide.js +++ b/dashboard-ui/bower_components/emby-webcomponents/guide/guide.js @@ -1 +1 @@ -define(["require","browser","globalize","connectionManager","serverNotifications","loading","datetime","focusManager","userSettings","imageLoader","events","layoutManager","itemShortcuts","registrationServices","dom","clearButtonStyle","css!./guide.css","programStyles","material-icons","scrollStyles","emby-button","paper-icon-button-light","emby-tabs","emby-scroller","flexStyles","registerElement"],function(require,browser,globalize,connectionManager,serverNotifications,loading,datetime,focusManager,userSettings,imageLoader,events,layoutManager,itemShortcuts,registrationServices,dom){"use strict";function showViewSettings(instance){require(["guide-settings-dialog"],function(guideSettingsDialog){guideSettingsDialog.show(instance.categoryOptions).then(function(){instance.refresh()})})}function updateProgramCellOnScroll(cell,scrollPct){var left=cell.posLeft;left||(left=parseFloat(cell.style.left.replace("%","")),cell.posLeft=left);var width=cell.posWidth;width||(width=parseFloat(cell.style.width.replace("%","")),cell.posWidth=width);var right=left+width,newPct=Math.max(Math.min(scrollPct,right),left),offset=newPct-left,pctOfWidth=offset/width*100,guideProgramName=cell.guideProgramName;guideProgramName||(guideProgramName=cell.querySelector(".guideProgramName"),cell.guideProgramName=guideProgramName);var caret=cell.caret;caret||(caret=cell.querySelector(".guideProgramNameCaret"),cell.caret=caret),guideProgramName&&(pctOfWidth>1?(guideProgramName.style.transform="translateX("+pctOfWidth+"%)",guideProgramName.classList.add("guideProgramName-withCaret"),caret.classList.remove("hide")):(guideProgramName.style.transform="none",guideProgramName.classList.remove("guideProgramName-withCaret"),caret.classList.add("hide")))}function updateProgramCellsOnScroll(programGrid,programCells){isUpdatingProgramCellScroll||(isUpdatingProgramCellScroll=!0,requestAnimationFrame(function(){for(var scrollLeft=programGrid.scrollLeft,scrollPct=scrollLeft?scrollLeft/programGrid.scrollWidth*100:0,i=0,length=programCells.length;i=0?date.setHours(date.getHours(),cellCurationMinutes,0,0):date.setHours(date.getHours(),0,0,0),date}function showLoading(){loading.show()}function hideLoading(){loading.hide()}function startCurrentTimeUpdateInterval(){clearCurrentTimeUpdateInterval(),currentTimeUpdateInterval=setInterval(updateCurrentTimeIndicator,6e4),updateCurrentTimeIndicator()}function clearCurrentTimeUpdateInterval(){var interval=currentTimeUpdateInterval;interval&&clearInterval(interval),currentTimeUpdateInterval=null,currentTimeIndicatorBar=null,currentTimeIndicatorArrow=null}function updateCurrentTimeIndicator(){if(currentTimeIndicatorBar||(currentTimeIndicatorBar=options.element.querySelector(".currentTimeIndicatorBar")),currentTimeIndicatorArrow||(currentTimeIndicatorArrow=options.element.querySelector(".currentTimeIndicatorArrowContainer")),currentDate){var dateDifference=(new Date).getTime()-currentDate.getTime(),pct=dateDifference>0?dateDifference/totalRendererdMs:0;pct=Math.min(pct,1),pct<=0||pct>=1?(currentTimeIndicatorBar.classList.add("hide"),currentTimeIndicatorArrow.classList.add("hide")):(currentTimeIndicatorBar.classList.remove("hide"),currentTimeIndicatorArrow.classList.remove("hide"),currentTimeIndicatorBar.style.transform="scaleX("+pct+")",currentTimeIndicatorArrow.style.left=100*pct+"%")}}function getChannelLimit(context){return registrationServices.validateFeature("livetv").then(function(){var limit=browser.slow?100:500;return context.querySelector(".guideRequiresUnlock").classList.add("hide"),limit},function(){var limit=5;return context.querySelector(".guideRequiresUnlock").classList.remove("hide"),context.querySelector(".unlockText").innerHTML=globalize.translate("sharedcomponents#LiveTvGuideRequiresUnlock",limit),limit})}function reloadGuide(context,newStartDate,scrollToTimeMs,focusToTimeMs,focusProgramOnRender){var apiClient=connectionManager.currentApiClient(),channelQuery={StartIndex:0,EnableFavoriteSorting:"false"!==userSettings.get("livetv-favoritechannelsattop")};channelQuery.UserId=apiClient.getCurrentUserId(),getChannelLimit(context).then(function(channelLimit){currentChannelLimit=channelLimit,showLoading(),channelQuery.StartIndex=currentStartIndex,channelQuery.Limit=channelLimit,channelQuery.AddCurrentProgram=!1,channelQuery.EnableUserData=!1,channelQuery.EnableImageTypes="Primary";var categories=self.categoryOptions.categories||[],displayMovieContent=!categories.length||categories.indexOf("movies")!==-1,displaySportsContent=!categories.length||categories.indexOf("sports")!==-1,displayNewsContent=!categories.length||categories.indexOf("news")!==-1,displayKidsContent=!categories.length||categories.indexOf("kids")!==-1,displaySeriesContent=!categories.length||categories.indexOf("series")!==-1;displayMovieContent&&displaySportsContent&&displayNewsContent&&displayKidsContent?(channelQuery.IsMovie=null,channelQuery.IsSports=null,channelQuery.IsKids=null,channelQuery.IsNews=null,channelQuery.IsSeries=null):(displayNewsContent&&(channelQuery.IsNews=!0),displaySportsContent&&(channelQuery.IsSports=!0),displayKidsContent&&(channelQuery.IsKids=!0),displayMovieContent&&(channelQuery.IsMovie=!0),displaySeriesContent&&(channelQuery.IsSeries=!0)),"DatePlayed"===userSettings.get("livetv-channelorder")?(channelQuery.SortBy="DatePlayed",channelQuery.SortOrder="Descending"):(channelQuery.SortBy=null,channelQuery.SortOrder=null);var date=newStartDate;date=new Date(date.getTime()+1e3);var nextDay=new Date(date.getTime()+msPerDay-2e3);console.log(nextDay),apiClient.getLiveTvChannels(channelQuery).then(function(channelsResult){var btnPreviousPage=context.querySelector(".btnPreviousPage"),btnNextPage=context.querySelector(".btnNextPage");channelsResult.TotalRecordCount>channelLimit?(context.querySelector(".guideOptions").classList.remove("hide"),btnPreviousPage.classList.remove("hide"),btnNextPage.classList.remove("hide"),channelQuery.StartIndex?context.querySelector(".btnPreviousPage").disabled=!1:context.querySelector(".btnPreviousPage").disabled=!0,channelQuery.StartIndex+channelLimit",startDate.setTime(startDate.getTime()+cellDurationMs);return html+='
',html+="
",html+='
',html+='arrow_drop_down',html+="
"}function parseDates(program){if(!program.StartDateLocal)try{program.StartDateLocal=datetime.parseISO8601Date(program.StartDate,{toLocal:!0})}catch(err){}if(!program.EndDateLocal)try{program.EndDateLocal=datetime.parseISO8601Date(program.EndDate,{toLocal:!0})}catch(err){}return null}function getTimerIndicator(item){var status;if("SeriesTimer"===item.Type)return'';if(item.TimerId||item.SeriesTimerId)status=item.Status||"Cancelled";else{if("Timer"!==item.Type)return"";status=item.Status}return item.SeriesTimerId?"Cancelled"!==status?'':'':''}function getChannelProgramsHtml(context,date,channel,programs,options,listInfo){var html="",startMs=date.getTime(),endMs=startMs+msPerDay-1,outerCssClass=layoutManager.tv?"channelPrograms channelPrograms-tv":"channelPrograms";html+='
';for(var programsFound,clickAction=layoutManager.tv?"link":"programdialog",categories=self.categoryOptions.categories||[],displayMovieContent=!categories.length||categories.indexOf("movies")!==-1,displaySportsContent=!categories.length||categories.indexOf("sports")!==-1,displayNewsContent=!categories.length||categories.indexOf("news")!==-1,displayKidsContent=!categories.length||categories.indexOf("kids")!==-1,displaySeriesContent=!categories.length||categories.indexOf("series")!==-1,enableColorCodedBackgrounds="true"===userSettings.get("guide-colorcodedbackgrounds"),i=listInfo.startIndex,length=programs.length;iendMs)break;items[program.Id]=program;var renderStartMs=Math.max(program.StartDateLocal.getTime(),startMs),startPercent=(program.StartDateLocal.getTime()-startMs)/msPerDay;startPercent*=100,startPercent=Math.max(startPercent,0);var renderEndMs=Math.min(program.EndDateLocal.getTime(),endMs),endPercent=(renderEndMs-renderStartMs)/msPerDay;endPercent*=100;var cssClass="programCell clearButton itemAction",accentCssClass=null,displayInnerContent=!0;program.IsKids?(cssClass+=" childProgramInfo",displayInnerContent=displayKidsContent,accentCssClass="childAccent"):program.IsSports?(cssClass+=" sportsProgramInfo",displayInnerContent=displaySportsContent,accentCssClass="sportsAccent"):program.IsNews?(cssClass+=" newsProgramInfo",displayInnerContent=displayNewsContent,accentCssClass="newsAccent"):program.IsMovie?(cssClass+=" movieProgramInfo",displayInnerContent=displayMovieContent,accentCssClass="movieAccent"):program.IsSeries?(cssClass+=" plainProgramInfo",displayInnerContent=displaySeriesContent):(cssClass+=" plainProgramInfo",displayInnerContent=displayMovieContent&&displayNewsContent&&displaySportsContent&&displayKidsContent&&displaySeriesContent),displayInnerContent||(accentCssClass=null),enableColorCodedBackgrounds&&accentCssClass?(cssClass+=" "+accentCssClass,accentCssClass=null):accentCssClass=null;var timerAttributes="";program.TimerId&&(timerAttributes+=' data-timerid="'+program.TimerId+'"'),program.SeriesTimerId&&(timerAttributes+=' data-seriestimerid="'+program.SeriesTimerId+'"');var isAttribute=endPercent>=2?' is="emby-programcell"':"";if(html+="',displayInnerContent){var guideProgramNameClass="guideProgramName";html+='
',html+='
',html+='
'+program.Name+"
";var indicatorHtml=null;program.IsLive&&options.showLiveIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#Live")+"":program.IsPremiere&&options.showPremiereIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#Premiere")+"":program.IsSeries&&!program.IsRepeat&&options.showNewIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#AttributeNew")+"":program.IsSeries&&program.IsRepeat&&options.showRepeatIndicator&&(indicatorHtml=''+globalize.translate("sharedcomponents#Repeat")+""),(indicatorHtml||program.EpisodeTitle&&options.showEpisodeTitle)&&(html+='
',html+=indicatorHtml||"",program.EpisodeTitle&&options.showEpisodeTitle&&(html+=''+program.EpisodeTitle+""),html+="
"),html+="
",program.IsHD&&options.showHdIcon&&(html+=layoutManager.tv?'
HD
':'
HD
'),html+=getTimerIndicator(program),accentCssClass&&(html+='
')}html+=""}}else if(programsFound)break}return html+="
"}function renderChannelHeaders(context,channels,apiClient){for(var html="",i=0,length=channels.length;i',channel.Number&&(html+='

'+channel.Number+"

"),!hasChannelImage&&channel.Name&&(html+='
'+channel.Name+"
"),html+=""}var channelList=context.querySelector(".channelsContainer");channelList.innerHTML=html,imageLoader.lazyChildren(channelList)}function renderPrograms(context,date,channels,programs){for(var allowIndicators=dom.getWindowSize().innerWidth>=600,options={showHdIcon:allowIndicators&&"true"===userSettings.get("guide-indicator-hd"),showLiveIndicator:allowIndicators&&"false"!==userSettings.get("guide-indicator-live"),showPremiereIndicator:allowIndicators&&"false"!==userSettings.get("guide-indicator-premiere"),showNewIndicator:allowIndicators&&"true"===userSettings.get("guide-indicator-new"),showRepeatIndicator:allowIndicators&&"true"===userSettings.get("guide-indicator-repeat"),showEpisodeTitle:!layoutManager.tv},listInfo={startIndex:0},html=[],i=0,length=channels.length;i=pct||left+width>=pct)break;programCell=programCell.nextSibling}programCell?focusManager.focus(programCell):focusManager.autoFocus(autoFocusParent,!0)}}function nativeScrollTo(container,pos,horizontal){container.scrollTo?horizontal?container.scrollTo(pos,0):container.scrollTo(0,pos):horizontal?container.scrollLeft=Math.round(pos):container.scrollTop=Math.round(pos)}function onProgramGridScroll(context,elem,timeslotHeaders){(new Date).getTime()-lastHeaderScroll>=1e3&&(lastGridScroll=(new Date).getTime(),nativeScrollTo(timeslotHeaders,elem.scrollLeft,!0)),updateProgramCellsOnScroll(elem,programCells)}function onTimeslotHeadersScroll(context,elem,programGrid){(new Date).getTime()-lastGridScroll>=1e3&&(lastHeaderScroll=(new Date).getTime(),nativeScrollTo(programGrid,elem.scrollLeft,!0))}function changeDate(page,date,scrollToTimeMs,focusToTimeMs,focusProgramOnRender){clearCurrentTimeUpdateInterval();var newStartDate=normalizeDateToTimeslot(date);currentDate=newStartDate,reloadGuide(page,newStartDate,scrollToTimeMs,focusToTimeMs,focusProgramOnRender)}function getDateTabText(date,isActive,tabIndex){var cssClass=isActive?"emby-tab-button guide-date-tab-button emby-tab-button-active":"emby-tab-button guide-date-tab-button",html='"}function setDateRange(page,guideInfo){var today=new Date;today.setHours(today.getHours(),0,0,0);var start=datetime.parseISO8601Date(guideInfo.StartDate,{toLocal:!0}),end=datetime.parseISO8601Date(guideInfo.EndDate,{toLocal:!0});start.setHours(0,0,0,0),end.setHours(0,0,0,0),start.getTime()>=end.getTime()&&end.setDate(start.getDate()+1),start=new Date(Math.max(today,start));var dateTabsHtml="",tabIndex=0,date=new Date;for(currentDate&&date.setTime(currentDate.getTime()),date.setHours(0,0,0,0),start.setHours(0,0,0,0);start<=end;){var isActive=date.getDate()===start.getDate()&&date.getMonth()===start.getMonth()&&date.getFullYear()===start.getFullYear();dateTabsHtml+=getDateTabText(start,isActive,tabIndex),start.setDate(start.getDate()+1),start.setHours(0,0,0,0),tabIndex++}page.querySelector(".emby-tabs-slider").innerHTML=dateTabsHtml,page.querySelector(".guideDateTabs").refresh();var newDate=new Date,scrollToTimeMs=60*newDate.getHours()*60*1e3,minutes=newDate.getMinutes();minutes>=30&&(scrollToTimeMs+=18e5);var focusToTimeMs=60*(60*newDate.getHours()+minutes)*1e3;changeDate(page,date,scrollToTimeMs,focusToTimeMs,layoutManager.tv)}function reloadPage(page){showLoading();var apiClient=connectionManager.currentApiClient();apiClient.getLiveTvGuideInfo().then(function(guideInfo){setDateRange(page,guideInfo)})}function setScrollEvents(view,enabled){layoutManager.tv&&require(["scrollHelper"],function(scrollHelper){var fn=enabled?"on":"off";scrollHelper.centerFocus[fn](view.querySelector(".programGrid"),!0)})}function onProgramGridFocus(e){var programCell=dom.parentWithClass(e.target,"programCell");if(programCell){var focused=e.target,id=focused.getAttribute("data-id"),item=items[id];item&&events.trigger(self,"focus",[{item:item}])}}function onTimerCreated(e,apiClient,data){for(var programId=data.ProgramId,newTimerId=data.Id,cells=options.element.querySelectorAll('.programCell[data-id="'+programId+'"]'),i=0,length=cells.length;i'),newTimerId&&cell.setAttribute("data-timerid",newTimerId)}}function onSeriesTimerCreated(e,apiClient,data){}function onTimerCancelled(e,apiClient,data){for(var id=data.Id,cells=options.element.querySelectorAll('.programCell[data-timerid="'+id+'"]'),i=0,length=cells.length;i0?(guideProgramName.style.transform="translateX("+pctOfWidth+"%)",caret.classList.remove("hide")):(guideProgramName.style.transform="none",caret.classList.add("hide")))}function updateProgramCellsOnScroll(programGrid,programCells){isUpdatingProgramCellScroll||(isUpdatingProgramCellScroll=!0,requestAnimationFrame(function(){for(var scrollLeft=programGrid.scrollLeft,scrollPct=scrollLeft?scrollLeft/programGrid.scrollWidth*100:0,i=0,length=programCells.length;i=0?date.setHours(date.getHours(),cellCurationMinutes,0,0):date.setHours(date.getHours(),0,0,0),date}function showLoading(){loading.show()}function hideLoading(){loading.hide()}function startCurrentTimeUpdateInterval(){clearCurrentTimeUpdateInterval(),currentTimeUpdateInterval=setInterval(updateCurrentTimeIndicator,6e4),updateCurrentTimeIndicator()}function clearCurrentTimeUpdateInterval(){var interval=currentTimeUpdateInterval;interval&&clearInterval(interval),currentTimeUpdateInterval=null,currentTimeIndicatorBar=null,currentTimeIndicatorArrow=null}function updateCurrentTimeIndicator(){if(currentTimeIndicatorBar||(currentTimeIndicatorBar=options.element.querySelector(".currentTimeIndicatorBar")),currentTimeIndicatorArrow||(currentTimeIndicatorArrow=options.element.querySelector(".currentTimeIndicatorArrowContainer")),currentDate){var dateDifference=(new Date).getTime()-currentDate.getTime(),pct=dateDifference>0?dateDifference/totalRendererdMs:0;pct=Math.min(pct,1),pct<=0||pct>=1?(currentTimeIndicatorBar.classList.add("hide"),currentTimeIndicatorArrow.classList.add("hide")):(currentTimeIndicatorBar.classList.remove("hide"),currentTimeIndicatorArrow.classList.remove("hide"),currentTimeIndicatorBar.style.transform="scaleX("+pct+")",currentTimeIndicatorArrow.style.left=100*pct+"%")}}function getChannelLimit(context){return registrationServices.validateFeature("livetv").then(function(){var limit=browser.slow?100:500;return context.querySelector(".guideRequiresUnlock").classList.add("hide"),limit},function(){var limit=5;return context.querySelector(".guideRequiresUnlock").classList.remove("hide"),context.querySelector(".unlockText").innerHTML=globalize.translate("sharedcomponents#LiveTvGuideRequiresUnlock",limit),limit})}function reloadGuide(context,newStartDate,scrollToTimeMs,focusToTimeMs,focusProgramOnRender){var apiClient=connectionManager.currentApiClient(),channelQuery={StartIndex:0,EnableFavoriteSorting:"false"!==userSettings.get("livetv-favoritechannelsattop")};channelQuery.UserId=apiClient.getCurrentUserId(),getChannelLimit(context).then(function(channelLimit){currentChannelLimit=channelLimit,showLoading(),channelQuery.StartIndex=currentStartIndex,channelQuery.Limit=channelLimit,channelQuery.AddCurrentProgram=!1,channelQuery.EnableUserData=!1,channelQuery.EnableImageTypes="Primary";var categories=self.categoryOptions.categories||[],displayMovieContent=!categories.length||categories.indexOf("movies")!==-1,displaySportsContent=!categories.length||categories.indexOf("sports")!==-1,displayNewsContent=!categories.length||categories.indexOf("news")!==-1,displayKidsContent=!categories.length||categories.indexOf("kids")!==-1,displaySeriesContent=!categories.length||categories.indexOf("series")!==-1;displayMovieContent&&displaySportsContent&&displayNewsContent&&displayKidsContent?(channelQuery.IsMovie=null,channelQuery.IsSports=null,channelQuery.IsKids=null,channelQuery.IsNews=null,channelQuery.IsSeries=null):(displayNewsContent&&(channelQuery.IsNews=!0),displaySportsContent&&(channelQuery.IsSports=!0),displayKidsContent&&(channelQuery.IsKids=!0),displayMovieContent&&(channelQuery.IsMovie=!0),displaySeriesContent&&(channelQuery.IsSeries=!0)),"DatePlayed"===userSettings.get("livetv-channelorder")?(channelQuery.SortBy="DatePlayed",channelQuery.SortOrder="Descending"):(channelQuery.SortBy=null,channelQuery.SortOrder=null);var date=newStartDate;date=new Date(date.getTime()+1e3);var nextDay=new Date(date.getTime()+msPerDay-2e3);console.log(nextDay),apiClient.getLiveTvChannels(channelQuery).then(function(channelsResult){var btnPreviousPage=context.querySelector(".btnPreviousPage"),btnNextPage=context.querySelector(".btnNextPage");channelsResult.TotalRecordCount>channelLimit?(context.querySelector(".guideOptions").classList.remove("hide"),btnPreviousPage.classList.remove("hide"),btnNextPage.classList.remove("hide"),channelQuery.StartIndex?context.querySelector(".btnPreviousPage").disabled=!1:context.querySelector(".btnPreviousPage").disabled=!0,channelQuery.StartIndex+channelLimit",startDate.setTime(startDate.getTime()+cellDurationMs);return html+='
',html+="
",html+='
',html+='arrow_drop_down',html+="
"}function parseDates(program){if(!program.StartDateLocal)try{program.StartDateLocal=datetime.parseISO8601Date(program.StartDate,{toLocal:!0})}catch(err){}if(!program.EndDateLocal)try{program.EndDateLocal=datetime.parseISO8601Date(program.EndDate,{toLocal:!0})}catch(err){}return null}function getTimerIndicator(item){var status;if("SeriesTimer"===item.Type)return'';if(item.TimerId||item.SeriesTimerId)status=item.Status||"Cancelled";else{if("Timer"!==item.Type)return"";status=item.Status}return item.SeriesTimerId?"Cancelled"!==status?'':'':''}function getChannelProgramsHtml(context,date,channel,programs,options,listInfo){var html="",startMs=date.getTime(),endMs=startMs+msPerDay-1,outerCssClass=layoutManager.tv?"channelPrograms channelPrograms-tv":"channelPrograms";html+='
';for(var programsFound,clickAction=layoutManager.tv?"link":"programdialog",categories=self.categoryOptions.categories||[],displayMovieContent=!categories.length||categories.indexOf("movies")!==-1,displaySportsContent=!categories.length||categories.indexOf("sports")!==-1,displayNewsContent=!categories.length||categories.indexOf("news")!==-1,displayKidsContent=!categories.length||categories.indexOf("kids")!==-1,displaySeriesContent=!categories.length||categories.indexOf("series")!==-1,enableColorCodedBackgrounds="true"===userSettings.get("guide-colorcodedbackgrounds"),i=listInfo.startIndex,length=programs.length;iendMs)break;items[program.Id]=program;var renderStartMs=Math.max(program.StartDateLocal.getTime(),startMs),startPercent=(program.StartDateLocal.getTime()-startMs)/msPerDay;startPercent*=100,startPercent=Math.max(startPercent,0);var renderEndMs=Math.min(program.EndDateLocal.getTime(),endMs),endPercent=(renderEndMs-renderStartMs)/msPerDay;endPercent*=100;var cssClass="programCell clearButton itemAction",accentCssClass=null,displayInnerContent=!0;program.IsKids?(cssClass+=" childProgramInfo",displayInnerContent=displayKidsContent,accentCssClass="childAccent"):program.IsSports?(cssClass+=" sportsProgramInfo",displayInnerContent=displaySportsContent,accentCssClass="sportsAccent"):program.IsNews?(cssClass+=" newsProgramInfo",displayInnerContent=displayNewsContent,accentCssClass="newsAccent"):program.IsMovie?(cssClass+=" movieProgramInfo",displayInnerContent=displayMovieContent,accentCssClass="movieAccent"):program.IsSeries?(cssClass+=" plainProgramInfo",displayInnerContent=displaySeriesContent):(cssClass+=" plainProgramInfo",displayInnerContent=displayMovieContent&&displayNewsContent&&displaySportsContent&&displayKidsContent&&displaySeriesContent);var timerAttributes="";program.TimerId&&(timerAttributes+=' data-timerid="'+program.TimerId+'"'),program.SeriesTimerId&&(timerAttributes+=' data-seriestimerid="'+program.SeriesTimerId+'"');var isAttribute=endPercent>=2?' is="emby-programcell"':"";if(html+="',html+=displayInnerContent&&enableColorCodedBackgrounds&&accentCssClass?'
':'
',displayInnerContent){var guideProgramNameClass="guideProgramName";html+='
',html+='
',html+='
'+program.Name;var indicatorHtml=null;program.IsLive&&options.showLiveIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#Live")+"":program.IsPremiere&&options.showPremiereIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#Premiere")+"":program.IsSeries&&!program.IsRepeat&&options.showNewIndicator?indicatorHtml=''+globalize.translate("sharedcomponents#AttributeNew")+"":program.IsSeries&&program.IsRepeat&&options.showRepeatIndicator&&(indicatorHtml=''+globalize.translate("sharedcomponents#Repeat")+""),(indicatorHtml||program.EpisodeTitle&&options.showEpisodeTitle)&&(html+='
',html+=indicatorHtml||"",program.EpisodeTitle&&options.showEpisodeTitle&&(html+=''+program.EpisodeTitle+""),html+="
"),html+="
",program.IsHD&&options.showHdIcon&&(html+=layoutManager.tv?'
HD
':'
HD
'),html+=getTimerIndicator(program),html+="
"}html+="
",html+=""}}else if(programsFound)break}return html+="
"}function renderChannelHeaders(context,channels,apiClient){for(var html="",i=0,length=channels.length;i',channel.Number&&(html+='

'+channel.Number+"

"),!hasChannelImage&&channel.Name&&(html+='
'+channel.Name+"
"),html+=""}var channelList=context.querySelector(".channelsContainer");channelList.innerHTML=html,imageLoader.lazyChildren(channelList)}function renderPrograms(context,date,channels,programs){for(var allowIndicators=dom.getWindowSize().innerWidth>=600,options={showHdIcon:allowIndicators&&"true"===userSettings.get("guide-indicator-hd"),showLiveIndicator:allowIndicators&&"false"!==userSettings.get("guide-indicator-live"),showPremiereIndicator:allowIndicators&&"false"!==userSettings.get("guide-indicator-premiere"),showNewIndicator:allowIndicators&&"true"===userSettings.get("guide-indicator-new"),showRepeatIndicator:allowIndicators&&"true"===userSettings.get("guide-indicator-repeat"),showEpisodeTitle:!layoutManager.tv},listInfo={startIndex:0},html=[],i=0,length=channels.length;i=pct||left+width>=pct)break;programCell=programCell.nextSibling}programCell?focusManager.focus(programCell):focusManager.autoFocus(autoFocusParent,!0)}}function nativeScrollTo(container,pos,horizontal){container.scrollTo?horizontal?container.scrollTo(pos,0):container.scrollTo(0,pos):horizontal?container.scrollLeft=Math.round(pos):container.scrollTop=Math.round(pos)}function onProgramGridScroll(context,elem,timeslotHeaders){(new Date).getTime()-lastHeaderScroll>=1e3&&(lastGridScroll=(new Date).getTime(),nativeScrollTo(timeslotHeaders,elem.scrollLeft,!0)),updateProgramCellsOnScroll(elem,programCells)}function onTimeslotHeadersScroll(context,elem){(new Date).getTime()-lastGridScroll>=1e3&&(lastHeaderScroll=(new Date).getTime(),nativeScrollTo(programGrid,elem.scrollLeft,!0))}function changeDate(page,date,scrollToTimeMs,focusToTimeMs,focusProgramOnRender){clearCurrentTimeUpdateInterval();var newStartDate=normalizeDateToTimeslot(date);currentDate=newStartDate,reloadGuide(page,newStartDate,scrollToTimeMs,focusToTimeMs,focusProgramOnRender)}function getDateTabText(date,isActive,tabIndex){var cssClass=isActive?"emby-tab-button guide-date-tab-button emby-tab-button-active":"emby-tab-button guide-date-tab-button",html='"}function setDateRange(page,guideInfo){var today=new Date;today.setHours(today.getHours(),0,0,0);var start=datetime.parseISO8601Date(guideInfo.StartDate,{toLocal:!0}),end=datetime.parseISO8601Date(guideInfo.EndDate,{toLocal:!0});start.setHours(0,0,0,0),end.setHours(0,0,0,0),start.getTime()>=end.getTime()&&end.setDate(start.getDate()+1),start=new Date(Math.max(today,start));var dateTabsHtml="",tabIndex=0,date=new Date;for(currentDate&&date.setTime(currentDate.getTime()),date.setHours(0,0,0,0),start.setHours(0,0,0,0);start<=end;){var isActive=date.getDate()===start.getDate()&&date.getMonth()===start.getMonth()&&date.getFullYear()===start.getFullYear();dateTabsHtml+=getDateTabText(start,isActive,tabIndex),start.setDate(start.getDate()+1),start.setHours(0,0,0,0),tabIndex++}page.querySelector(".emby-tabs-slider").innerHTML=dateTabsHtml,page.querySelector(".guideDateTabs").refresh();var newDate=new Date,newDateHours=newDate.getHours(),scrollToTimeMs=60*newDateHours*60*1e3,minutes=newDate.getMinutes();minutes>=30&&(scrollToTimeMs+=18e5);var focusToTimeMs=60*(60*newDateHours+minutes)*1e3;changeDate(page,date,scrollToTimeMs,focusToTimeMs,layoutManager.tv)}function reloadPage(page){showLoading();var apiClient=connectionManager.currentApiClient();apiClient.getLiveTvGuideInfo().then(function(guideInfo){setDateRange(page,guideInfo)})}function getChildren(element){var nativeResult=element.children;if(nativeResult)return nativeResult;for(var node,i=0,nodes=element.childNodes,children=[];null!=(node=nodes[i++]);)1===node.nodeType&&children.push(node);return children}function isFirstChild(element){var children=getChildren(element.parentNode);return element===children[0]}function isLastChild(element){var children=getChildren(element.parentNode);return children.length>0&&element===children[children.length-1]}function onInputCommand(e){var container,target=e.target,programCell=dom.parentWithClass(target,"programCell"),scrollX=!1;switch(e.detail.command){case"up":container=programCell?programGrid:null,container&&isFirstChild(dom.parentWithClass(programCell,"channelPrograms"))&&(container=null),lastFocusDirection=e.detail.command,focusManager.moveUp(target,{container:container});break;case"down":container=programCell?programGrid:null,container&&isLastChild(dom.parentWithClass(programCell,"channelPrograms"))&&(container=null),lastFocusDirection=e.detail.command,focusManager.moveDown(target,{container:container});break;case"left":container=programCell?dom.parentWithClass(programCell,"channelPrograms"):null,container&&isFirstChild(programCell)&&(container=null),lastFocusDirection=e.detail.command,focusManager.moveLeft(target,{container:container}),scrollX=!0;break;case"right":container=programCell?dom.parentWithClass(programCell,"channelPrograms"):null,lastFocusDirection=e.detail.command,focusManager.moveRight(target,{container:container}),scrollX=!0;break;default:return}e.preventDefault(),e.stopPropagation()}function onScrollerFocus(e){var target=e.target,programCell=dom.parentWithClass(target,"programCell");if(programCell){var focused=target,id=focused.getAttribute("data-id"),item=items[id];item&&events.trigger(self,"focus",[{item:item}])}if("left"===lastFocusDirection||"right"===lastFocusDirection)programCell&&scrollHelper.toCenter(programGrid,programCell,!0);else if("up"===lastFocusDirection||"down"===lastFocusDirection){var verticalScroller=dom.parentWithClass(target,"guideVerticalScroller");if(verticalScroller){var focusedElement=programCell||dom.parentWithTag(target,"BUTTON");verticalScroller.toCenter(focusedElement,!0)}}}function setScrollEvents(view,enabled){if(layoutManager.tv){var guideVerticalScroller=view.querySelector(".guideVerticalScroller");enabled?inputManager.on(guideVerticalScroller,onInputCommand):inputManager.off(guideVerticalScroller,onInputCommand)}}function onTimerCreated(e,apiClient,data){for(var programId=data.ProgramId,newTimerId=data.Id,cells=options.element.querySelectorAll('.programCell[data-id="'+programId+'"]'),i=0,length=cells.length;i'),newTimerId&&cell.setAttribute("data-timerid",newTimerId)}}function onSeriesTimerCreated(e,apiClient,data){}function onTimerCancelled(e,apiClient,data){for(var id=data.Id,cells=options.element.querySelectorAll('.programCell[data-timerid="'+id+'"]'),i=0,length=cells.length;i
+
-
+
+
diff --git a/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js b/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js index 494a412155..a77a354137 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js +++ b/dashboard-ui/bower_components/emby-webcomponents/htmlvideoplayer/plugin.js @@ -1 +1 @@ -define(["browser","require","events","apphost","loading","dom","playbackManager","embyRouter","appSettings","connectionManager"],function(browser,require,events,appHost,loading,dom,playbackManager,embyRouter,appSettings,connectionManager){"use strict";function tryRemoveElement(elem){var parentNode=elem.parentNode;if(parentNode)try{parentNode.removeChild(elem)}catch(err){console.log("Error removing dialog element: "+err)}}function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function HtmlVideoPlayer(){function updateVideoUrl(streamInfo){var isHls=streamInfo.url.toLowerCase().indexOf(".m3u8")!==-1,mediaSource=streamInfo.mediaSource,item=streamInfo.item;if(mediaSource&&item&&!mediaSource.RunTimeTicks&&isHls&&"Transcode"===streamInfo.playMethod&&(browser.iOS||browser.osx)){var hlsPlaylistUrl=streamInfo.url.replace("master.m3u8","live.m3u8");return loading.show(),console.log("prefetching hls playlist: "+hlsPlaylistUrl),connectionManager.getApiClient(item.ServerId).ajax({type:"GET",url:hlsPlaylistUrl}).then(function(){return console.log("completed prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),streamInfo.url=hlsPlaylistUrl,Promise.resolve()},function(){return console.log("error prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),Promise.resolve()})}return Promise.resolve()}function getSupportedFeatures(){var list=[],video=document.createElement("video");return browser.ipad&&navigator.userAgent.toLowerCase().indexOf("os 9")===-1&&video.webkitSupportsPresentationMode&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&list.push("PictureInPicture"),list.push("SetBrightness"),list}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function requireHlsPlayer(callback){require(["hlsjs"],function(hls){window.Hls=hls,callback()})}function bindEventsToHlsPlayer(hls,elem,resolve,reject){hls.on(Hls.Events.MANIFEST_PARSED,function(){playWithPromise(elem).then(resolve,function(){reject&&(reject(),reject=null)})}),hls.on(Hls.Events.ERROR,function(event,data){if(console.log("HLS Error: Type: "+data.type+" Details: "+(data.details||"")+" Fatal: "+(data.fatal||!1)),data.fatal)switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:data.response&&data.response.code&&data.response.code>=400&&data.response.code<500?(console.log("hls.js response error code: "+data.response.code),reject?(reject(),reject=null):onErrorInternal("network")):(console.log("fatal network error encountered, try to recover"),hls.startLoad());break;case Hls.ErrorTypes.MEDIA_ERROR:console.log("fatal media error encountered, try to recover");var currentReject=reject;reject=null,handleMediaError(currentReject);break;default:hls.destroy(),reject?(reject(),reject=null):onErrorInternal("mediadecodeerror")}})}function setCurrentSrc(elem,options){elem.removeEventListener("error",onError);var val=options.url;console.log("playing url: "+val);var seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds),destroyHlsPlayer();for(var tracks=getMediaStreamTextTracks(options.mediaSource),currentTrackIndex=-1,i=0,length=tracks.length;i'+getTracksHtml(tracks,options.mediaSource,options.item.ServerId),elem.addEventListener("loadedmetadata",onLoadedMetadata),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)):applySrc(elem,val,options).then(function(){return setTracks(elem,tracks,options.mediaSource,options.item.ServerId),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)})}function handleMediaError(reject){if(hlsPlayer){var now=Date.now();window.performance&&window.performance.now&&(now=performance.now()),!recoverDecodingErrorDate||now-recoverDecodingErrorDate>3e3?(recoverDecodingErrorDate=now,console.log("try to recover media Error ..."),hlsPlayer.recoverMediaError()):!recoverSwapAudioCodecDate||now-recoverSwapAudioCodecDate>3e3?(recoverSwapAudioCodecDate=now,console.log("try to swap Audio Codec and recover media Error ..."),hlsPlayer.swapAudioCodec(),hlsPlayer.recoverMediaError()):(console.error("cannot recover, last media error recovery failed ..."),reject?reject():onErrorInternal("mediadecodeerror"))}}function applySrc(elem,src,options){return window.Windows&&options.mediaSource&&options.mediaSource.IsLocal?Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4;return playlist.items.append(new Windows.Media.Playback.MediaPlaybackItem(source1,startTime)),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),Promise.resolve()}):(elem.src=src,Promise.resolve())}function onSuccessfulPlay(elem){elem.addEventListener("error",onError)}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?(onSuccessfulPlay(elem),Promise.resolve()):Promise.reject()}):(onSuccessfulPlay(elem),Promise.resolve())}catch(err){return console.log("error calling video.play: "+err),Promise.reject()}}function destroyHlsPlayer(){var player=hlsPlayer;if(player){try{player.destroy()}catch(err){console.log(err)}hlsPlayer=null}}function onEnded(){destroyCustomTrack(this),onEndedInternal(!0,this)}function onEndedInternal(triggerEnded,elem){if(elem.removeEventListener("error",onError),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),destroyHlsPlayer(),self.originalDocumentTitle&&(document.title=self.originalDocumentTitle,self.originalDocumentTitle=null),triggerEnded){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null}currentSrc=null}function onTimeUpdate(e){var time=this.currentTime;time&&!timeUpdated&&(timeUpdated=!0,ensureValidVideo(this)),_currentTime=time;var timeMs=1e3*time;timeMs+=(currentPlayOptions.transcodingOffsetTicks||0)/1e4,updateSubtitleText(timeMs),events.trigger(self,"timeupdate")}function onVolumeChange(){saveVolume(this.volume),events.trigger(self,"volumechange")}function onNavigatedToOsd(){videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")}function onPlaying(e){started?events.trigger(self,"unpause"):(started=!0,this.removeAttribute("controls"),currentPlayOptions.title?(self.originalDocumentTitle=document.title,document.title=currentPlayOptions.title):self.originalDocumentTitle=null,setCurrentTrackElement(subtitleTrackIndexToSetOnPlaying),seekOnPlaybackStart(e.target),currentPlayOptions.fullscreen?embyRouter.showVideoOsd().then(onNavigatedToOsd):(embyRouter.setTransparency("backdrop"),videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")),loading.hide()),events.trigger(self,"playing")}function ensureValidVideo(elem){if(elem===mediaElement)return 0===elem.videoWidth&&0===elem.videoHeight?void onErrorInternal("mediadecodeerror"):void 0}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onClick(){events.trigger(self,"click")}function onDblClick(){events.trigger(self,"dblclick")}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code||0:0;console.log("Media element error code: "+errorCode.toString());var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:if(hlsPlayer)return void handleMediaError();type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){destroyCustomTrack(mediaElement),events.trigger(self,"error",[{type:type}])}function onLoadedMetadata(e){var mediaElem=e.target;if(mediaElem.removeEventListener("loadedmetadata",onLoadedMetadata),!hlsPlayer)try{mediaElem.play()}catch(err){console.log("error calling mediaElement.play: "+err)}}function enableHlsPlayer(src,item,mediaSource){if(src&&src.indexOf(".m3u8")===-1)return!1;if(null==window.MediaSource)return!1;if(canPlayNativeHls()){if(browser.edge)return!0;if(mediaSource.RunTimeTicks)return!1}return!(browser.safari&&!browser.osx)}function canPlayNativeHls(){var media=document.createElement("video");return!(!media.canPlayType("application/x-mpegURL").replace(/no/,"")&&!media.canPlayType("application/vnd.apple.mpegURL").replace(/no/,""))}function setTracks(elem,tracks,mediaSource,serverId){elem.innerHTML=getTracksHtml(tracks,mediaSource,serverId)}function getTextTrackUrl(track,serverId){return playbackManager.getSubtitleUrl(track,serverId)}function getTracksHtml(tracks,mediaSource,serverId){return tracks.map(function(t){var defaultAttribute=mediaSource.DefaultSubtitleStreamIndex===t.Index?" default":"",language=t.Language||"und",label=t.Language||"und";return'"}).join("")}function enableNativeTrackSupport(track){if(browser.firefox&&(currentSrc||"").toLowerCase().indexOf(".m3u8")!==-1)return!1;if(browser.ps4)return!1;if(browser.edge)return!1;if(track){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return!1}return!0}function destroyCustomTrack(videoElement){if(window.removeEventListener("resize",onVideoResize),window.removeEventListener("orientationchange",onVideoResize),videoSubtitlesElem){var subtitlesContainer=videoSubtitlesElem.parentNode;subtitlesContainer&&tryRemoveElement(subtitlesContainer),videoSubtitlesElem=null}if(currentTrackEvents=null,videoElement)for(var allTracks=videoElement.textTracks||[],i=0;i
',videoSubtitlesElem=subtitlesContainer.querySelector(".videoSubtitlesInner"),videoElement.parentNode.appendChild(subtitlesContainer),currentTrackEvents=data.TrackEvents}})}function renderTracksEvents(videoElement,track,serverId){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return void renderWithLibjass(videoElement,track,serverId);if(requiresCustomSubtitlesElement())return void renderSubtitlesWithCustomElement(videoElement,track,serverId);for(var trackElement=null,expectedId="manualTrack"+track.Index,allTracks=videoElement.textTracks,i=0;i=ticks){selectedTrackEvent=currentTrackEvent;break}}selectedTrackEvent?(videoSubtitlesElem.innerHTML=normalizeTrackEventText(selectedTrackEvent.Text),videoSubtitlesElem.classList.remove("hide")):(videoSubtitlesElem.innerHTML="",videoSubtitlesElem.classList.add("hide"))}}}function getMediaStreamAudioTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Audio"===s.Type})}function getMediaStreamTextTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type&&"External"===s.DeliveryMethod})}function setCurrentTrackElement(streamIndex){console.log("Setting new text track index to: "+streamIndex);var mediaStreamTextTracks=getMediaStreamTextTracks(currentPlayOptions.mediaSource),track=streamIndex===-1?null:mediaStreamTextTracks.filter(function(t){return t.Index===streamIndex})[0];enableNativeTrackSupport(track)?setTrackForCustomDisplay(mediaElement,null):(setTrackForCustomDisplay(mediaElement,track),streamIndex=-1,track=null);for(var expectedId="textTrack"+streamIndex,trackIndex=streamIndex!==-1&&track?mediaStreamTextTracks.indexOf(track):-1,modes=["disabled","showing","hidden"],allTracks=mediaElement.textTracks,i=0;i':'",dlg.innerHTML=html;var videoElement=dlg.querySelector("video");videoElement.volume=getSavedVolume(),videoElement.addEventListener("timeupdate",onTimeUpdate),videoElement.addEventListener("ended",onEnded),videoElement.addEventListener("volumechange",onVolumeChange),videoElement.addEventListener("pause",onPause),videoElement.addEventListener("playing",onPlaying),videoElement.addEventListener("click",onClick),videoElement.addEventListener("dblclick",onDblClick),document.body.insertBefore(dlg,document.body.firstChild),videoDialog=dlg,mediaElement=videoElement,options.fullscreen&&browser.supportsCssAnimation()&&!browser.slow?zoomIn(dlg).then(function(){resolve(videoElement)}):resolve(videoElement)})})}var self=this;self.name="Html Video Player",self.type="mediaplayer",self.id="htmlvideoplayer",self.priority=1;var mediaElement,videoDialog,currentSrc,hlsPlayer,currentPlayOptions,subtitleTrackIndexToSetOnPlaying,currentClock,currentAssRenderer,videoSubtitlesElem,currentTrackEvents,started=!1,timeUpdated=!1,lastCustomTrackMs=0,customTrackIndex=-1;self.currentSrc=function(){return currentSrc},self.play=function(options){return browser.msie&&"Transcode"===options.playMethod&&!window.MediaSource?(alert("Playback of this content is not supported in Internet Explorer. For a better experience, try a modern browser such as Microsoft Edge, Google Chrome, Firefox or Opera."),Promise.reject()):(started=!1,timeUpdated=!1,_currentTime=null,createMediaElement(options).then(function(elem){return updateVideoUrl(options,options.mediaSource).then(function(){return setCurrentSrc(elem,options)})}))};var supportedFeatures;self.supports=function(feature){return supportedFeatures||(supportedFeatures=getSupportedFeatures()),supportedFeatures.indexOf(feature)!==-1},self.setPictureInPictureEnabled=function(isEnabled){var video=mediaElement;video&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&video.webkitSetPresentationMode(isEnabled?"picture-in-picture":"inline")},self.isPictureInPictureEnabled=function(isEnabled){var video=mediaElement;return!!video&&"picture-in-picture"===video.webkitPresentationMode};var recoverDecodingErrorDate,recoverSwapAudioCodecDate;self.setSubtitleStreamIndex=function(index){setCurrentTrackElement(index)},self.canSetAudioStreamIndex=function(){return!(!browser.edge&&!browser.msie)},self.setAudioStreamIndex=function(index){var i,length,audioStreams=getMediaStreamAudioTracks(currentPlayOptions.mediaSource),audioTrackOffset=-1;for(i=0,length=audioStreams.length;i=100?"none":rawValue/100;elem.style["-webkit-filter"]="brightness("+cssValue+");",elem.style.filter="brightness("+cssValue+")",elem.brightnessValue=val,events.trigger(self,"brightnesschange")}},self.getBrightness=function(){if(mediaElement){var val=mediaElement.brightnessValue;return null==val?100:val}},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted}}return HtmlVideoPlayer.prototype.canPlayMediaType=function(mediaType){return"video"===(mediaType||"").toLowerCase()},HtmlVideoPlayer.prototype.getDeviceProfile=function(item,options){return appHost.getDeviceProfile?appHost.getDeviceProfile(item,options):getDefaultProfile()},HtmlVideoPlayer.prototype.setAspectRatio=function(val){},HtmlVideoPlayer.prototype.getAspectRatio=function(){return this._currentAspectRatio},HtmlVideoPlayer.prototype.getSupportedAspectRatios=function(){return[]},HtmlVideoPlayer.prototype.togglePictureInPicture=function(){return this.setPictureInPictureEnabled(!this.isPictureInPictureEnabled())},HtmlVideoPlayer}); \ No newline at end of file +define(["browser","require","events","apphost","loading","dom","playbackManager","embyRouter","appSettings","connectionManager"],function(browser,require,events,appHost,loading,dom,playbackManager,embyRouter,appSettings,connectionManager){"use strict";function tryRemoveElement(elem){var parentNode=elem.parentNode;if(parentNode)try{parentNode.removeChild(elem)}catch(err){console.log("Error removing dialog element: "+err)}}function getSavedVolume(){return appSettings.get("volume")||1}function saveVolume(value){value&&appSettings.set("volume",value)}function getDefaultProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile"],function(profileBuilder){resolve(profileBuilder({}))})})}function HtmlVideoPlayer(){function updateVideoUrl(streamInfo){var isHls=streamInfo.url.toLowerCase().indexOf(".m3u8")!==-1,mediaSource=streamInfo.mediaSource,item=streamInfo.item;if(mediaSource&&item&&!mediaSource.RunTimeTicks&&isHls&&"Transcode"===streamInfo.playMethod&&(browser.iOS||browser.osx)){var hlsPlaylistUrl=streamInfo.url.replace("master.m3u8","live.m3u8");return loading.show(),console.log("prefetching hls playlist: "+hlsPlaylistUrl),connectionManager.getApiClient(item.ServerId).ajax({type:"GET",url:hlsPlaylistUrl}).then(function(){return console.log("completed prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),streamInfo.url=hlsPlaylistUrl,Promise.resolve()},function(){return console.log("error prefetching hls playlist: "+hlsPlaylistUrl),loading.hide(),Promise.resolve()})}return Promise.resolve()}function getSupportedFeatures(){var list=[],video=document.createElement("video");return browser.ipad&&navigator.userAgent.toLowerCase().indexOf("os 9")===-1&&video.webkitSupportsPresentationMode&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&list.push("PictureInPicture"),list.push("SetBrightness"),list}function getCrossOriginValue(mediaSource){return mediaSource.IsRemote?null:"anonymous"}function requireHlsPlayer(callback){require(["hlsjs"],function(hls){window.Hls=hls,callback()})}function bindEventsToHlsPlayer(hls,elem,resolve,reject){hls.on(Hls.Events.MANIFEST_PARSED,function(){playWithPromise(elem).then(resolve,function(){reject&&(reject(),reject=null)})}),hls.on(Hls.Events.ERROR,function(event,data){if(console.log("HLS Error: Type: "+data.type+" Details: "+(data.details||"")+" Fatal: "+(data.fatal||!1)),data.fatal)switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:data.response&&data.response.code&&data.response.code>=400&&data.response.code<500?(console.log("hls.js response error code: "+data.response.code),reject?(reject(),reject=null):onErrorInternal("network")):(console.log("fatal network error encountered, try to recover"),hls.startLoad());break;case Hls.ErrorTypes.MEDIA_ERROR:console.log("fatal media error encountered, try to recover");var currentReject=reject;reject=null,handleMediaError(currentReject);break;default:hls.destroy(),reject?(reject(),reject=null):onErrorInternal("mediadecodeerror")}})}function setCurrentSrc(elem,options){elem.removeEventListener("error",onError);var val=options.url;console.log("playing url: "+val);var seconds=(options.playerStartPositionTicks||0)/1e7;seconds&&(val+="#t="+seconds),destroyHlsPlayer();for(var tracks=getMediaStreamTextTracks(options.mediaSource),currentTrackIndex=-1,i=0,length=tracks.length;i'+getTracksHtml(tracks,options.mediaSource,options.item.ServerId),elem.addEventListener("loadedmetadata",onLoadedMetadata),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)):applySrc(elem,val,options).then(function(){return setTracks(elem,tracks,options.mediaSource,options.item.ServerId),currentSrc=val,setCurrentTrackElement(currentTrackIndex),playWithPromise(elem)})}function handleMediaError(reject){if(hlsPlayer){var now=Date.now();window.performance&&window.performance.now&&(now=performance.now()),!recoverDecodingErrorDate||now-recoverDecodingErrorDate>3e3?(recoverDecodingErrorDate=now,console.log("try to recover media Error ..."),hlsPlayer.recoverMediaError()):!recoverSwapAudioCodecDate||now-recoverSwapAudioCodecDate>3e3?(recoverSwapAudioCodecDate=now,console.log("try to swap Audio Codec and recover media Error ..."),hlsPlayer.swapAudioCodec(),hlsPlayer.recoverMediaError()):(console.error("cannot recover, last media error recovery failed ..."),reject?reject():onErrorInternal("mediadecodeerror"))}}function applySrc(elem,src,options){return window.Windows&&options.mediaSource&&options.mediaSource.IsLocal?Windows.Storage.StorageFile.getFileFromPathAsync(options.url).then(function(file){var playlist=new Windows.Media.Playback.MediaPlaybackList,source1=Windows.Media.Core.MediaSource.createFromStorageFile(file),startTime=(options.playerStartPositionTicks||0)/1e4;return playlist.items.append(new Windows.Media.Playback.MediaPlaybackItem(source1,startTime)),elem.src=URL.createObjectURL(playlist,{oneTimeOnly:!0}),Promise.resolve()}):(elem.src=src,Promise.resolve())}function onSuccessfulPlay(elem){elem.addEventListener("error",onError)}function playWithPromise(elem){try{var promise=elem.play();return promise&&promise.then?promise.catch(function(e){var errorName=(e.name||"").toLowerCase();return"notallowederror"===errorName||"aborterror"===errorName?(onSuccessfulPlay(elem),Promise.resolve()):Promise.reject()}):(onSuccessfulPlay(elem),Promise.resolve())}catch(err){return console.log("error calling video.play: "+err),Promise.reject()}}function destroyHlsPlayer(){var player=hlsPlayer;if(player){try{player.destroy()}catch(err){console.log(err)}hlsPlayer=null}}function onEnded(){destroyCustomTrack(this),onEndedInternal(!0,this)}function onEndedInternal(triggerEnded,elem){if(elem.removeEventListener("error",onError),elem.src="",elem.innerHTML="",elem.removeAttribute("src"),destroyHlsPlayer(),self.originalDocumentTitle&&(document.title=self.originalDocumentTitle,self.originalDocumentTitle=null),triggerEnded){var stopInfo={src:currentSrc};events.trigger(self,"stopped",[stopInfo]),_currentTime=null}currentSrc=null}function onTimeUpdate(e){var time=this.currentTime;time&&!timeUpdated&&(timeUpdated=!0,ensureValidVideo(this)),_currentTime=time;var timeMs=1e3*time;timeMs+=(currentPlayOptions.transcodingOffsetTicks||0)/1e4,updateSubtitleText(timeMs),events.trigger(self,"timeupdate")}function onVolumeChange(){saveVolume(this.volume),events.trigger(self,"volumechange")}function onNavigatedToOsd(){videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")}function onPlaying(e){started?events.trigger(self,"unpause"):(started=!0,this.removeAttribute("controls"),currentPlayOptions.title?(self.originalDocumentTitle=document.title,document.title=currentPlayOptions.title):self.originalDocumentTitle=null,setCurrentTrackElement(subtitleTrackIndexToSetOnPlaying),seekOnPlaybackStart(e.target),currentPlayOptions.fullscreen?embyRouter.showVideoOsd().then(onNavigatedToOsd):(embyRouter.setTransparency("backdrop"),videoDialog.classList.remove("videoPlayerContainer-withBackdrop"),videoDialog.classList.remove("videoPlayerContainer-onTop")),loading.hide()),events.trigger(self,"playing")}function ensureValidVideo(elem){if(elem===mediaElement)return 0===elem.videoWidth&&0===elem.videoHeight?void onErrorInternal("mediadecodeerror"):void 0}function seekOnPlaybackStart(element){var seconds=(currentPlayOptions.playerStartPositionTicks||0)/1e7;if(seconds){var src=(self.currentSrc()||"").toLowerCase();if(!browser.chrome||src.indexOf(".m3u8")!==-1){var delay=browser.safari?2500:0;delay?setTimeout(function(){element.currentTime=seconds},delay):element.currentTime=seconds}}}function onClick(){events.trigger(self,"click")}function onDblClick(){events.trigger(self,"dblclick")}function onPause(){events.trigger(self,"pause")}function onError(){var errorCode=this.error?this.error.code||0:0;console.log("Media element error code: "+errorCode.toString());var type;switch(errorCode){case 1:return;case 2:type="network";break;case 3:if(hlsPlayer)return void handleMediaError();type="mediadecodeerror";break;case 4:type="medianotsupported";break;default:return}onErrorInternal(type)}function onErrorInternal(type){destroyCustomTrack(mediaElement),events.trigger(self,"error",[{type:type}])}function onLoadedMetadata(e){var mediaElem=e.target;if(mediaElem.removeEventListener("loadedmetadata",onLoadedMetadata),!hlsPlayer)try{mediaElem.play()}catch(err){console.log("error calling mediaElement.play: "+err)}}function enableHlsPlayer(src,item,mediaSource){if(src&&src.indexOf(".m3u8")===-1)return!1;if(null==window.MediaSource)return!1;if(canPlayNativeHls()){if(browser.edge)return!0;if(mediaSource.RunTimeTicks)return!1}return!(browser.safari&&!browser.osx)}function canPlayNativeHls(){var media=document.createElement("video");return!(!media.canPlayType("application/x-mpegURL").replace(/no/,"")&&!media.canPlayType("application/vnd.apple.mpegURL").replace(/no/,""))}function setTracks(elem,tracks,mediaSource,serverId){elem.innerHTML=getTracksHtml(tracks,mediaSource,serverId)}function getTextTrackUrl(track,serverId){return playbackManager.getSubtitleUrl(track,serverId)}function getTracksHtml(tracks,mediaSource,serverId){return tracks.map(function(t){var defaultAttribute=mediaSource.DefaultSubtitleStreamIndex===t.Index?" default":"",language=t.Language||"und",label=t.Language||"und";return'"}).join("")}function enableNativeTrackSupport(track){if(browser.firefox&&(currentSrc||"").toLowerCase().indexOf(".m3u8")!==-1)return!1;if(browser.ps4)return!1;if(browser.edge)return!1;if(track){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return!1}return!0}function destroyCustomTrack(videoElement){if(window.removeEventListener("resize",onVideoResize),window.removeEventListener("orientationchange",onVideoResize),videoSubtitlesElem){var subtitlesContainer=videoSubtitlesElem.parentNode;subtitlesContainer&&tryRemoveElement(subtitlesContainer),videoSubtitlesElem=null}if(currentTrackEvents=null,videoElement)for(var allTracks=videoElement.textTracks||[],i=0;i
',videoSubtitlesElem=subtitlesContainer.querySelector(".videoSubtitlesInner"),videoElement.parentNode.appendChild(subtitlesContainer),currentTrackEvents=data.TrackEvents}})}function renderTracksEvents(videoElement,track,serverId){var format=(track.Codec||"").toLowerCase();if("ssa"===format||"ass"===format)return void renderWithLibjass(videoElement,track,serverId);if(requiresCustomSubtitlesElement())return void renderSubtitlesWithCustomElement(videoElement,track,serverId);for(var trackElement=null,expectedId="manualTrack"+track.Index,allTracks=videoElement.textTracks,i=0;i=ticks){selectedTrackEvent=currentTrackEvent;break}}selectedTrackEvent?(videoSubtitlesElem.innerHTML=normalizeTrackEventText(selectedTrackEvent.Text),videoSubtitlesElem.classList.remove("hide")):(videoSubtitlesElem.innerHTML="",videoSubtitlesElem.classList.add("hide"))}}}function getMediaStreamAudioTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Audio"===s.Type})}function getMediaStreamTextTracks(mediaSource){return mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type&&"External"===s.DeliveryMethod})}function setCurrentTrackElement(streamIndex){console.log("Setting new text track index to: "+streamIndex);var mediaStreamTextTracks=getMediaStreamTextTracks(currentPlayOptions.mediaSource),track=streamIndex===-1?null:mediaStreamTextTracks.filter(function(t){return t.Index===streamIndex})[0];enableNativeTrackSupport(track)?setTrackForCustomDisplay(mediaElement,null):(setTrackForCustomDisplay(mediaElement,track),streamIndex=-1,track=null);for(var expectedId="textTrack"+streamIndex,trackIndex=streamIndex!==-1&&track?mediaStreamTextTracks.indexOf(track):-1,modes=["disabled","showing","hidden"],allTracks=mediaElement.textTracks,i=0;i':'",dlg.innerHTML=html;var videoElement=dlg.querySelector("video");videoElement.volume=getSavedVolume(),videoElement.addEventListener("timeupdate",onTimeUpdate),videoElement.addEventListener("ended",onEnded),videoElement.addEventListener("volumechange",onVolumeChange),videoElement.addEventListener("pause",onPause),videoElement.addEventListener("playing",onPlaying),videoElement.addEventListener("click",onClick),videoElement.addEventListener("dblclick",onDblClick),document.body.insertBefore(dlg,document.body.firstChild),videoDialog=dlg,mediaElement=videoElement,options.fullscreen&&browser.supportsCssAnimation()&&!browser.slow?zoomIn(dlg).then(function(){resolve(videoElement)}):resolve(videoElement)})})}var self=this;self.name="Html Video Player",self.type="mediaplayer",self.id="htmlvideoplayer",self.priority=1;var mediaElement,videoDialog,currentSrc,hlsPlayer,currentPlayOptions,subtitleTrackIndexToSetOnPlaying,currentClock,currentAssRenderer,videoSubtitlesElem,currentTrackEvents,started=!1,timeUpdated=!1,lastCustomTrackMs=0,customTrackIndex=-1;self.currentSrc=function(){return currentSrc},self.play=function(options){return browser.msie&&"Transcode"===options.playMethod&&!window.MediaSource?(alert("Playback of this content is not supported in Internet Explorer. For a better experience, try a modern browser such as Microsoft Edge, Google Chrome, Firefox or Opera."),Promise.reject()):(started=!1,timeUpdated=!1,_currentTime=null,createMediaElement(options).then(function(elem){return updateVideoUrl(options,options.mediaSource).then(function(){return setCurrentSrc(elem,options)})}))};var supportedFeatures;self.supports=function(feature){return supportedFeatures||(supportedFeatures=getSupportedFeatures()),supportedFeatures.indexOf(feature)!==-1},self.setPictureInPictureEnabled=function(isEnabled){var video=mediaElement;video&&video.webkitSupportsPresentationMode&&"function"==typeof video.webkitSetPresentationMode&&video.webkitSetPresentationMode(isEnabled?"picture-in-picture":"inline")},self.isPictureInPictureEnabled=function(isEnabled){var video=mediaElement;return!!video&&"picture-in-picture"===video.webkitPresentationMode};var recoverDecodingErrorDate,recoverSwapAudioCodecDate;self.setSubtitleStreamIndex=function(index){setCurrentTrackElement(index)},self.canSetAudioStreamIndex=function(){return!(!browser.edge&&!browser.msie)},self.setAudioStreamIndex=function(index){var i,length,audioStreams=getMediaStreamAudioTracks(currentPlayOptions.mediaSource),audioTrackOffset=-1;for(i=0,length=audioStreams.length;i=100?"none":rawValue/100;elem.style["-webkit-filter"]="brightness("+cssValue+");",elem.style.filter="brightness("+cssValue+")",elem.brightnessValue=val,events.trigger(self,"brightnesschange")}},self.getBrightness=function(){if(mediaElement){var val=mediaElement.brightnessValue;return null==val?100:val}},self.setVolume=function(val){mediaElement&&(mediaElement.volume=val/100)},self.getVolume=function(){if(mediaElement)return 100*mediaElement.volume},self.volumeUp=function(){self.setVolume(Math.min(self.getVolume()+2,100))},self.volumeDown=function(){self.setVolume(Math.max(self.getVolume()-2,0))},self.setMute=function(mute){mediaElement&&(mediaElement.muted=mute)},self.isMuted=function(){return!!mediaElement&&mediaElement.muted}}return HtmlVideoPlayer.prototype.canPlayMediaType=function(mediaType){return"video"===(mediaType||"").toLowerCase()},HtmlVideoPlayer.prototype.supportsPlayMethod=function(playMethod,item){return!appHost.supportsPlayMethod||appHost.supportsPlayMethod(playMethod,item)},HtmlVideoPlayer.prototype.getDeviceProfile=function(item,options){return appHost.getDeviceProfile?appHost.getDeviceProfile(item,options):getDefaultProfile()},HtmlVideoPlayer.prototype.setAspectRatio=function(val){},HtmlVideoPlayer.prototype.getAspectRatio=function(){return this._currentAspectRatio},HtmlVideoPlayer.prototype.getSupportedAspectRatios=function(){return[]},HtmlVideoPlayer.prototype.togglePictureInPicture=function(){return this.setPictureInPictureEnabled(!this.isPictureInPictureEnabled())},HtmlVideoPlayer}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.js b/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.js index c23e381e7f..974f4e7207 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.js +++ b/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.js @@ -1 +1 @@ -define(["itemHelper","dom","layoutManager","dialogHelper","datetime","loading","focusManager","connectionManager","globalize","require","shell","emby-checkbox","emby-input","emby-select","listViewStyle","emby-textarea","emby-button","paper-icon-button-light","css!./../formdialog"],function(itemHelper,dom,layoutManager,dialogHelper,datetime,loading,focusManager,connectionManager,globalize,require,shell){"use strict";function isDialog(){return currentContext.classList.contains("dialog")}function closeDialog(isSubmitted){isDialog()&&dialogHelper.close(currentContext)}function submitUpdatedItem(form,item){function afterContentTypeUpdated(){require(["toast"],function(toast){toast(globalize.translate("sharedcomponents#MessageItemSaved"))}),loading.hide(),closeDialog(!0)}var apiClient=getApiClient();apiClient.updateItem(item).then(function(){var newContentType=form.querySelector("#selectContentType").value||"";(metadataEditorInfo.ContentType||"")!==newContentType?apiClient.ajax({url:apiClient.getUrl("Items/"+item.Id+"/ContentType",{ContentType:newContentType}),type:"POST"}).then(function(){afterContentTypeUpdated()}):afterContentTypeUpdated()})}function getSelectedAirDays(form){var checkedItems=form.querySelectorAll(".chkAirDay:checked")||[];return Array.prototype.map.call(checkedItems,function(c){return c.getAttribute("data-day")})}function getAlbumArtists(form){return form.querySelector("#txtAlbumArtist").value.trim().split(";").filter(function(s){return s.length>0}).map(function(a){return{Name:a}})}function getArtists(form){return form.querySelector("#txtArtist").value.trim().split(";").filter(function(s){return s.length>0}).map(function(a){return{Name:a}})}function getDateFromForm(form,element,property){var val=form.querySelector(element).value;if(!val)return null;if(currentItem[property]){var date=datetime.parseISO8601Date(currentItem[property],!0),parts=date.toISOString().split("T");if(0===parts[0].indexOf(val)){var iso=parts[1];val+="T"+iso}}return val}function onSubmit(e){loading.show();var form=this;try{var item={Id:currentItem.Id,Name:form.querySelector("#txtName").value,OriginalTitle:form.querySelector("#txtOriginalName").value,ForcedSortName:form.querySelector("#txtSortName").value,DisplayMediaType:form.querySelector("#txtDisplayMediaType").value,CommunityRating:form.querySelector("#txtCommunityRating").value,VoteCount:form.querySelector("#txtCommunityVoteCount").value,HomePageUrl:form.querySelector("#txtHomePageUrl").value,CriticRating:form.querySelector("#txtCriticRating").value,IndexNumber:form.querySelector("#txtIndexNumber").value||null,AbsoluteEpisodeNumber:form.querySelector("#txtAbsoluteEpisodeNumber").value,DvdEpisodeNumber:form.querySelector("#txtDvdEpisodeNumber").value,DvdSeasonNumber:form.querySelector("#txtDvdSeasonNumber").value,AirsBeforeSeasonNumber:form.querySelector("#txtAirsBeforeSeason").value,AirsAfterSeasonNumber:form.querySelector("#txtAirsAfterSeason").value,AirsBeforeEpisodeNumber:form.querySelector("#txtAirsBeforeEpisode").value,ParentIndexNumber:form.querySelector("#txtParentIndexNumber").value||null,DisplayOrder:form.querySelector("#selectDisplayOrder").value,Players:form.querySelector("#txtPlayers").value,Album:form.querySelector("#txtAlbum").value,AlbumArtists:getAlbumArtists(form),ArtistItems:getArtists(form),AwardSummary:form.querySelector("#txtAwardSummary").value,Overview:form.querySelector("#txtOverview").value,Status:form.querySelector("#selectStatus").value,AirDays:getSelectedAirDays(form),AirTime:form.querySelector("#txtAirTime").value,Genres:editableListViewValues(form.querySelector("#listGenres")),Tags:editableListViewValues(form.querySelector("#listTags")),Keywords:editableListViewValues(form.querySelector("#listKeywords")),Studios:editableListViewValues(form.querySelector("#listStudios")).map(function(element){return{Name:element}}),PremiereDate:getDateFromForm(form,"#txtPremiereDate","PremiereDate"),DateCreated:getDateFromForm(form,"#txtDateAdded","DateCreated"),EndDate:getDateFromForm(form,"#txtEndDate","EndDate"),ProductionYear:form.querySelector("#txtProductionYear").value,AspectRatio:form.querySelector("#txtOriginalAspectRatio").value,Video3DFormat:form.querySelector("#select3dFormat").value,OfficialRating:form.querySelector("#selectOfficialRating").value,CustomRating:form.querySelector("#selectCustomRating").value,People:currentItem.People,LockData:form.querySelector("#chkLockData").checked,LockedFields:Array.prototype.filter.call(form.querySelectorAll(".selectLockedField"),function(c){return!c.checked}).map(function(c){return c.getAttribute("data-value")})};item.ProviderIds=Object.assign({},currentItem.ProviderIds);var idElements=form.querySelectorAll(".txtExternalId");if(Array.prototype.map.call(idElements,function(idElem){var providerKey=idElem.getAttribute("data-providerkey");item.ProviderIds[providerKey]=idElem.value}),item.PreferredMetadataLanguage=form.querySelector("#selectLanguage").value,item.PreferredMetadataCountryCode=form.querySelector("#selectCountry").value,"Person"===currentItem.Type){var placeOfBirth=form.querySelector("#txtPlaceOfBirth").value;item.ProductionLocations=placeOfBirth?[placeOfBirth]:[]}if("Series"===currentItem.Type){var seriesRuntime=form.querySelector("#txtSeriesRuntime").value;item.RunTimeTicks=seriesRuntime?6e8*seriesRuntime:null}var tagline=form.querySelector("#txtTagline").value;item.Taglines=tagline?[tagline]:[],submitUpdatedItem(form,item)}catch(err){alert(err)}return e.preventDefault(),e.stopPropagation(),!1}function editableListViewValues(list){return Array.prototype.map.call(list.querySelectorAll(".textValue"),function(el){return el.textContent})}function addElementToEditableListview(source,sortCallback){require(["prompt"],function(prompt){prompt({label:"Value:"}).then(function(text){var list=dom.parentWithClass(source,"editableListviewContainer").querySelector(".paperList"),items=editableListViewValues(list);items.push(text),populateListView(list,items,sortCallback)})})}function removeElementFromListview(source){var el=dom.parentWithClass(source,"listItem");el.parentNode.removeChild(el)}function editPerson(context,person,index){require(["personEditor"],function(personEditor){personEditor.show(person).then(function(updatedPerson){var isNew=index===-1;isNew&¤tItem.People.push(updatedPerson),populatePeople(context,currentItem.People)})})}function showMoreMenu(context,button,user){require(["itemContextMenu"],function(itemContextMenu){var item=currentItem;itemContextMenu.show({item:item,positionTo:button,edit:!1,editImages:!0,editSubtitles:!0,sync:!1,share:!1,play:!1,queue:!1,user:user}).then(function(result){result.deleted?afterDeleted(context,item):result.updated&&reload(context,item.Id,item.ServerId)})})}function afterDeleted(context,item){var parentId=item.ParentId||item.SeasonId||item.SeriesId;parentId?reload(context,parentId,item.ServerId):require(["embyRouter"],function(embyRouter){embyRouter.goHome()})}function onWebSocketMessageReceived(e,data){var msg=data;"LibraryChanged"===msg.MessageType&&msg.Data.ItemsUpdated.indexOf(currentItem.Id)!==-1&&(console.log("Item updated - reloading metadata"),reload(currentContext,currentItem.Id,currentItem.ServerId))}function bindItemChanged(context,apiClient){Events.on(apiClient,"websocketmessage",onWebSocketMessageReceived)}function unbindItemChanged(context,apiClient){Events.off(apiClient,"websocketmessage",onWebSocketMessageReceived)}function onEditorClick(e){var btnRemoveFromEditorList=dom.parentWithClass(e.target,"btnRemoveFromEditorList");if(btnRemoveFromEditorList)return void removeElementFromListview(btnRemoveFromEditorList);var btnAddTextItem=dom.parentWithClass(e.target,"btnAddTextItem");btnAddTextItem&&addElementToEditableListview(btnAddTextItem)}function getApiClient(){return connectionManager.getApiClient(currentItem.ServerId)}function init(context,apiClient){context.querySelector(".externalIds").addEventListener("click",function(e){var btnOpenExternalId=dom.parentWithClass(e.target,"btnOpenExternalId");if(btnOpenExternalId){var field=context.querySelector("#"+btnOpenExternalId.getAttribute("data-fieldid")),formatString=field.getAttribute("data-formatstring");field.value&&shell.openUrl(formatString.replace("{0}",field.value))}}),context.querySelector(".btnCancel").addEventListener("click",function(){closeDialog(!1)}),context.querySelector(".btnMore").addEventListener("click",function(e){getApiClient().getCurrentUser().then(function(user){showMoreMenu(context,e.target,user)})}),context.querySelector(".btnHeaderSave").addEventListener("click",function(e){context.querySelector(".btnSave").click()}),context.querySelector("#chkLockData").addEventListener("click",function(e){e.target.checked?hideElement(".providerSettingsContainer"):showElement(".providerSettingsContainer")}),context.removeEventListener("click",onEditorClick),context.addEventListener("click",onEditorClick);var form=context.querySelector("form");form.removeEventListener("submit",onSubmit),form.addEventListener("submit",onSubmit),context.querySelector("#btnAddPerson").addEventListener("click",function(event,data){editPerson(context,{},-1)}),context.querySelector("#peopleList").addEventListener("click",function(e){var index,btnDeletePerson=dom.parentWithClass(e.target,"btnDeletePerson");btnDeletePerson&&(index=parseInt(btnDeletePerson.getAttribute("data-index")),currentItem.People.splice(index,1),populatePeople(context,currentItem.People));var btnEditPerson=dom.parentWithClass(e.target,"btnEditPerson");btnEditPerson&&(index=parseInt(btnEditPerson.getAttribute("data-index")),editPerson(context,currentItem.People[index],index))}),isDialog()&&bindItemChanged(context,apiClient)}function getItem(itemId,serverId){var apiClient=connectionManager.getApiClient(serverId);return itemId?apiClient.getItem(apiClient.getCurrentUserId(),itemId):apiClient.getRootFolder(apiClient.getCurrentUserId())}function getEditorConfig(itemId,serverId){var apiClient=connectionManager.getApiClient(serverId);return itemId?apiClient.getJSON(apiClient.getUrl("Items/"+itemId+"/MetadataEditor")):Promise.resolve({})}function populateCountries(select,allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html}function populateLanguages(select,languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html}function renderContentTypeOptions(context,metadataInfo){metadataInfo.ContentTypeOptions.length?showElement("#fldContentType",context):hideElement("#fldContentType",context);var html=metadataInfo.ContentTypeOptions.map(function(i){return'"}).join(""),selectEl=context.querySelector("#selectContentType");selectEl.innerHTML=html,selectEl.value=metadataInfo.ContentType||""}function loadExternalIds(context,item,externalIds){for(var html="",providerIds=item.ProviderIds||{},i=0,length=externalIds.length;i',html+='
';var value=providerIds[idInfo.Key]||"";html+='
',html+='',html+="
",formatString&&(html+=''),html+="
",html+=""}var elem=context.querySelector(".externalIds",context);elem.innerHTML=html}function hideElement(selector,context,multiple){if(context=context||document,"string"==typeof selector){var elements=multiple?context.querySelectorAll(selector):[context.querySelector(selector)];Array.prototype.forEach.call(elements,function(el){el&&el.classList.add("hide")})}else selector.classList.add("hide")}function showElement(selector,context,multiple){if(context=context||document,"string"==typeof selector){var elements=multiple?context.querySelectorAll(selector):[context.querySelector(selector)];Array.prototype.forEach.call(elements,function(el){el&&el.classList.remove("hide")})}else selector.classList.remove("hide")}function setFieldVisibilities(context,item){item.Path&&"Remote"!==item.LocationType?showElement("#fldPath",context):hideElement("#fldPath",context),"Series"===item.Type||"Movie"===item.Type||"Trailer"===item.Type?showElement("#fldOriginalName",context):hideElement("#fldOriginalName",context),"Series"===item.Type?showElement("#fldSeriesRuntime",context):hideElement("#fldSeriesRuntime",context),"Series"===item.Type||"Person"===item.Type?showElement("#fldEndDate",context):hideElement("#fldEndDate",context),"MusicAlbum"===item.Type?showElement("#albumAssociationMessage",context):hideElement("#albumAssociationMessage",context),"Game"===item.MediaType?showElement("#fldPlayers",context):hideElement("#fldPlayers",context),"Movie"===item.Type||"Trailer"===item.Type?showElement("#fldCriticRating",context):hideElement("#fldCriticRating",context),"Movie"===item.Type?showElement("#fldAwardSummary",context):hideElement("#fldAwardSummary",context),"Series"===item.Type?(showElement("#fldStatus",context),showElement("#fldAirDays",context),showElement("#fldAirTime",context)):(hideElement("#fldStatus",context),hideElement("#fldAirDays",context),hideElement("#fldAirTime",context)),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fld3dFormat",context):hideElement("#fld3dFormat",context),"Audio"===item.Type?showElement("#fldAlbumArtist",context):hideElement("#fldAlbumArtist",context),"Audio"===item.Type||"MusicVideo"===item.Type?(showElement("#fldArtist",context),showElement("#fldAlbum",context)):(hideElement("#fldArtist",context),hideElement("#fldAlbum",context)),"Episode"===item.Type?showElement("#collapsibleDvdEpisodeInfo",context):hideElement("#collapsibleDvdEpisodeInfo",context),"Episode"===item.Type&&0===item.ParentIndexNumber?showElement("#collapsibleSpecialEpisodeInfo",context):hideElement("#collapsibleSpecialEpisodeInfo",context),"Person"===item.Type||"Genre"===item.Type||"Studio"===item.Type||"GameGenre"===item.Type||"MusicGenre"===item.Type||"TvChannel"===item.Type?(hideElement("#fldCommunityRating",context),hideElement("#fldCommunityVoteCount",context),hideElement("#genresCollapsible",context),hideElement("#peopleCollapsible",context),hideElement("#studiosCollapsible",context),"TvChannel"===item.Type?showElement("#fldOfficialRating",context):hideElement("#fldOfficialRating",context),hideElement("#fldCustomRating",context)):(showElement("#fldCommunityRating",context),showElement("#fldCommunityVoteCount",context),showElement("#genresCollapsible",context),showElement("#peopleCollapsible",context),showElement("#studiosCollapsible",context),showElement("#fldOfficialRating",context),showElement("#fldCustomRating",context)),showElement("#tagsCollapsible",context),"TvChannel"===item.Type?(hideElement("#metadataSettingsCollapsible",context),hideElement("#fldPremiereDate",context),hideElement("#fldDateAdded",context),hideElement("#fldYear",context)):(showElement("#metadataSettingsCollapsible",context),showElement("#fldPremiereDate",context),showElement("#fldDateAdded",context),showElement("#fldYear",context)),"Movie"===item.Type||"Trailer"===item.Type||"BoxSet"===item.Type?showElement("#keywordsCollapsible",context):hideElement("#keywordsCollapsible",context),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fldSourceType",context):hideElement("#fldSourceType",context),"Person"===item.Type?(context.querySelector("#txtProductionYear").label(globalize.translate("sharedcomponents#LabelBirthYear")),context.querySelector("#txtPremiereDate").label(globalize.translate("sharedcomponents#LabelBirthDate")),context.querySelector("#txtEndDate").label(globalize.translate("sharedcomponents#LabelDeathDate")),showElement("#fldPlaceOfBirth")):(context.querySelector("#txtProductionYear").label(globalize.translate("sharedcomponents#LabelYear")),context.querySelector("#txtPremiereDate").label(globalize.translate("sharedcomponents#LabelReleaseDate")),context.querySelector("#txtEndDate").label(globalize.translate("sharedcomponents#LabelEndDate")),hideElement("#fldPlaceOfBirth")),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fldOriginalAspectRatio"):hideElement("#fldOriginalAspectRatio"),"Audio"===item.Type||"Episode"===item.Type||"Season"===item.Type?(showElement("#fldIndexNumber"),"Episode"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelEpisodeNumber")):"Season"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelSeasonNumber")):"Audio"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelTrackNumber")):context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelNumber"))):hideElement("#fldIndexNumber"),"Audio"===item.Type||"Episode"===item.Type?(showElement("#fldParentIndexNumber"),"Episode"===item.Type?context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelSeasonNumber")):"Audio"===item.Type?context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelDiscNumber")):context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelParentNumber"))):hideElement("#fldParentIndexNumber",context),"BoxSet"===item.Type?(showElement("#fldDisplayOrder",context),context.querySelector("#selectDisplayOrder").innerHTML='"):(context.querySelector("#selectDisplayOrder").innerHTML="",hideElement("#fldDisplayOrder",context));var displaySettingFields=context.querySelectorAll(".fldDisplaySetting"),hiddenDisplaySettingFields=Array.prototype.filter.call(displaySettingFields,function(field){return"none"!==field.style.display});hiddenDisplaySettingFields.length?showElement("#collapsibleDisplaySettings",context):hideElement("#collapsibleDisplaySettings",context)}function fillItemInfo(context,item,parentalRatingOptions){var select=context.querySelector("#selectOfficialRating");populateRatings(parentalRatingOptions,select,item.OfficialRating),select.value=item.OfficialRating||"",select=context.querySelector("#selectCustomRating"),populateRatings(parentalRatingOptions,select,item.CustomRating),select.value=item.CustomRating||"";var selectStatus=context.querySelector("#selectStatus");populateStatus(selectStatus),selectStatus.value=item.Status||"",context.querySelector("#select3dFormat",context).value=item.Video3DFormat||"",Array.prototype.forEach.call(context.querySelectorAll(".chkAirDay",context),function(el){el.checked=(item.AirDays||[]).indexOf(el.getAttribute("data-day"))!==-1}),populateListView(context.querySelector("#listGenres"),item.Genres),populatePeople(context,item.People||[]),populateListView(context.querySelector("#listStudios"),(item.Studios||[]).map(function(element){return element.Name||""})),populateListView(context.querySelector("#listTags"),item.Tags),populateListView(context.querySelector("#listKeywords"),item.Keywords);var lockData=item.LockData||!1,chkLockData=context.querySelector("#chkLockData");chkLockData.checked=lockData,chkLockData.checked?hideElement(".providerSettingsContainer",context):showElement(".providerSettingsContainer",context),populateInternetProviderSettings(context,item,item.LockedFields),context.querySelector("#txtPath").value=item.Path||"",context.querySelector("#txtName").value=item.Name||"",context.querySelector("#txtOriginalName").value=item.OriginalTitle||"",context.querySelector("#txtOverview").value=item.Overview||"",context.querySelector("#txtTagline").value=item.Taglines&&item.Taglines.length?item.Taglines[0]:"",context.querySelector("#txtSortName").value=item.ForcedSortName||"",context.querySelector("#txtDisplayMediaType").value=item.DisplayMediaType||"",context.querySelector("#txtCommunityRating").value=item.CommunityRating||"",context.querySelector("#txtCommunityVoteCount").value=item.VoteCount||"",context.querySelector("#txtHomePageUrl").value=item.HomePageUrl||"",context.querySelector("#txtAwardSummary").value=item.AwardSummary||"",context.querySelector("#txtCriticRating").value=item.CriticRating||"",context.querySelector("#txtIndexNumber").value="IndexNumber"in item?item.IndexNumber:"",context.querySelector("#txtParentIndexNumber").value="ParentIndexNumber"in item?item.ParentIndexNumber:"",context.querySelector("#txtPlayers").value=item.Players||"",context.querySelector("#txtAbsoluteEpisodeNumber").value="AbsoluteEpisodeNumber"in item?item.AbsoluteEpisodeNumber:"",context.querySelector("#txtDvdEpisodeNumber").value="DvdEpisodeNumber"in item?item.DvdEpisodeNumber:"",context.querySelector("#txtDvdSeasonNumber").value="DvdSeasonNumber"in item?item.DvdSeasonNumber:"",context.querySelector("#txtAirsBeforeSeason").value="AirsBeforeSeasonNumber"in item?item.AirsBeforeSeasonNumber:"",context.querySelector("#txtAirsAfterSeason").value="AirsAfterSeasonNumber"in item?item.AirsAfterSeasonNumber:"",context.querySelector("#txtAirsBeforeEpisode").value="AirsBeforeEpisodeNumber"in item?item.AirsBeforeEpisodeNumber:"",context.querySelector("#txtAlbum").value=item.Album||"",context.querySelector("#txtAlbumArtist").value=(item.AlbumArtists||[]).map(function(a){return a.Name}).join(";"),context.querySelector("#selectDisplayOrder").value=item.DisplayOrder,context.querySelector("#txtArtist").value=(item.ArtistItems||[]).map(function(a){return a.Name}).join(";");var date;if(item.DateCreated)try{date=datetime.parseISO8601Date(item.DateCreated,!0),context.querySelector("#txtDateAdded").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtDateAdded").value=""}else context.querySelector("#txtDateAdded").value="";if(item.PremiereDate)try{date=datetime.parseISO8601Date(item.PremiereDate,!0),context.querySelector("#txtPremiereDate").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtPremiereDate").value=""}else context.querySelector("#txtPremiereDate").value="";if(item.EndDate)try{date=datetime.parseISO8601Date(item.EndDate,!0),context.querySelector("#txtEndDate").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtEndDate").value=""}else context.querySelector("#txtEndDate").value="";context.querySelector("#txtProductionYear").value=item.ProductionYear||"",context.querySelector("#txtAirTime").value=item.AirTime||"";var placeofBirth=item.ProductionLocations&&item.ProductionLocations.length?item.ProductionLocations[0]:"";if(context.querySelector("#txtPlaceOfBirth").value=placeofBirth,context.querySelector("#txtOriginalAspectRatio").value=item.AspectRatio||"",context.querySelector("#selectLanguage").value=item.PreferredMetadataLanguage||"",context.querySelector("#selectCountry").value=item.PreferredMetadataCountryCode||"",item.RunTimeTicks){var minutes=item.RunTimeTicks/6e8;context.querySelector("#txtSeriesRuntime").value=Math.round(minutes)}else context.querySelector("#txtSeriesRuntime",context).value=""}function populateRatings(allParentalRatings,select,currentValue){var html="";html+="";var i,length,rating,ratings=[],currentValueFound=!1;for(i=0,length=allParentalRatings.length;i"+rating.Name+"";select.innerHTML=html}function populateStatus(select){var html="";html+="",html+="",html+="",select.innerHTML=html}function populateListView(list,items,sortCallback){items=items||[],"undefined"==typeof sortCallback?items.sort(function(a,b){return a.toLowerCase().localeCompare(b.toLowerCase())}):items=sortCallback(items);for(var html="",i=0;i',html+='live_tv',html+='
',html+='
',html+=items[i],html+="
",html+="
",html+='',html+="";list.innerHTML=html}function populatePeople(context,people){for(var lastType="",html="",elem=context.querySelector("#peopleList"),i=0,length=people.length;i',html+='person',html+='",html+='',html+=""}elem.innerHTML=html}function generateSliders(fields,currentFields){for(var html="",i=0;i",html+=""+name+"",html+=""}return html}function populateInternetProviderSettings(context,item,lockedFields){var container=context.querySelector(".providerSettingsContainer");lockedFields=lockedFields||[];var metadatafields=[{name:globalize.translate("sharedcomponents#Name"),value:"Name"},{name:globalize.translate("sharedcomponents#Overview"),value:"Overview"},{name:globalize.translate("sharedcomponents#Genres"),value:"Genres"},{name:globalize.translate("sharedcomponents#ParentalRating"),value:"OfficialRating"},{name:globalize.translate("sharedcomponents#People"),value:"Cast"}];"Person"===item.Type?metadatafields.push({name:globalize.translate("sharedcomponents#BirthLocation"),value:"ProductionLocations"}):metadatafields.push({name:globalize.translate("sharedcomponents#ProductionLocations"),value:"ProductionLocations"}),"Series"===item.Type&&metadatafields.push({name:globalize.translate("Runtime"),value:"Runtime"}),metadatafields.push({name:globalize.translate("sharedcomponents#Studios"),value:"Studios"}),metadatafields.push({name:globalize.translate("sharedcomponents#Tags"),value:"Tags"}),metadatafields.push({name:globalize.translate("sharedcomponents#Keywords"),value:"Keywords"}),metadatafields.push({name:globalize.translate("sharedcomponents#Images"),value:"Images"}),metadatafields.push({name:globalize.translate("sharedcomponents#Backdrops"),value:"Backdrops"}),"Game"===item.Type&&metadatafields.push({name:globalize.translate("sharedcomponents#Screenshots"),value:"Screenshots"});var html="";html+="

"+globalize.translate("sharedcomponents#HeaderEnabledFields")+"

",html+="

"+globalize.translate("sharedcomponents#HeaderEnabledFieldsHelp")+"

",html+=generateSliders(metadatafields,lockedFields),container.innerHTML=html}function reload(context,itemId,serverId){loading.show(),Promise.all([getItem(itemId,serverId),getEditorConfig(itemId,serverId)]).then(function(responses){var item=responses[0];metadataEditorInfo=responses[1],currentItem=item;var languages=metadataEditorInfo.Cultures,countries=metadataEditorInfo.Countries;renderContentTypeOptions(context,metadataEditorInfo),loadExternalIds(context,item,metadataEditorInfo.ExternalIdInfos),populateLanguages(context.querySelector("#selectLanguage"),languages),populateCountries(context.querySelector("#selectCountry"),countries),setFieldVisibilities(context,item),fillItemInfo(context,item,metadataEditorInfo.ParentalRatingOptions),"Video"===item.MediaType&&"Episode"!==item.Type?showElement("#fldTagline",context):hideElement("#fldTagline",context),loading.hide()})}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function show(itemId,serverId,resolve,reject){loading.show(),require(["text!./metadataeditor.template.html"],function(template){var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="medium-tall";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="";html+=globalize.translateDocument(template,"sharedcomponents"),dlg.innerHTML=html,layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg),dlg.addEventListener("close",function(){layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),unbindItemChanged(dlg,connectionManager.getApiClient(serverId)),resolve()}),currentContext=dlg,init(dlg,connectionManager.getApiClient(serverId)),reload(dlg,itemId,serverId)})}var currentContext,metadataEditorInfo,currentItem;return{show:function(itemId,serverId){return new Promise(function(resolve,reject){return show(itemId,serverId,resolve,reject)})},embed:function(elem,itemId,serverId){return new Promise(function(resolve,reject){loading.show(),require(["text!./metadataeditor.template.html"],function(template){elem.innerHTML=globalize.translateDocument(template,"sharedcomponents"),elem.querySelector(".formDialogFooter").classList.remove("formDialogFooter"),elem.querySelector(".btnHeaderSave").classList.remove("hide"),elem.querySelector(".btnCancel").classList.add("hide"),currentContext=elem,init(elem,connectionManager.getApiClient(serverId)),reload(elem,itemId,serverId),focusManager.autoFocus(elem)})})}}}); \ No newline at end of file +define(["itemHelper","dom","layoutManager","dialogHelper","datetime","loading","focusManager","connectionManager","globalize","require","shell","emby-checkbox","emby-input","emby-select","listViewStyle","emby-textarea","emby-button","paper-icon-button-light","css!./../formdialog"],function(itemHelper,dom,layoutManager,dialogHelper,datetime,loading,focusManager,connectionManager,globalize,require,shell){"use strict";function isDialog(){return currentContext.classList.contains("dialog")}function closeDialog(isSubmitted){isDialog()&&dialogHelper.close(currentContext)}function submitUpdatedItem(form,item){function afterContentTypeUpdated(){require(["toast"],function(toast){toast(globalize.translate("sharedcomponents#MessageItemSaved"))}),loading.hide(),closeDialog(!0)}var apiClient=getApiClient();apiClient.updateItem(item).then(function(){var newContentType=form.querySelector("#selectContentType").value||"";(metadataEditorInfo.ContentType||"")!==newContentType?apiClient.ajax({url:apiClient.getUrl("Items/"+item.Id+"/ContentType",{ContentType:newContentType}),type:"POST"}).then(function(){afterContentTypeUpdated()}):afterContentTypeUpdated()})}function getSelectedAirDays(form){var checkedItems=form.querySelectorAll(".chkAirDay:checked")||[];return Array.prototype.map.call(checkedItems,function(c){return c.getAttribute("data-day")})}function getAlbumArtists(form){return form.querySelector("#txtAlbumArtist").value.trim().split(";").filter(function(s){return s.length>0}).map(function(a){return{Name:a}})}function getArtists(form){return form.querySelector("#txtArtist").value.trim().split(";").filter(function(s){return s.length>0}).map(function(a){return{Name:a}})}function getDateFromForm(form,element,property){var val=form.querySelector(element).value;if(!val)return null;if(currentItem[property]){var date=datetime.parseISO8601Date(currentItem[property],!0),parts=date.toISOString().split("T");if(0===parts[0].indexOf(val)){var iso=parts[1];val+="T"+iso}}return val}function onSubmit(e){loading.show();var form=this;try{var item={Id:currentItem.Id,Name:form.querySelector("#txtName").value,OriginalTitle:form.querySelector("#txtOriginalName").value,ForcedSortName:form.querySelector("#txtSortName").value,DisplayMediaType:form.querySelector("#txtDisplayMediaType").value,CommunityRating:form.querySelector("#txtCommunityRating").value,VoteCount:form.querySelector("#txtCommunityVoteCount").value,HomePageUrl:form.querySelector("#txtHomePageUrl").value,CriticRating:form.querySelector("#txtCriticRating").value,IndexNumber:form.querySelector("#txtIndexNumber").value||null,AbsoluteEpisodeNumber:form.querySelector("#txtAbsoluteEpisodeNumber").value,DvdEpisodeNumber:form.querySelector("#txtDvdEpisodeNumber").value,DvdSeasonNumber:form.querySelector("#txtDvdSeasonNumber").value,AirsBeforeSeasonNumber:form.querySelector("#txtAirsBeforeSeason").value,AirsAfterSeasonNumber:form.querySelector("#txtAirsAfterSeason").value,AirsBeforeEpisodeNumber:form.querySelector("#txtAirsBeforeEpisode").value,ParentIndexNumber:form.querySelector("#txtParentIndexNumber").value||null,DisplayOrder:form.querySelector("#selectDisplayOrder").value,Players:form.querySelector("#txtPlayers").value,Album:form.querySelector("#txtAlbum").value,AlbumArtists:getAlbumArtists(form),ArtistItems:getArtists(form),Overview:form.querySelector("#txtOverview").value,Status:form.querySelector("#selectStatus").value,AirDays:getSelectedAirDays(form),AirTime:form.querySelector("#txtAirTime").value,Genres:editableListViewValues(form.querySelector("#listGenres")),Tags:editableListViewValues(form.querySelector("#listTags")),Keywords:editableListViewValues(form.querySelector("#listKeywords")),Studios:editableListViewValues(form.querySelector("#listStudios")).map(function(element){return{Name:element}}),PremiereDate:getDateFromForm(form,"#txtPremiereDate","PremiereDate"),DateCreated:getDateFromForm(form,"#txtDateAdded","DateCreated"),EndDate:getDateFromForm(form,"#txtEndDate","EndDate"),ProductionYear:form.querySelector("#txtProductionYear").value,AspectRatio:form.querySelector("#txtOriginalAspectRatio").value,Video3DFormat:form.querySelector("#select3dFormat").value,OfficialRating:form.querySelector("#selectOfficialRating").value,CustomRating:form.querySelector("#selectCustomRating").value,People:currentItem.People,LockData:form.querySelector("#chkLockData").checked,LockedFields:Array.prototype.filter.call(form.querySelectorAll(".selectLockedField"),function(c){return!c.checked}).map(function(c){return c.getAttribute("data-value")})};item.ProviderIds=Object.assign({},currentItem.ProviderIds);var idElements=form.querySelectorAll(".txtExternalId");if(Array.prototype.map.call(idElements,function(idElem){var providerKey=idElem.getAttribute("data-providerkey");item.ProviderIds[providerKey]=idElem.value}),item.PreferredMetadataLanguage=form.querySelector("#selectLanguage").value,item.PreferredMetadataCountryCode=form.querySelector("#selectCountry").value,"Person"===currentItem.Type){var placeOfBirth=form.querySelector("#txtPlaceOfBirth").value;item.ProductionLocations=placeOfBirth?[placeOfBirth]:[]}if("Series"===currentItem.Type){var seriesRuntime=form.querySelector("#txtSeriesRuntime").value;item.RunTimeTicks=seriesRuntime?6e8*seriesRuntime:null}var tagline=form.querySelector("#txtTagline").value;item.Taglines=tagline?[tagline]:[],submitUpdatedItem(form,item)}catch(err){alert(err)}return e.preventDefault(),e.stopPropagation(),!1}function editableListViewValues(list){return Array.prototype.map.call(list.querySelectorAll(".textValue"),function(el){return el.textContent})}function addElementToEditableListview(source,sortCallback){require(["prompt"],function(prompt){prompt({label:"Value:"}).then(function(text){var list=dom.parentWithClass(source,"editableListviewContainer").querySelector(".paperList"),items=editableListViewValues(list);items.push(text),populateListView(list,items,sortCallback)})})}function removeElementFromListview(source){var el=dom.parentWithClass(source,"listItem");el.parentNode.removeChild(el)}function editPerson(context,person,index){require(["personEditor"],function(personEditor){personEditor.show(person).then(function(updatedPerson){var isNew=index===-1;isNew&¤tItem.People.push(updatedPerson),populatePeople(context,currentItem.People)})})}function showMoreMenu(context,button,user){require(["itemContextMenu"],function(itemContextMenu){var item=currentItem;itemContextMenu.show({item:item,positionTo:button,edit:!1,editImages:!0,editSubtitles:!0,sync:!1,share:!1,play:!1,queue:!1,user:user}).then(function(result){result.deleted?afterDeleted(context,item):result.updated&&reload(context,item.Id,item.ServerId)})})}function afterDeleted(context,item){var parentId=item.ParentId||item.SeasonId||item.SeriesId;parentId?reload(context,parentId,item.ServerId):require(["embyRouter"],function(embyRouter){embyRouter.goHome()})}function onWebSocketMessageReceived(e,data){var msg=data;"LibraryChanged"===msg.MessageType&&msg.Data.ItemsUpdated.indexOf(currentItem.Id)!==-1&&(console.log("Item updated - reloading metadata"),reload(currentContext,currentItem.Id,currentItem.ServerId))}function bindItemChanged(context,apiClient){Events.on(apiClient,"websocketmessage",onWebSocketMessageReceived)}function unbindItemChanged(context,apiClient){Events.off(apiClient,"websocketmessage",onWebSocketMessageReceived)}function onEditorClick(e){var btnRemoveFromEditorList=dom.parentWithClass(e.target,"btnRemoveFromEditorList");if(btnRemoveFromEditorList)return void removeElementFromListview(btnRemoveFromEditorList);var btnAddTextItem=dom.parentWithClass(e.target,"btnAddTextItem");btnAddTextItem&&addElementToEditableListview(btnAddTextItem)}function getApiClient(){return connectionManager.getApiClient(currentItem.ServerId)}function init(context,apiClient){context.querySelector(".externalIds").addEventListener("click",function(e){var btnOpenExternalId=dom.parentWithClass(e.target,"btnOpenExternalId");if(btnOpenExternalId){var field=context.querySelector("#"+btnOpenExternalId.getAttribute("data-fieldid")),formatString=field.getAttribute("data-formatstring");field.value&&shell.openUrl(formatString.replace("{0}",field.value))}}),context.querySelector(".btnCancel").addEventListener("click",function(){closeDialog(!1)}),context.querySelector(".btnMore").addEventListener("click",function(e){getApiClient().getCurrentUser().then(function(user){showMoreMenu(context,e.target,user)})}),context.querySelector(".btnHeaderSave").addEventListener("click",function(e){context.querySelector(".btnSave").click()}),context.querySelector("#chkLockData").addEventListener("click",function(e){e.target.checked?hideElement(".providerSettingsContainer"):showElement(".providerSettingsContainer")}),context.removeEventListener("click",onEditorClick),context.addEventListener("click",onEditorClick);var form=context.querySelector("form");form.removeEventListener("submit",onSubmit),form.addEventListener("submit",onSubmit),context.querySelector("#btnAddPerson").addEventListener("click",function(event,data){editPerson(context,{},-1)}),context.querySelector("#peopleList").addEventListener("click",function(e){var index,btnDeletePerson=dom.parentWithClass(e.target,"btnDeletePerson");btnDeletePerson&&(index=parseInt(btnDeletePerson.getAttribute("data-index")),currentItem.People.splice(index,1),populatePeople(context,currentItem.People));var btnEditPerson=dom.parentWithClass(e.target,"btnEditPerson");btnEditPerson&&(index=parseInt(btnEditPerson.getAttribute("data-index")),editPerson(context,currentItem.People[index],index))}),isDialog()&&bindItemChanged(context,apiClient)}function getItem(itemId,serverId){var apiClient=connectionManager.getApiClient(serverId);return itemId?apiClient.getItem(apiClient.getCurrentUserId(),itemId):apiClient.getRootFolder(apiClient.getCurrentUserId())}function getEditorConfig(itemId,serverId){var apiClient=connectionManager.getApiClient(serverId);return itemId?apiClient.getJSON(apiClient.getUrl("Items/"+itemId+"/MetadataEditor")):Promise.resolve({})}function populateCountries(select,allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html}function populateLanguages(select,languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html}function renderContentTypeOptions(context,metadataInfo){metadataInfo.ContentTypeOptions.length?showElement("#fldContentType",context):hideElement("#fldContentType",context);var html=metadataInfo.ContentTypeOptions.map(function(i){return'"}).join(""),selectEl=context.querySelector("#selectContentType");selectEl.innerHTML=html,selectEl.value=metadataInfo.ContentType||""}function loadExternalIds(context,item,externalIds){for(var html="",providerIds=item.ProviderIds||{},i=0,length=externalIds.length;i',html+='
';var value=providerIds[idInfo.Key]||"";html+='
',html+='',html+="
",formatString&&(html+=''),html+="
",html+=""}var elem=context.querySelector(".externalIds",context);elem.innerHTML=html}function hideElement(selector,context,multiple){if(context=context||document,"string"==typeof selector){var elements=multiple?context.querySelectorAll(selector):[context.querySelector(selector)];Array.prototype.forEach.call(elements,function(el){el&&el.classList.add("hide")})}else selector.classList.add("hide")}function showElement(selector,context,multiple){if(context=context||document,"string"==typeof selector){var elements=multiple?context.querySelectorAll(selector):[context.querySelector(selector)];Array.prototype.forEach.call(elements,function(el){el&&el.classList.remove("hide")})}else selector.classList.remove("hide")}function setFieldVisibilities(context,item){item.Path&&"Remote"!==item.LocationType?showElement("#fldPath",context):hideElement("#fldPath",context),"Series"===item.Type||"Movie"===item.Type||"Trailer"===item.Type?showElement("#fldOriginalName",context):hideElement("#fldOriginalName",context),"Series"===item.Type?showElement("#fldSeriesRuntime",context):hideElement("#fldSeriesRuntime",context),"Series"===item.Type||"Person"===item.Type?showElement("#fldEndDate",context):hideElement("#fldEndDate",context),"MusicAlbum"===item.Type?showElement("#albumAssociationMessage",context):hideElement("#albumAssociationMessage",context),"Game"===item.MediaType?showElement("#fldPlayers",context):hideElement("#fldPlayers",context),"Movie"===item.Type||"Trailer"===item.Type?showElement("#fldCriticRating",context):hideElement("#fldCriticRating",context),"Series"===item.Type?(showElement("#fldStatus",context),showElement("#fldAirDays",context),showElement("#fldAirTime",context)):(hideElement("#fldStatus",context),hideElement("#fldAirDays",context),hideElement("#fldAirTime",context)),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fld3dFormat",context):hideElement("#fld3dFormat",context),"Audio"===item.Type?showElement("#fldAlbumArtist",context):hideElement("#fldAlbumArtist",context),"Audio"===item.Type||"MusicVideo"===item.Type?(showElement("#fldArtist",context),showElement("#fldAlbum",context)):(hideElement("#fldArtist",context),hideElement("#fldAlbum",context)),"Episode"===item.Type?showElement("#collapsibleDvdEpisodeInfo",context):hideElement("#collapsibleDvdEpisodeInfo",context),"Episode"===item.Type&&0===item.ParentIndexNumber?showElement("#collapsibleSpecialEpisodeInfo",context):hideElement("#collapsibleSpecialEpisodeInfo",context),"Person"===item.Type||"Genre"===item.Type||"Studio"===item.Type||"GameGenre"===item.Type||"MusicGenre"===item.Type||"TvChannel"===item.Type?(hideElement("#fldCommunityRating",context),hideElement("#fldCommunityVoteCount",context),hideElement("#genresCollapsible",context),hideElement("#peopleCollapsible",context),hideElement("#studiosCollapsible",context),"TvChannel"===item.Type?showElement("#fldOfficialRating",context):hideElement("#fldOfficialRating",context),hideElement("#fldCustomRating",context)):(showElement("#fldCommunityRating",context),showElement("#fldCommunityVoteCount",context),showElement("#genresCollapsible",context),showElement("#peopleCollapsible",context),showElement("#studiosCollapsible",context),showElement("#fldOfficialRating",context),showElement("#fldCustomRating",context)),showElement("#tagsCollapsible",context),"TvChannel"===item.Type?(hideElement("#metadataSettingsCollapsible",context),hideElement("#fldPremiereDate",context),hideElement("#fldDateAdded",context),hideElement("#fldYear",context)):(showElement("#metadataSettingsCollapsible",context),showElement("#fldPremiereDate",context),showElement("#fldDateAdded",context),showElement("#fldYear",context)),"Movie"===item.Type||"Trailer"===item.Type||"BoxSet"===item.Type?showElement("#keywordsCollapsible",context):hideElement("#keywordsCollapsible",context),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fldSourceType",context):hideElement("#fldSourceType",context),"Person"===item.Type?(context.querySelector("#txtProductionYear").label(globalize.translate("sharedcomponents#LabelBirthYear")),context.querySelector("#txtPremiereDate").label(globalize.translate("sharedcomponents#LabelBirthDate")),context.querySelector("#txtEndDate").label(globalize.translate("sharedcomponents#LabelDeathDate")),showElement("#fldPlaceOfBirth")):(context.querySelector("#txtProductionYear").label(globalize.translate("sharedcomponents#LabelYear")),context.querySelector("#txtPremiereDate").label(globalize.translate("sharedcomponents#LabelReleaseDate")),context.querySelector("#txtEndDate").label(globalize.translate("sharedcomponents#LabelEndDate")),hideElement("#fldPlaceOfBirth")),"Video"===item.MediaType&&"TvChannel"!==item.Type?showElement("#fldOriginalAspectRatio"):hideElement("#fldOriginalAspectRatio"),"Audio"===item.Type||"Episode"===item.Type||"Season"===item.Type?(showElement("#fldIndexNumber"),"Episode"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelEpisodeNumber")):"Season"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelSeasonNumber")):"Audio"===item.Type?context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelTrackNumber")):context.querySelector("#txtIndexNumber").label(globalize.translate("sharedcomponents#LabelNumber"))):hideElement("#fldIndexNumber"),"Audio"===item.Type||"Episode"===item.Type?(showElement("#fldParentIndexNumber"),"Episode"===item.Type?context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelSeasonNumber")):"Audio"===item.Type?context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelDiscNumber")):context.querySelector("#txtParentIndexNumber").label(globalize.translate("sharedcomponents#LabelParentNumber"))):hideElement("#fldParentIndexNumber",context),"BoxSet"===item.Type?(showElement("#fldDisplayOrder",context),context.querySelector("#selectDisplayOrder").innerHTML='"):(context.querySelector("#selectDisplayOrder").innerHTML="",hideElement("#fldDisplayOrder",context));var displaySettingFields=context.querySelectorAll(".fldDisplaySetting"),hiddenDisplaySettingFields=Array.prototype.filter.call(displaySettingFields,function(field){return"none"!==field.style.display});hiddenDisplaySettingFields.length?showElement("#collapsibleDisplaySettings",context):hideElement("#collapsibleDisplaySettings",context)}function fillItemInfo(context,item,parentalRatingOptions){var select=context.querySelector("#selectOfficialRating");populateRatings(parentalRatingOptions,select,item.OfficialRating),select.value=item.OfficialRating||"",select=context.querySelector("#selectCustomRating"),populateRatings(parentalRatingOptions,select,item.CustomRating),select.value=item.CustomRating||"";var selectStatus=context.querySelector("#selectStatus");populateStatus(selectStatus),selectStatus.value=item.Status||"",context.querySelector("#select3dFormat",context).value=item.Video3DFormat||"",Array.prototype.forEach.call(context.querySelectorAll(".chkAirDay",context),function(el){el.checked=(item.AirDays||[]).indexOf(el.getAttribute("data-day"))!==-1}),populateListView(context.querySelector("#listGenres"),item.Genres),populatePeople(context,item.People||[]),populateListView(context.querySelector("#listStudios"),(item.Studios||[]).map(function(element){return element.Name||""})),populateListView(context.querySelector("#listTags"),item.Tags),populateListView(context.querySelector("#listKeywords"),item.Keywords);var lockData=item.LockData||!1,chkLockData=context.querySelector("#chkLockData");chkLockData.checked=lockData,chkLockData.checked?hideElement(".providerSettingsContainer",context):showElement(".providerSettingsContainer",context),populateInternetProviderSettings(context,item,item.LockedFields),context.querySelector("#txtPath").value=item.Path||"",context.querySelector("#txtName").value=item.Name||"",context.querySelector("#txtOriginalName").value=item.OriginalTitle||"",context.querySelector("#txtOverview").value=item.Overview||"",context.querySelector("#txtTagline").value=item.Taglines&&item.Taglines.length?item.Taglines[0]:"",context.querySelector("#txtSortName").value=item.ForcedSortName||"",context.querySelector("#txtDisplayMediaType").value=item.DisplayMediaType||"",context.querySelector("#txtCommunityRating").value=item.CommunityRating||"",context.querySelector("#txtCommunityVoteCount").value=item.VoteCount||"",context.querySelector("#txtHomePageUrl").value=item.HomePageUrl||"",context.querySelector("#txtCriticRating").value=item.CriticRating||"",context.querySelector("#txtIndexNumber").value="IndexNumber"in item?item.IndexNumber:"",context.querySelector("#txtParentIndexNumber").value="ParentIndexNumber"in item?item.ParentIndexNumber:"",context.querySelector("#txtPlayers").value=item.Players||"",context.querySelector("#txtAbsoluteEpisodeNumber").value="AbsoluteEpisodeNumber"in item?item.AbsoluteEpisodeNumber:"",context.querySelector("#txtDvdEpisodeNumber").value="DvdEpisodeNumber"in item?item.DvdEpisodeNumber:"",context.querySelector("#txtDvdSeasonNumber").value="DvdSeasonNumber"in item?item.DvdSeasonNumber:"",context.querySelector("#txtAirsBeforeSeason").value="AirsBeforeSeasonNumber"in item?item.AirsBeforeSeasonNumber:"",context.querySelector("#txtAirsAfterSeason").value="AirsAfterSeasonNumber"in item?item.AirsAfterSeasonNumber:"",context.querySelector("#txtAirsBeforeEpisode").value="AirsBeforeEpisodeNumber"in item?item.AirsBeforeEpisodeNumber:"",context.querySelector("#txtAlbum").value=item.Album||"",context.querySelector("#txtAlbumArtist").value=(item.AlbumArtists||[]).map(function(a){return a.Name}).join(";"),context.querySelector("#selectDisplayOrder").value=item.DisplayOrder,context.querySelector("#txtArtist").value=(item.ArtistItems||[]).map(function(a){return a.Name}).join(";");var date;if(item.DateCreated)try{date=datetime.parseISO8601Date(item.DateCreated,!0),context.querySelector("#txtDateAdded").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtDateAdded").value=""}else context.querySelector("#txtDateAdded").value="";if(item.PremiereDate)try{date=datetime.parseISO8601Date(item.PremiereDate,!0),context.querySelector("#txtPremiereDate").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtPremiereDate").value=""}else context.querySelector("#txtPremiereDate").value="";if(item.EndDate)try{date=datetime.parseISO8601Date(item.EndDate,!0),context.querySelector("#txtEndDate").value=date.toISOString().slice(0,10)}catch(e){context.querySelector("#txtEndDate").value=""}else context.querySelector("#txtEndDate").value="";context.querySelector("#txtProductionYear").value=item.ProductionYear||"",context.querySelector("#txtAirTime").value=item.AirTime||"";var placeofBirth=item.ProductionLocations&&item.ProductionLocations.length?item.ProductionLocations[0]:"";if(context.querySelector("#txtPlaceOfBirth").value=placeofBirth,context.querySelector("#txtOriginalAspectRatio").value=item.AspectRatio||"",context.querySelector("#selectLanguage").value=item.PreferredMetadataLanguage||"",context.querySelector("#selectCountry").value=item.PreferredMetadataCountryCode||"",item.RunTimeTicks){var minutes=item.RunTimeTicks/6e8;context.querySelector("#txtSeriesRuntime").value=Math.round(minutes)}else context.querySelector("#txtSeriesRuntime",context).value=""}function populateRatings(allParentalRatings,select,currentValue){var html="";html+="";var i,length,rating,ratings=[],currentValueFound=!1;for(i=0,length=allParentalRatings.length;i"+rating.Name+"";select.innerHTML=html}function populateStatus(select){var html="";html+="",html+="",html+="",select.innerHTML=html}function populateListView(list,items,sortCallback){items=items||[],"undefined"==typeof sortCallback?items.sort(function(a,b){return a.toLowerCase().localeCompare(b.toLowerCase())}):items=sortCallback(items);for(var html="",i=0;i',html+='live_tv',html+='
',html+='
',html+=items[i],html+="
",html+="
",html+='',html+="";list.innerHTML=html}function populatePeople(context,people){for(var lastType="",html="",elem=context.querySelector("#peopleList"),i=0,length=people.length;i',html+='person',html+='",html+='',html+=""}elem.innerHTML=html}function generateSliders(fields,currentFields){for(var html="",i=0;i",html+=""+name+"",html+=""}return html}function populateInternetProviderSettings(context,item,lockedFields){var container=context.querySelector(".providerSettingsContainer");lockedFields=lockedFields||[];var metadatafields=[{name:globalize.translate("sharedcomponents#Name"),value:"Name"},{name:globalize.translate("sharedcomponents#Overview"),value:"Overview"},{name:globalize.translate("sharedcomponents#Genres"),value:"Genres"},{name:globalize.translate("sharedcomponents#ParentalRating"),value:"OfficialRating"},{name:globalize.translate("sharedcomponents#People"),value:"Cast"}];"Person"===item.Type?metadatafields.push({name:globalize.translate("sharedcomponents#BirthLocation"),value:"ProductionLocations"}):metadatafields.push({name:globalize.translate("sharedcomponents#ProductionLocations"),value:"ProductionLocations"}),"Series"===item.Type&&metadatafields.push({name:globalize.translate("Runtime"),value:"Runtime"}),metadatafields.push({name:globalize.translate("sharedcomponents#Studios"),value:"Studios"}),metadatafields.push({name:globalize.translate("sharedcomponents#Tags"),value:"Tags"}),metadatafields.push({name:globalize.translate("sharedcomponents#Keywords"),value:"Keywords"}),metadatafields.push({name:globalize.translate("sharedcomponents#Images"),value:"Images"}),metadatafields.push({name:globalize.translate("sharedcomponents#Backdrops"),value:"Backdrops"}),"Game"===item.Type&&metadatafields.push({name:globalize.translate("sharedcomponents#Screenshots"),value:"Screenshots"});var html="";html+="

"+globalize.translate("sharedcomponents#HeaderEnabledFields")+"

",html+="

"+globalize.translate("sharedcomponents#HeaderEnabledFieldsHelp")+"

",html+=generateSliders(metadatafields,lockedFields),container.innerHTML=html}function reload(context,itemId,serverId){loading.show(),Promise.all([getItem(itemId,serverId),getEditorConfig(itemId,serverId)]).then(function(responses){var item=responses[0];metadataEditorInfo=responses[1],currentItem=item;var languages=metadataEditorInfo.Cultures,countries=metadataEditorInfo.Countries;renderContentTypeOptions(context,metadataEditorInfo),loadExternalIds(context,item,metadataEditorInfo.ExternalIdInfos),populateLanguages(context.querySelector("#selectLanguage"),languages),populateCountries(context.querySelector("#selectCountry"),countries),setFieldVisibilities(context,item),fillItemInfo(context,item,metadataEditorInfo.ParentalRatingOptions),"Video"===item.MediaType&&"Episode"!==item.Type?showElement("#fldTagline",context):hideElement("#fldTagline",context),loading.hide()})}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function show(itemId,serverId,resolve,reject){loading.show(),require(["text!./metadataeditor.template.html"],function(template){var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="medium-tall";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="";html+=globalize.translateDocument(template,"sharedcomponents"),dlg.innerHTML=html,layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg),dlg.addEventListener("close",function(){layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),unbindItemChanged(dlg,connectionManager.getApiClient(serverId)),resolve()}),currentContext=dlg,init(dlg,connectionManager.getApiClient(serverId)),reload(dlg,itemId,serverId)})}var currentContext,metadataEditorInfo,currentItem;return{show:function(itemId,serverId){return new Promise(function(resolve,reject){return show(itemId,serverId,resolve,reject)})},embed:function(elem,itemId,serverId){return new Promise(function(resolve,reject){loading.show(),require(["text!./metadataeditor.template.html"],function(template){elem.innerHTML=globalize.translateDocument(template,"sharedcomponents"),elem.querySelector(".formDialogFooter").classList.remove("formDialogFooter"),elem.querySelector(".btnHeaderSave").classList.remove("hide"),elem.querySelector(".btnCancel").classList.add("hide"),currentContext=elem,init(elem,connectionManager.getApiClient(serverId)),reload(elem,itemId,serverId),focusManager.autoFocus(elem)})})}}}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.template.html b/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.template.html index fe0982276e..4e480c6d70 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.template.html +++ b/dashboard-ui/bower_components/emby-webcomponents/metadataeditor/metadataeditor.template.html @@ -68,9 +68,6 @@
-
- -
diff --git a/dashboard-ui/bower_components/emby-webcomponents/notifications/notifications.js b/dashboard-ui/bower_components/emby-webcomponents/notifications/notifications.js index 69b4d89e65..dde6431219 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/notifications/notifications.js +++ b/dashboard-ui/bower_components/emby-webcomponents/notifications/notifications.js @@ -1 +1 @@ -define(["serverNotifications","playbackManager","events","globalize","require"],function(serverNotifications,playbackManager,events,globalize,require){"use strict";function onOneDocumentClick(){document.removeEventListener("click",onOneDocumentClick),document.removeEventListener("keydown",onOneDocumentClick),window.Notification&&Notification.requestPermission()}function closeAfter(notification,timeoutMs){setTimeout(function(){notification.close?notification.close():notification.cancel&¬ification.cancel()},timeoutMs)}function resetRegistration(){var serviceWorker=navigator.serviceWorker;serviceWorker&&serviceWorker.ready.then(function(registration){serviceWorkerRegistration=registration})}function showPersistentNotification(title,options,timeoutMs){serviceWorkerRegistration.showNotification(title,options)}function showNonPersistentNotification(title,options,timeoutMs){try{var notif=new Notification(title,options);notif.show&¬if.show(),timeoutMs&&closeAfter(notif,timeoutMs)}catch(err){if(!options.actions)throw err;options.actions=[],showNonPersistentNotification(title,options,timeoutMs)}}function showNotification(options,timeoutMs,apiClient){var title=options.title;return options.data=options.data||{},options.data.serverId=apiClient.serverInfo().Id,options.icon=options.icon||getIconUrl(),options.badge=options.badge||getIconUrl("badge.png"),resetRegistration(),serviceWorkerRegistration?void showPersistentNotification(title,options,timeoutMs):void showNonPersistentNotification(title,options,timeoutMs)}function showNewItemNotification(item,apiClient){if(!playbackManager.isPlayingLocally(["Video"])){var body=item.Name;item.SeriesName&&(body=item.SeriesName+" - "+body);var notification={title:"New "+item.Type,body:body,vibrate:!0,tag:"newItem"+item.Id,data:{}},imageTags=item.ImageTags||{};imageTags.Primary&&(notification.icon=apiClient.getScaledImageUrl(item.Id,{width:80,tag:imageTags.Primary,type:"Primary"})),showNotification(notification,15e3,apiClient)}}function onLibraryChanged(data,apiClient){var newItems=data.ItemsAdded;newItems.length&&apiClient.getItems(apiClient.getCurrentUserId(),{Recursive:!0,Limit:3,Filters:"IsNotFolder",SortBy:"DateCreated",SortOrder:"Descending",Ids:newItems.join(","),MediaTypes:"Audio,Video"}).then(function(result){for(var items=result.Items,i=0,length=items.length;i=interceptors.length)return void resolve();var interceptor=interceptors[index];interceptor.intercept(options).then(function(){runNextPrePlay(interceptors,index+1,options,resolve,reject)},reject)}function playAfterBitrateDetect(connectionManager,maxBitrate,item,playOptions,onPlaybackStartedFn){var promise,startPosition=playOptions.startPositionTicks,player=getPlayer(item,playOptions),activePlayer=currentPlayer;return activePlayer?(playNextAfterEnded=!1,promise=onPlaybackChanging(activePlayer,player,item)):promise=Promise.resolve(),isServerItem(item)&&"Game"!==item.MediaType?Promise.all([promise,player.getDeviceProfile(item)]).then(function(responses){var deviceProfile=responses[1],apiClient=connectionManager.getApiClient(item.ServerId);return getPlaybackMediaSource(apiClient,deviceProfile,maxBitrate,item,startPosition).then(function(mediaSource){return createStreamInfo(apiClient,item.MediaType,item,mediaSource,startPosition).then(function(streamInfo){return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,getPlayerData(player).maxStreamingBitrate=maxBitrate,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource)},function(){onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource),setTimeout(function(err){onPlaybackError.call(player,err,{type:"mediadecodeerror"})},100)})})})}):promise.then(function(){var streamInfo=createStreamInfoFromUrlItem(item);return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo)},function(){self.stop(player)})})}function createStreamInfoFromUrlItem(item){return{url:item.Url||item.Path,playMethod:"DirectPlay",item:item,textTracks:[],mediaType:item.MediaType}}function backdropImageUrl(apiClient,item,options){return options=options||{},options.type=options.type||"Backdrop",options.maxWidth||options.width||options.maxHeight||options.height||(options.quality=100),item.BackdropImageTags&&item.BackdropImageTags.length?(options.tag=item.BackdropImageTags[0],apiClient.getScaledImageUrl(item.Id,options)):item.ParentBackdropImageTags&&item.ParentBackdropImageTags.length?(options.tag=item.ParentBackdropImageTags[0],apiClient.getScaledImageUrl(item.ParentBackdropItemId,options)):null}function getMimeType(type,container){if(container=(container||"").toLowerCase(),"audio"===type){if("opus"===container)return"audio/ogg";if("webma"===container)return"audio/webm";if("m4a"===container)return"audio/mp4"}else if("video"===type){if("mkv"===container)return"video/x-matroska";if("m4v"===container)return"video/mp4";if("mov"===container)return"video/quicktime";if("mpg"===container)return"video/mpeg";if("flv"===container)return"video/x-flv"}return type+"/"+container}function createStreamInfo(apiClient,type,item,mediaSource,startPosition,forceTranscoding){var mediaUrl,contentType,directOptions,transcodingOffsetTicks=0,playerStartPositionTicks=startPosition,liveStreamId=mediaSource.LiveStreamId,playMethod="Transcode",mediaSourceContainer=(mediaSource.Container||"").toLowerCase();if("Video"===type)contentType=getMimeType("video",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding?(mediaUrl=mediaSource.Path,playMethod="DirectPlay"):mediaSource.SupportsDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Videos/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(playerStartPositionTicks=null,contentType=getMimeType("video",mediaSource.TranscodingContainer),mediaUrl.toLowerCase().indexOf("copytimestamps=true")===-1&&(transcodingOffsetTicks=startPosition||0)));else if("Audio"===type)if(contentType=getMimeType("audio",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding)mediaUrl=mediaSource.Path,playMethod="DirectPlay";else{var isDirectStream=mediaSource.SupportsDirectStream;isDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Audio/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(transcodingOffsetTicks=startPosition||0,playerStartPositionTicks=null,contentType=getMimeType("audio",mediaSource.TranscodingContainer)))}else"Game"===type&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");!mediaUrl&&mediaSource.SupportsDirectPlay&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");var resultInfo={url:mediaUrl,mimeType:contentType,transcodingOffsetTicks:transcodingOffsetTicks,playMethod:playMethod,playerStartPositionTicks:playerStartPositionTicks,item:item,mediaSource:mediaSource,textTracks:getTextTracks(apiClient,mediaSource),tracks:getTextTracks(apiClient,mediaSource),mediaType:type,liveStreamId:liveStreamId,playSessionId:getParam("playSessionId",mediaUrl),title:item.Name},backdropUrl=backdropImageUrl(apiClient,item,{});return backdropUrl&&(resultInfo.backdropUrl=backdropUrl),Promise.resolve(resultInfo)}function getParam(name,url){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS,"i"),results=regex.exec(url);return null==results?"":decodeURIComponent(results[1].replace(/\+/g," "))}function getTextTracks(apiClient,mediaSource){for(var subtitleStreams=mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type}),textStreams=subtitleStreams.filter(function(s){return"External"===s.DeliveryMethod}),tracks=[],i=0,length=textStreams.length;i=playlistLength&&(newIndex=0);break;default:newIndex=self.getCurrentPlaylistIndex(player)+1}if(newIndex<0||newIndex>=playlistLength)return null;var item=playlist[newIndex];return item?{item:item,index:newIndex}:null}function queue(options,mode,player){if(player=player||currentPlayer,!player)return self.play(options);if(!enableLocalPlaylistManagement(player))return"next"===mode?player.queueNext(item):player.queue(item);if(options.items)return translateItemsForPlayback(options.items,options).then(function(items){queueAll(items,mode)});if(!options.serverId)throw new Error("serverId required!");return getItemsForPlayback(options.serverId,{Ids:options.ids.join(",")}).then(function(result){return translateItemsForPlayback(result.Items,options).then(function(items){queueAll(items,mode)})})}function queueAll(items,mode){for(var i=0,length=items.length;idatetime.parseISO8601Date(item.EndDate).getTime()||(new Date).getTime()=supported.length&&(index=0),self.setAspectRatio(supported[index].id,player)}},self.setAspectRatio=function(val,player){player=player||currentPlayer,player&&player.setAspectRatio&&player.setAspectRatio(val)},self.getSupportedAspectRatios=function(player){return player=player||currentPlayer,player&&player.getSupportedAspectRatios?player.getSupportedAspectRatios():[]},self.getAspectRatio=function(player){if(player=player||currentPlayer,player&&player.getAspectRatio)return player.getAspectRatio()};var brightnessOsdLoaded;self.setBrightness=function(val,player){player=player||currentPlayer,player&&(brightnessOsdLoaded||(brightnessOsdLoaded=!0,require(["brightnessOsd"])),player.setBrightness(val))},self.getBrightness=function(player){if(player=player||currentPlayer)return player.getBrightness()},self.setVolume=function(val,player){player=player||currentPlayer,player&&player.setVolume(val)},self.getVolume=function(player){if(player=player||currentPlayer)return player.getVolume()},self.volumeUp=function(player){player=player||currentPlayer,player&&player.volumeUp()},self.volumeDown=function(player){player=player||currentPlayer,player&&player.volumeDown()},self.changeAudioStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeAudioStreamIndex()},self.changeSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeSubtitleStreamIndex()},self.getAudioStreamIndex=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getAudioStreamIndex():getPlayerData(player).audioStreamIndex},self.setAudioStreamIndex=function(index,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setAudioStreamIndex(index):void("Transcode"!==getPlayerData(player).streamInfo.playMethod&&player.canSetAudioStreamIndex()?(player.setAudioStreamIndex(index),getPlayerData(player).audioStreamIndex=index):(changeStream(player,getCurrentTicks(player),{AudioStreamIndex:index}),getPlayerData(player).audioStreamIndex=index))},self.getMaxStreamingBitrate=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getMaxStreamingBitrate():getPlayerData(player).maxStreamingBitrate||appSettings.maxStreamingBitrate()},self.enableAutomaticBitrateDetection=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.enableAutomaticBitrateDetection():appSettings.enableAutomaticBitrateDetection()},self.setMaxStreamingBitrate=function(options,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setMaxStreamingBitrate(options);var promise;options.enableAutomaticBitrateDetection?(appSettings.enableAutomaticBitrateDetection(!0),promise=connectionManager.getApiClient(self.currentItem(player).ServerId).detectBitrate(!0)):(appSettings.enableAutomaticBitrateDetection(!1),promise=Promise.resolve(options.maxBitrate)),promise.then(function(bitrate){appSettings.maxStreamingBitrate(bitrate),changeStream(player,getCurrentTicks(player),{MaxStreamingBitrate:bitrate})})},self.isFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.isFullscreen?player.isFullscreen():fullscreenManager.isFullScreen()},self.toggleFullscreen=function(player){return player=player||currentPlayer,!player.isLocalPlayer||player.toggleFulscreen?player.toggleFulscreen():void(fullscreenManager.isFullScreen()?fullscreenManager.exitFullscreen():fullscreenManager.requestFullscreen())},self.togglePictureInPicture=function(player){return player=player||currentPlayer,player.togglePictureInPicture()},self.getSubtitleStreamIndex=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.getSubtitleStreamIndex();if(!player)throw new Error("player cannot be null");return getPlayerData(player).subtitleStreamIndex},self.setSubtitleStreamIndex=function(index,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setSubtitleStreamIndex(index);var currentStream=getCurrentSubtitleStream(player),newStream=getSubtitleStream(player,index);if(currentStream||newStream){var selectedTrackElementIndex=-1,currentPlayMethod=(getPlayerData(player).streamInfo||{}).playMethod;currentStream&&!newStream?("Encode"===currentStream.DeliveryMethod||"Embed"===currentStream.DeliveryMethod&&"Transcode"===currentPlayMethod)&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1}):!currentStream&&newStream?"External"===newStream.DeliveryMethod?selectedTrackElementIndex=index:"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?selectedTrackElementIndex=index:changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index}):currentStream&&newStream&&("External"===newStream.DeliveryMethod||"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?(selectedTrackElementIndex=index,"External"!==currentStream.DeliveryMethod&&"Embed"!==currentStream.DeliveryMethod&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1})):changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index})),player.setSubtitleStreamIndex(selectedTrackElementIndex),getPlayerData(player).subtitleStreamIndex=index}},self.toggleDisplayMirroring=function(){self.enableDisplayMirroring(!self.enableDisplayMirroring())},self.enableDisplayMirroring=function(enabled){if(null!=enabled){var val=enabled?"1":"0";return void appSettings.set("displaymirror",val)}return"0"!==(appSettings.get("displaymirror")||"")},self.stop=function(player){return player=player||currentPlayer,player?(playNextAfterEnded=!1,player.stop(!0,!0)):Promise.resolve()},self.playPause=function(player){if(player=player||currentPlayer)return player.playPause?player.playPause():player.paused()?self.unpause(player):self.pause(player)},self.paused=function(player){if(player=player||currentPlayer)return player.paused()},self.pause=function(player){player=player||currentPlayer,player&&player.pause()},self.unpause=function(player){player=player||currentPlayer,player&&player.unpause()},self.seek=function(ticks,player){return ticks=Math.max(0,ticks),player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.seek(ticks):void changeStream(player,ticks)},self.nextChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player),nextChapter=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks>ticks})[0];nextChapter?self.seek(nextChapter.StartPositionTicks,player):self.nextTrack(player)},self.previousChapter=function(player){player=player||currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player);ticks-=1e8,0===self.getCurrentPlaylistIndex(player)&&(ticks=Math.max(ticks,0));var previousChapters=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks<=ticks});previousChapters.length?self.seek(previousChapters[previousChapters.length-1].StartPositionTicks,player):self.previousTrack(player)},self.fastForward=function(player){if(player=player||currentPlayer,null!=player.fastForward)return void player.fastForward(userSettings.skipForwardLength());var ticks=getCurrentTicks(player);ticks+=1e4*userSettings.skipForwardLength();var runTimeTicks=self.duration(player)||0;ticks0||canPlayerSeek(player)),item&&(state.NowPlayingItem=getNowPlayingItemForReporting(player,item,mediaSource)),state.MediaSource=mediaSource,Promise.resolve(state)},self.currentTime=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.currentTime():getCurrentTicks(player)},self.duration=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.duration();if(!player)throw new Error("player cannot be null");var streamInfo=getPlayerData(player).streamInfo;if(streamInfo&&streamInfo.mediaSource&&streamInfo.mediaSource.RunTimeTicks)return streamInfo.mediaSource.RunTimeTicks;var playerDuration=player.duration();return playerDuration&&(playerDuration*=1e4),playerDuration};var currentId=0;self.getSubtitleUrl=function(textStream,serverId){var apiClient=connectionManager.getApiClient(serverId),textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);return textStreamUrl},self.setCurrentPlaylistItem=function(playlistItemId,player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setCurrentPlaylistItem(playlistItemId);for(var newItem,newItemIndex,i=0,length=playlist.length;i=playlist.length)throw new Error("newIndex out of bounds");moveInArray(playlist,oldIndex,newIndex),events.trigger(player,"playlistitemmove",[{playlistItemId:playlistItemId,newIndex:newIndex}])}},self.getCurrentPlaylistIndex=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistIndex():findPlaylistIndex(currentPlaylistItemId,playlist)},self.getCurrentPlaylistItemId=function(i,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistItemId():currentPlaylistItemId},self.setRepeatMode=function(value,player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setRepeatMode(value):(repeatMode=value,void events.trigger(player,"repeatmodechange"))},self.getRepeatMode=function(player){return player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getRepeatMode():repeatMode},self.nextTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.nextTrack();var newItemInfo=getNextItemInfo(player);if(newItemInfo){console.log("playing next track");var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItemInfo.item,playOptions,function(){setPlaylistState(newItemInfo.item.PlaylistItemId,newItemInfo.index)})}},self.previousTrack=function(player){if(player=player||currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.previousTrack();var newIndex=self.getCurrentPlaylistIndex(player)-1;if(newIndex>=0){var newItem=playlist[newIndex];if(newItem){var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItem,playOptions,function(){setPlaylistState(newItem.PlaylistItemId,newIndex)})}}},self.queue=function(options,player){queue(options,"",player)},self.queueNext=function(options,player){queue(options,"next",player)},events.on(pluginManager,"registered",function(e,plugin){"mediaplayer"===plugin.type&&initMediaPlayer(plugin)}),pluginManager.ofType("mediaplayer").map(initMediaPlayer),window.addEventListener("beforeunload",function(e){var player=currentPlayer;player&&self.isPlaying(player)&&(playNextAfterEnded=!1,onPlaybackStopped.call(player))}),events.on(serverNotifications,"ServerShuttingDown",function(e,apiClient,data){self.setDefaultPlayerActive()}),events.on(serverNotifications,"ServerRestarting",function(e,apiClient,data){self.setDefaultPlayerActive()})}return PlaybackManager.prototype.sendCommand=function(cmd,player){switch(console.log("MediaController received command: "+cmd.Name),cmd.Name){case"SetRepeatMode":this.setRepeatMode(cmd.Arguments.RepeatMode,player);break;case"VolumeUp":this.volumeUp(player);break;case"VolumeDown":this.volumeDown(player);break;case"Mute":this.setMute(!0,player);break;case"Unmute":this.setMute(!1,player);break;case"ToggleMute":this.toggleMute(player);break;case"SetVolume":this.setVolume(cmd.Arguments.Volume,player);break;case"SetAspectRatio":this.setAspectRatio(cmd.Arguments.AspectRatio,player);break;case"SetBrightness":this.setBrightness(cmd.Arguments.Brightness,player);break;case"SetAudioStreamIndex":this.setAudioStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetSubtitleStreamIndex":this.setSubtitleStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetMaxStreamingBitrate":break;case"ToggleFullscreen":this.toggleFullscreen(player);break;default:player.sendCommand&&player.sendCommand(cmd)}},new PlaybackManager}); \ No newline at end of file +define(["events","datetime","appSettings","pluginManager","userSettings","globalize","connectionManager","loading","serverNotifications","apphost","fullscreenManager","layoutManager"],function(events,datetime,appSettings,pluginManager,userSettings,globalize,connectionManager,loading,serverNotifications,apphost,fullscreenManager,layoutManager){"use strict";function enableLocalPlaylistManagement(player){return!!player.isLocalPlayer}function bindToFullscreenChange(player){events.on(fullscreenManager,"fullscreenchange",function(){events.trigger(player,"fullscreenchange")})}function triggerPlayerChange(playbackManagerInstance,newPlayer,newTarget,previousPlayer,previousTargetInfo){(newPlayer||previousPlayer)&&(newTarget&&previousTargetInfo&&newTarget.id===previousTargetInfo.id||events.trigger(playbackManagerInstance,"playerchange",[newPlayer,newTarget,previousPlayer]))}function reportPlayback(state,serverId,method,progressEventName){if(serverId){var info=Object.assign({},state.PlayState);info.ItemId=state.NowPlayingItem.Id,progressEventName&&(info.EventName=progressEventName);var apiClient=connectionManager.getApiClient(serverId);apiClient[method](info)}}function normalizeName(t){return t.toLowerCase().replace(" ","")}function PlaybackManager(){function displayPlayerInLocalGroup(player){return player.isLocalPlayer}function getSupportedCommands(player){if(player.isLocalPlayer){var list=["GoHome","GoToSettings","VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","SetMaxStreamingBitrate","DisplayContent","GoToSearch","DisplayMessage","SetRepeatMode"];return apphost.supports("fullscreenchange")&&!layoutManager.tv&&list.push("ToggleFullscreen"),player.supports&&(player.supports("PictureInPicture")&&list.push("PictureInPicture"),player.supports("SetBrightness")&&list.push("SetBrightness"),player.supports("SetAspectRatio")&&list.push("SetAspectRatio")),list}throw new Error("player must define supported commands")}function createTarget(player){return{name:player.name,id:player.id,playerName:player.name,playableMediaTypes:["Audio","Video","Game"].map(player.canPlayMediaType),isLocalPlayer:player.isLocalPlayer,supportedCommands:getSupportedCommands(player)}}function getPlayerTargets(player){return player.getTargets?player.getTargets():Promise.resolve([createTarget(player)])}function getCurrentSubtitleStream(player){if(!player)throw new Error("player cannot be null");var index=getPlayerData(player).subtitleStreamIndex;return null==index||index===-1?null:getSubtitleStream(player,index)}function getSubtitleStream(player,index){return self.currentMediaSource(player).MediaStreams.filter(function(s){return"Subtitle"===s.Type&&s.Index===index})[0]}function setCurrentPlayerInternal(player,targetInfo){var previousPlayer=self._currentPlayer,previousTargetInfo=currentTargetInfo;if(player&&!targetInfo&&player.isLocalPlayer&&(targetInfo=createTarget(player)),player&&!targetInfo)throw new Error("targetInfo cannot be null");currentPairingId=null,self._currentPlayer=player,currentTargetInfo=targetInfo,targetInfo&&console.log("Active player: "+JSON.stringify(targetInfo)),player&&player.isLocalPlayer&&(lastLocalPlayer=player),previousPlayer&&self.endPlayerUpdates(previousPlayer),player&&self.beginPlayerUpdates(player),triggerPlayerChange(self,player,targetInfo,previousPlayer,previousTargetInfo)}function getAutomaticPlayers(){var player=self._currentPlayer;return player&&!enableLocalPlaylistManagement(player)?[player]:self.getPlayers().filter(enableLocalPlaylistManagement)}function canPlayerSeek(player){if(!player)throw new Error("player cannot be null");var playerData=getPlayerData(player),currentSrc=(playerData.streamInfo.url||"").toLowerCase();return currentSrc.indexOf(".m3u8")!==-1||"Transcode"!==playerData.streamInfo.playMethod&&player.duration()}function changeStream(player,ticks,params){if(canPlayerSeek(player)&&null==params)return void player.currentTime(parseInt(ticks/1e4));params=params||{};var liveStreamId=getPlayerData(player).streamInfo.liveStreamId,playSessionId=getPlayerData(player).streamInfo.playSessionId,playerData=getPlayerData(player),currentItem=playerData.streamInfo.item;player.getDeviceProfile(currentItem,{isRetry:params.EnableDirectPlay===!1}).then(function(deviceProfile){var audioStreamIndex=null==params.AudioStreamIndex?getPlayerData(player).audioStreamIndex:params.AudioStreamIndex,subtitleStreamIndex=null==params.SubtitleStreamIndex?getPlayerData(player).subtitleStreamIndex:params.SubtitleStreamIndex,currentMediaSource=playerData.streamInfo.mediaSource,apiClient=connectionManager.getApiClient(currentItem.ServerId);ticks&&(ticks=parseInt(ticks));var maxBitrate=params.MaxStreamingBitrate||self.getMaxStreamingBitrate(player);getPlaybackInfo(player,apiClient,currentItem,deviceProfile,maxBitrate,ticks,currentMediaSource,audioStreamIndex,subtitleStreamIndex,liveStreamId,params.EnableDirectPlay,params.EnableDirectStream,params.AllowVideoStreamCopy,params.AllowAudioStreamCopy).then(function(result){validatePlaybackInfoResult(result)&&(currentMediaSource=result.MediaSources[0],createStreamInfo(apiClient,currentItem.MediaType,currentItem,currentMediaSource,ticks).then(function(streamInfo){return streamInfo.fullscreen=currentPlayOptions.fullscreen,streamInfo.url?(getPlayerData(player).subtitleStreamIndex=subtitleStreamIndex,getPlayerData(player).audioStreamIndex=audioStreamIndex,getPlayerData(player).maxStreamingBitrate=maxBitrate,void changeStreamToUrl(apiClient,player,playSessionId,streamInfo)):(showPlaybackInfoErrorMessage("NoCompatibleStream"),void self.nextTrack())}))})})}function changeStreamToUrl(apiClient,player,playSessionId,streamInfo,newPositionTicks){var playerData=getPlayerData(player);playerData.isChangingStream=!0,"Video"===playerData.MediaType?apiClient.stopActiveEncodings(playSessionId).then(function(){setSrcIntoPlayer(apiClient,player,streamInfo)}):setSrcIntoPlayer(apiClient,player,streamInfo)}function setSrcIntoPlayer(apiClient,player,streamInfo){player.play(streamInfo).then(function(){var playerData=getPlayerData(player);playerData.isChangingStream=!1,playerData.streamInfo=streamInfo,sendProgressUpdate(player,"timeupdate")},function(e){onPlaybackError.call(player,e,{type:"mediadecodeerror"})})}function getPlayerData(player){if(!player)throw new Error("player cannot be null");if(!player.name)throw new Error("player name cannot be null");var state=playerStates[player.name];return state||(playerStates[player.name]={},state=playerStates[player.name]),player}function getCurrentTicks(player){if(!player)throw new Error("player cannot be null");var playerTime=Math.floor(1e4*(player||self._currentPlayer).currentTime());return playerTime+=getPlayerData(player).streamInfo.transcodingOffsetTicks||0}function getNowPlayingItemForReporting(player,item,mediaSource){var nowPlayingItem=Object.assign({},item);return mediaSource&&(nowPlayingItem.RunTimeTicks=mediaSource.RunTimeTicks),nowPlayingItem.RunTimeTicks=nowPlayingItem.RunTimeTicks||1e4*player.duration(),nowPlayingItem}function translateItemsForPlayback(items,options){var promise,firstItem=items[0],serverId=firstItem.ServerId;return"Program"===firstItem.Type?promise=getItemsForPlayback(serverId,{Ids:firstItem.ChannelId}):"Playlist"===firstItem.Type?promise=getItemsForPlayback(serverId,{ParentId:firstItem.Id}):"MusicArtist"===firstItem.Type?promise=getItemsForPlayback(serverId,{ArtistIds:firstItem.Id,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio"}):"MusicGenre"===firstItem.Type?promise=getItemsForPlayback(serverId,{Genres:firstItem.Name,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio"}):firstItem.IsFolder?promise=getItemsForPlayback(serverId,{ParentId:firstItem.Id,Filters:"IsNotFolder",Recursive:!0,SortBy:"SortName",MediaTypes:"Audio,Video"}):"Episode"===firstItem.Type&&1===items.length&&getPlayer(firstItem,options).supportsProgress!==!1&&(promise=new Promise(function(resolve,reject){var apiClient=connectionManager.getApiClient(firstItem.ServerId);apiClient.getCurrentUser().then(function(user){return user.Configuration.EnableNextEpisodeAutoPlay&&firstItem.SeriesId?void apiClient.getEpisodes(firstItem.SeriesId,{IsVirtualUnaired:!1,IsMissing:!1,UserId:apiClient.getCurrentUserId(),Fields:"MediaSources,Chapters"}).then(function(episodesResult){var foundItem=!1;episodesResult.Items=episodesResult.Items.filter(function(e){return!!foundItem||e.Id===firstItem.Id&&(foundItem=!0,!0)}),episodesResult.TotalRecordCount=episodesResult.Items.length,resolve(episodesResult)},reject):void resolve(null)})})),promise?promise.then(function(result){return result?result.Items:items}):Promise.resolve(items)}function enableIntros(item){return"Video"===item.MediaType&&("TvChannel"!==item.Type&&("InProgress"!==item.Status&&isServerItem(item)))}function playWithIntros(items,options,user){var firstItem=items[0];"Video"===firstItem.MediaType;var afterPlayInternal=function(){for(var i=0,length=items.length;i=interceptors.length)return void resolve();var interceptor=interceptors[index];interceptor.intercept(options).then(function(){runNextPrePlay(interceptors,index+1,options,resolve,reject)},reject)}function playAfterBitrateDetect(connectionManager,maxBitrate,item,playOptions,onPlaybackStartedFn){var promise,startPosition=playOptions.startPositionTicks,player=getPlayer(item,playOptions),activePlayer=self._currentPlayer;return activePlayer?(playNextAfterEnded=!1,promise=onPlaybackChanging(activePlayer,player,item)):promise=Promise.resolve(),isServerItem(item)&&"Game"!==item.MediaType?Promise.all([promise,player.getDeviceProfile(item)]).then(function(responses){var deviceProfile=responses[1],apiClient=connectionManager.getApiClient(item.ServerId);return getPlaybackMediaSource(player,apiClient,deviceProfile,maxBitrate,item,startPosition).then(function(mediaSource){return createStreamInfo(apiClient,item.MediaType,item,mediaSource,startPosition).then(function(streamInfo){return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,getPlayerData(player).maxStreamingBitrate=maxBitrate,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource)},function(){onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo,mediaSource),setTimeout(function(err){onPlaybackError.call(player,err,{type:"mediadecodeerror"})},100)})})})}):promise.then(function(){var streamInfo=createStreamInfoFromUrlItem(item);return streamInfo.fullscreen=playOptions.fullscreen,getPlayerData(player).isChangingStream=!1,player.play(streamInfo).then(function(){loading.hide(),onPlaybackStartedFn(),onPlaybackStarted(player,playOptions,streamInfo)},function(){self.stop(player)})})}function createStreamInfoFromUrlItem(item){return{url:item.Url||item.Path,playMethod:"DirectPlay",item:item,textTracks:[],mediaType:item.MediaType}}function backdropImageUrl(apiClient,item,options){return options=options||{},options.type=options.type||"Backdrop",options.maxWidth||options.width||options.maxHeight||options.height||(options.quality=100),item.BackdropImageTags&&item.BackdropImageTags.length?(options.tag=item.BackdropImageTags[0],apiClient.getScaledImageUrl(item.Id,options)):item.ParentBackdropImageTags&&item.ParentBackdropImageTags.length?(options.tag=item.ParentBackdropImageTags[0],apiClient.getScaledImageUrl(item.ParentBackdropItemId,options)):null}function getMimeType(type,container){if(container=(container||"").toLowerCase(),"audio"===type){if("opus"===container)return"audio/ogg";if("webma"===container)return"audio/webm";if("m4a"===container)return"audio/mp4"}else if("video"===type){if("mkv"===container)return"video/x-matroska";if("m4v"===container)return"video/mp4";if("mov"===container)return"video/quicktime";if("mpg"===container)return"video/mpeg";if("flv"===container)return"video/x-flv"}return type+"/"+container}function createStreamInfo(apiClient,type,item,mediaSource,startPosition,forceTranscoding){var mediaUrl,contentType,directOptions,transcodingOffsetTicks=0,playerStartPositionTicks=startPosition,liveStreamId=mediaSource.LiveStreamId,playMethod="Transcode",mediaSourceContainer=(mediaSource.Container||"").toLowerCase();if("Video"===type)contentType=getMimeType("video",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding?(mediaUrl=mediaSource.Path,playMethod="DirectPlay"):mediaSource.SupportsDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Videos/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(playerStartPositionTicks=null,contentType=getMimeType("video",mediaSource.TranscodingContainer),mediaUrl.toLowerCase().indexOf("copytimestamps=true")===-1&&(transcodingOffsetTicks=startPosition||0)));else if("Audio"===type)if(contentType=getMimeType("audio",mediaSourceContainer),mediaSource.enableDirectPlay&&!forceTranscoding)mediaUrl=mediaSource.Path,playMethod="DirectPlay";else{var isDirectStream=mediaSource.SupportsDirectStream;isDirectStream&&!forceTranscoding?(directOptions={Static:!0,mediaSourceId:mediaSource.Id,deviceId:apiClient.deviceId(),api_key:apiClient.accessToken()},mediaSource.ETag&&(directOptions.Tag=mediaSource.ETag),mediaSource.LiveStreamId&&(directOptions.LiveStreamId=mediaSource.LiveStreamId),mediaUrl=apiClient.getUrl("Audio/"+item.Id+"/stream."+mediaSourceContainer,directOptions),playMethod="DirectStream"):mediaSource.SupportsTranscoding&&(mediaUrl=apiClient.getUrl(mediaSource.TranscodingUrl),"hls"===mediaSource.TranscodingSubProtocol?contentType="application/x-mpegURL":(transcodingOffsetTicks=startPosition||0,playerStartPositionTicks=null,contentType=getMimeType("audio",mediaSource.TranscodingContainer)))}else"Game"===type&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");!mediaUrl&&mediaSource.SupportsDirectPlay&&(mediaUrl=mediaSource.Path,playMethod="DirectPlay");var resultInfo={url:mediaUrl,mimeType:contentType,transcodingOffsetTicks:transcodingOffsetTicks,playMethod:playMethod,playerStartPositionTicks:playerStartPositionTicks,item:item,mediaSource:mediaSource,textTracks:getTextTracks(apiClient,mediaSource),tracks:getTextTracks(apiClient,mediaSource),mediaType:type,liveStreamId:liveStreamId,playSessionId:getParam("playSessionId",mediaUrl),title:item.Name},backdropUrl=backdropImageUrl(apiClient,item,{});return backdropUrl&&(resultInfo.backdropUrl=backdropUrl),Promise.resolve(resultInfo)}function getParam(name,url){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS,"i"),results=regex.exec(url);return null==results?"":decodeURIComponent(results[1].replace(/\+/g," "))}function getTextTracks(apiClient,mediaSource){for(var subtitleStreams=mediaSource.MediaStreams.filter(function(s){return"Subtitle"===s.Type}),textStreams=subtitleStreams.filter(function(s){return"External"===s.DeliveryMethod}),tracks=[],i=0,length=textStreams.length;i=playlistLength&&(newIndex=0);break;default:newIndex=self.getCurrentPlaylistIndex(player)+1}if(newIndex<0||newIndex>=playlistLength)return null;var item=playlist[newIndex];return item?{item:item,index:newIndex}:null}function queue(options,mode,player){if(player=player||self._currentPlayer,!player)return self.play(options);if(!enableLocalPlaylistManagement(player))return"next"===mode?player.queueNext(item):player.queue(item);if(options.items)return translateItemsForPlayback(options.items,options).then(function(items){queueAll(items,mode)});if(!options.serverId)throw new Error("serverId required!");return getItemsForPlayback(options.serverId,{Ids:options.ids.join(",")}).then(function(result){return translateItemsForPlayback(result.Items,options).then(function(items){queueAll(items,mode)})})}function queueAll(items,mode){for(var i=0,length=items.length;idatetime.parseISO8601Date(item.EndDate).getTime()||(new Date).getTime()=supported.length&&(index=0),self.setAspectRatio(supported[index].id,player)}},self.setAspectRatio=function(val,player){player=player||self._currentPlayer,player&&player.setAspectRatio&&player.setAspectRatio(val)},self.getSupportedAspectRatios=function(player){return player=player||self._currentPlayer,player&&player.getSupportedAspectRatios?player.getSupportedAspectRatios():[]},self.getAspectRatio=function(player){if(player=player||self._currentPlayer,player&&player.getAspectRatio)return player.getAspectRatio()};var brightnessOsdLoaded;self.setBrightness=function(val,player){player=player||self._currentPlayer,player&&(brightnessOsdLoaded||(brightnessOsdLoaded=!0,require(["brightnessOsd"])),player.setBrightness(val))},self.getBrightness=function(player){if(player=player||self._currentPlayer)return player.getBrightness()},self.setVolume=function(val,player){player=player||self._currentPlayer,player&&player.setVolume(val)},self.getVolume=function(player){if(player=player||self._currentPlayer)return player.getVolume()},self.volumeUp=function(player){player=player||self._currentPlayer,player&&player.volumeUp()},self.volumeDown=function(player){player=player||self._currentPlayer,player&&player.volumeDown()},self.changeAudioStreamIndex=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeAudioStreamIndex()},self.changeSubtitleStreamIndex=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.changeSubtitleStreamIndex()},self.getAudioStreamIndex=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getAudioStreamIndex():getPlayerData(player).audioStreamIndex},self.setAudioStreamIndex=function(index,player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setAudioStreamIndex(index):void("Transcode"!==getPlayerData(player).streamInfo.playMethod&&player.canSetAudioStreamIndex()?(player.setAudioStreamIndex(index),getPlayerData(player).audioStreamIndex=index):(changeStream(player,getCurrentTicks(player),{AudioStreamIndex:index}),getPlayerData(player).audioStreamIndex=index))},self.getMaxStreamingBitrate=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getMaxStreamingBitrate():getPlayerData(player).maxStreamingBitrate||appSettings.maxStreamingBitrate()},self.enableAutomaticBitrateDetection=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.enableAutomaticBitrateDetection():appSettings.enableAutomaticBitrateDetection()},self.setMaxStreamingBitrate=function(options,player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setMaxStreamingBitrate(options);var promise;options.enableAutomaticBitrateDetection?(appSettings.enableAutomaticBitrateDetection(!0),promise=connectionManager.getApiClient(self.currentItem(player).ServerId).detectBitrate(!0)):(appSettings.enableAutomaticBitrateDetection(!1),promise=Promise.resolve(options.maxBitrate)),promise.then(function(bitrate){appSettings.maxStreamingBitrate(bitrate),changeStream(player,getCurrentTicks(player),{MaxStreamingBitrate:bitrate})})},self.isFullscreen=function(player){return player=player||self._currentPlayer,!player.isLocalPlayer||player.isFullscreen?player.isFullscreen():fullscreenManager.isFullScreen()},self.toggleFullscreen=function(player){return player=player||self._currentPlayer,!player.isLocalPlayer||player.toggleFulscreen?player.toggleFulscreen():void(fullscreenManager.isFullScreen()?fullscreenManager.exitFullscreen():fullscreenManager.requestFullscreen())},self.togglePictureInPicture=function(player){return player=player||self._currentPlayer,player.togglePictureInPicture()},self.getSubtitleStreamIndex=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.getSubtitleStreamIndex();if(!player)throw new Error("player cannot be null");return getPlayerData(player).subtitleStreamIndex},self.setSubtitleStreamIndex=function(index,player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setSubtitleStreamIndex(index);var currentStream=getCurrentSubtitleStream(player),newStream=getSubtitleStream(player,index);if(currentStream||newStream){var selectedTrackElementIndex=-1,currentPlayMethod=(getPlayerData(player).streamInfo||{}).playMethod;currentStream&&!newStream?("Encode"===currentStream.DeliveryMethod||"Embed"===currentStream.DeliveryMethod&&"Transcode"===currentPlayMethod)&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1}):!currentStream&&newStream?"External"===newStream.DeliveryMethod?selectedTrackElementIndex=index:"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?selectedTrackElementIndex=index:changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index}):currentStream&&newStream&&("External"===newStream.DeliveryMethod||"Embed"===newStream.DeliveryMethod&&"Transcode"!==currentPlayMethod?(selectedTrackElementIndex=index,"External"!==currentStream.DeliveryMethod&&"Embed"!==currentStream.DeliveryMethod&&changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:-1})):changeStream(player,getCurrentTicks(player),{SubtitleStreamIndex:index})),player.setSubtitleStreamIndex(selectedTrackElementIndex),getPlayerData(player).subtitleStreamIndex=index}},self.toggleDisplayMirroring=function(){self.enableDisplayMirroring(!self.enableDisplayMirroring())},self.enableDisplayMirroring=function(enabled){if(null!=enabled){var val=enabled?"1":"0";return void appSettings.set("displaymirror",val)}return"0"!==(appSettings.get("displaymirror")||"")},self.stop=function(player){return player=player||self._currentPlayer,player?(playNextAfterEnded=!1,player.stop(!0,!0)):Promise.resolve()},self.playPause=function(player){if(player=player||self._currentPlayer)return player.playPause?player.playPause():player.paused()?self.unpause(player):self.pause(player)},self.paused=function(player){if(player=player||self._currentPlayer)return player.paused()},self.pause=function(player){player=player||self._currentPlayer,player&&player.pause()},self.unpause=function(player){player=player||self._currentPlayer,player&&player.unpause()},self.seek=function(ticks,player){return ticks=Math.max(0,ticks),player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.seek(ticks):void changeStream(player,ticks)},self.nextChapter=function(player){player=player||self._currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player),nextChapter=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks>ticks})[0];nextChapter?self.seek(nextChapter.StartPositionTicks,player):self.nextTrack(player)},self.previousChapter=function(player){player=player||self._currentPlayer;var item=self.currentItem(player),ticks=getCurrentTicks(player);ticks-=1e8,0===self.getCurrentPlaylistIndex(player)&&(ticks=Math.max(ticks,0));var previousChapters=(item.Chapters||[]).filter(function(i){return i.StartPositionTicks<=ticks});previousChapters.length?self.seek(previousChapters[previousChapters.length-1].StartPositionTicks,player):self.previousTrack(player)},self.fastForward=function(player){if(player=player||self._currentPlayer,null!=player.fastForward)return void player.fastForward(userSettings.skipForwardLength());var ticks=getCurrentTicks(player);ticks+=1e4*userSettings.skipForwardLength();var runTimeTicks=self.duration(player)||0;ticks0||canPlayerSeek(player)),item&&(state.NowPlayingItem=getNowPlayingItemForReporting(player,item,mediaSource)),state.MediaSource=mediaSource,Promise.resolve(state)},self.currentTime=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.currentTime():getCurrentTicks(player)},self.duration=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.duration();if(!player)throw new Error("player cannot be null");var streamInfo=getPlayerData(player).streamInfo;if(streamInfo&&streamInfo.mediaSource&&streamInfo.mediaSource.RunTimeTicks)return streamInfo.mediaSource.RunTimeTicks;var playerDuration=player.duration();return playerDuration&&(playerDuration*=1e4),playerDuration};var currentId=0;self.getSubtitleUrl=function(textStream,serverId){var apiClient=connectionManager.getApiClient(serverId),textStreamUrl=textStream.IsExternalUrl?textStream.DeliveryUrl:apiClient.getUrl(textStream.DeliveryUrl);return textStreamUrl},self.setCurrentPlaylistItem=function(playlistItemId,player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.setCurrentPlaylistItem(playlistItemId);for(var newItem,newItemIndex,i=0,length=playlist.length;i=playlist.length)throw new Error("newIndex out of bounds");moveInArray(playlist,oldIndex,newIndex),events.trigger(player,"playlistitemmove",[{playlistItemId:playlistItemId,newIndex:newIndex}])}},self.getCurrentPlaylistIndex=function(i,player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistIndex():findPlaylistIndex(currentPlaylistItemId,playlist)},self.getCurrentPlaylistItemId=function(i,player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getCurrentPlaylistItemId():currentPlaylistItemId},self.setRepeatMode=function(value,player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.setRepeatMode(value):(repeatMode=value,void events.trigger(player,"repeatmodechange"))},self.getRepeatMode=function(player){return player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player)?player.getRepeatMode():repeatMode},self.nextTrack=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.nextTrack();var newItemInfo=getNextItemInfo(player);if(newItemInfo){console.log("playing next track");var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItemInfo.item,playOptions,function(){setPlaylistState(newItemInfo.item.PlaylistItemId,newItemInfo.index)})}},self.previousTrack=function(player){if(player=player||self._currentPlayer,player&&!enableLocalPlaylistManagement(player))return player.previousTrack();var newIndex=self.getCurrentPlaylistIndex(player)-1;if(newIndex>=0){var newItem=playlist[newIndex];if(newItem){var playOptions=Object.assign({},currentPlayOptions,{startPositionTicks:0});playInternal(newItem,playOptions,function(){setPlaylistState(newItem.PlaylistItemId,newIndex)})}}},self.queue=function(options,player){queue(options,"",player)},self.queueNext=function(options,player){queue(options,"next",player)},events.on(pluginManager,"registered",function(e,plugin){"mediaplayer"===plugin.type&&initMediaPlayer(plugin)}),pluginManager.ofType("mediaplayer").map(initMediaPlayer),window.addEventListener("beforeunload",function(e){var player=self._currentPlayer;player&&self.isPlaying(player)&&(playNextAfterEnded=!1,onPlaybackStopped.call(player))}),events.on(serverNotifications,"ServerShuttingDown",function(e,apiClient,data){self.setDefaultPlayerActive()}),events.on(serverNotifications,"ServerRestarting",function(e,apiClient,data){self.setDefaultPlayerActive()})}return PlaybackManager.prototype.trySetActiveDeviceName=function(name){name=normalizeName(name);var instance=this;instance.getTargets().then(function(result){var target=result.filter(function(p){return normalizeName(p.name)===name})[0];target&&instance.trySetActivePlayer(target.playerName,target)})},PlaybackManager.prototype.displayContent=function(options,player){player=player||this._currentPlayer,player&&player.displayContent&&player.displayContent(options)},PlaybackManager.prototype.beginPlayerUpdates=function(player){player.beginPlayerUpdates&&player.beginPlayerUpdates()},PlaybackManager.prototype.endPlayerUpdates=function(player){player.endPlayerUpdates&&player.endPlayerUpdates()},PlaybackManager.prototype.setDefaultPlayerActive=function(){this.setActivePlayer("localplayer")},PlaybackManager.prototype.removeActivePlayer=function(name){var playerInfo=this.getPlayerInfo();playerInfo&&playerInfo.name===name&&this.setDefaultPlayerActive()},PlaybackManager.prototype.removeActiveTarget=function(id){var playerInfo=this.getPlayerInfo();playerInfo&&playerInfo.id===id&&this.setDefaultPlayerActive()},PlaybackManager.prototype.disconnectFromPlayer=function(){var playerInfo=this.getPlayerInfo();if(playerInfo){var instance=this;playerInfo.supportedCommands.indexOf("EndSession")!==-1?require(["dialog"],function(dialog){var menuItems=[];menuItems.push({name:globalize.translate("ButtonYes"),id:"yes"}),menuItems.push({name:globalize.translate("ButtonNo"),id:"no"}),dialog({buttons:menuItems,text:globalize.translate("ConfirmEndPlayerSession")}).then(function(id){switch(id){case"yes":instance.getCurrentPlayer().endSession(),instance.setDefaultPlayerActive();break;case"no":instance.setDefaultPlayerActive()}})}):this.setDefaultPlayerActive()}},PlaybackManager.prototype.sendCommand=function(cmd,player){switch(console.log("MediaController received command: "+cmd.Name),cmd.Name){case"SetRepeatMode":this.setRepeatMode(cmd.Arguments.RepeatMode,player);break;case"VolumeUp":this.volumeUp(player);break;case"VolumeDown":this.volumeDown(player);break;case"Mute":this.setMute(!0,player);break;case"Unmute":this.setMute(!1,player);break;case"ToggleMute":this.toggleMute(player);break;case"SetVolume":this.setVolume(cmd.Arguments.Volume,player);break;case"SetAspectRatio":this.setAspectRatio(cmd.Arguments.AspectRatio,player);break;case"SetBrightness":this.setBrightness(cmd.Arguments.Brightness,player);break;case"SetAudioStreamIndex":this.setAudioStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetSubtitleStreamIndex":this.setSubtitleStreamIndex(parseInt(cmd.Arguments.Index),player);break;case"SetMaxStreamingBitrate":break;case"ToggleFullscreen":this.toggleFullscreen(player);break;default:player.sendCommand&&player.sendCommand(cmd)}},new PlaybackManager}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/playlisteditor/playlisteditor.js b/dashboard-ui/bower_components/emby-webcomponents/playlisteditor/playlisteditor.js index 6c611dd489..78f62090a7 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/playlisteditor/playlisteditor.js +++ b/dashboard-ui/bower_components/emby-webcomponents/playlisteditor/playlisteditor.js @@ -1 +1 @@ -define(["shell","dialogHelper","loading","layoutManager","playbackManager","connectionManager","userSettings","embyRouter","globalize","emby-input","paper-icon-button-light","emby-select","material-icons","css!./../formdialog","emby-button"],function(shell,dialogHelper,loading,layoutManager,playbackManager,connectionManager,userSettings,embyRouter,globalize){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onSubmit(e){var panel=parentWithClass(this,"dialog"),playlistId=panel.querySelector("#selectPlaylistToAddTo").value,apiClient=connectionManager.getApiClient(currentServerId);return playlistId?(userSettings.set("playlisteditor-lastplaylistid",playlistId),addToPlaylist(apiClient,panel,playlistId)):createPlaylist(apiClient,panel),e.preventDefault(),!1}function createPlaylist(apiClient,dlg){loading.show();var url=apiClient.getUrl("Playlists",{Name:dlg.querySelector("#txtNewPlaylistName").value,Ids:dlg.querySelector(".fldSelectedItemIds").value||"",userId:apiClient.getCurrentUserId()});apiClient.ajax({type:"POST",url:url,dataType:"json"}).then(function(result){loading.hide();var id=result.Id;dlg.submitted=!0,dialogHelper.close(dlg),redirectToPlaylist(apiClient,id)})}function redirectToPlaylist(apiClient,id){apiClient.getItem(apiClient.getCurrentUserId(),id).then(function(item){embyRouter.showItem(item)})}function addToPlaylist(apiClient,dlg,id){var itemIds=dlg.querySelector(".fldSelectedItemIds").value||"";if("queue"===id)return playbackManager.queue({serverId:apiClient.serverId(),ids:itemIds.split(",")}),dlg.submitted=!0,void dialogHelper.close(dlg);loading.show();var url=apiClient.getUrl("Playlists/"+id+"/Items",{Ids:itemIds,userId:apiClient.getCurrentUserId()});apiClient.ajax({type:"POST",url:url}).then(function(){loading.hide(),dlg.submitted=!0,dialogHelper.close(dlg)})}function triggerChange(select){select.dispatchEvent(new CustomEvent("change",{}))}function populatePlaylists(editorOptions,panel){var select=panel.querySelector("#selectPlaylistToAddTo");loading.hide(),panel.querySelector(".newPlaylistInfo").classList.add("hide");var options={Recursive:!0,IncludeItemTypes:"Playlist",SortBy:"SortName"},apiClient=connectionManager.getApiClient(currentServerId);apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var html="";editorOptions.enableAddToPlayQueue!==!1&&playbackManager.isPlaying()&&(html+='"),html+='",html+=result.Items.map(function(i){return'"}),select.innerHTML=html;var defaultValue=editorOptions.defaultValue;defaultValue||(defaultValue=userSettings.get("playlisteditor-lastplaylistid")||""),select.value="new"===defaultValue?"":defaultValue,select.value||(select.value=""),triggerChange(select),loading.hide()})}function getEditorHtml(){var html="";return html+='
',html+='
',html+='
',html+='
',html+='',html+="
",html+='
',html+='
',html+='',html+="
",html+="
",html+='
',html+='",html+="
",html+='',html+="
",html+="
",html+="
"}function initEditor(content,options,items){if(content.querySelector("#selectPlaylistToAddTo").addEventListener("change",function(){this.value?(content.querySelector(".newPlaylistInfo").classList.add("hide"),content.querySelector("#txtNewPlaylistName").removeAttribute("required")):(content.querySelector(".newPlaylistInfo").classList.remove("hide"),content.querySelector("#txtNewPlaylistName").setAttribute("required","required"))}),content.querySelector("form").addEventListener("submit",onSubmit),content.querySelector(".fldSelectedItemIds",content).value=items.join(","),items.length)content.querySelector(".fldSelectPlaylist").classList.remove("hide"),populatePlaylists(options,content);else{content.querySelector(".fldSelectPlaylist").classList.add("hide");var selectPlaylistToAddTo=content.querySelector("#selectPlaylistToAddTo");selectPlaylistToAddTo.innerHTML="",selectPlaylistToAddTo.value="",triggerChange(selectPlaylistToAddTo)}}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function PlaylistEditor(){}var currentServerId;return PlaylistEditor.prototype.show=function(options){var items=options.items||{};currentServerId=options.serverId;var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="small";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="",title=globalize.translate("sharedcomponents#HeaderAddToPlaylist");return html+='
',html+='',html+='

',html+=title,html+="

",html+="
",html+=getEditorHtml(),dlg.innerHTML=html,initEditor(dlg,options,items),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg).then(function(){return layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),dlg.submitted?Promise.resolve():Promise.reject()})},PlaylistEditor}); \ No newline at end of file +define(["shell","dialogHelper","loading","layoutManager","playbackManager","connectionManager","userSettings","embyRouter","globalize","emby-input","paper-icon-button-light","emby-select","material-icons","css!./../formdialog","emby-button"],function(shell,dialogHelper,loading,layoutManager,playbackManager,connectionManager,userSettings,embyRouter,globalize){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onSubmit(e){var panel=parentWithClass(this,"dialog"),playlistId=panel.querySelector("#selectPlaylistToAddTo").value,apiClient=connectionManager.getApiClient(currentServerId);return playlistId?(userSettings.set("playlisteditor-lastplaylistid",playlistId),addToPlaylist(apiClient,panel,playlistId)):createPlaylist(apiClient,panel),e.preventDefault(),!1}function createPlaylist(apiClient,dlg){loading.show();var url=apiClient.getUrl("Playlists",{Name:dlg.querySelector("#txtNewPlaylistName").value,Ids:dlg.querySelector(".fldSelectedItemIds").value||"",userId:apiClient.getCurrentUserId()});apiClient.ajax({type:"POST",url:url,dataType:"json"}).then(function(result){loading.hide();var id=result.Id;dlg.submitted=!0,dialogHelper.close(dlg),redirectToPlaylist(apiClient,id)})}function redirectToPlaylist(apiClient,id){apiClient.getItem(apiClient.getCurrentUserId(),id).then(function(item){embyRouter.showItem(item)})}function addToPlaylist(apiClient,dlg,id){var itemIds=dlg.querySelector(".fldSelectedItemIds").value||"";if("queue"===id)return playbackManager.queue({serverId:apiClient.serverId(),ids:itemIds.split(",")}),dlg.submitted=!0,void dialogHelper.close(dlg);loading.show();var url=apiClient.getUrl("Playlists/"+id+"/Items",{Ids:itemIds,userId:apiClient.getCurrentUserId()});apiClient.ajax({type:"POST",url:url}).then(function(){loading.hide(),dlg.submitted=!0,dialogHelper.close(dlg)})}function triggerChange(select){select.dispatchEvent(new CustomEvent("change",{}))}function populatePlaylists(editorOptions,panel){var select=panel.querySelector("#selectPlaylistToAddTo");loading.hide(),panel.querySelector(".newPlaylistInfo").classList.add("hide");var options={Recursive:!0,IncludeItemTypes:"Playlist",SortBy:"SortName",EnableTotalRecordCount:!1},apiClient=connectionManager.getApiClient(currentServerId);apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var html="";editorOptions.enableAddToPlayQueue!==!1&&playbackManager.isPlaying()&&(html+='"),html+='",html+=result.Items.map(function(i){return'"}),select.innerHTML=html;var defaultValue=editorOptions.defaultValue;defaultValue||(defaultValue=userSettings.get("playlisteditor-lastplaylistid")||""),select.value="new"===defaultValue?"":defaultValue,select.value||(select.value=""),triggerChange(select),loading.hide()})}function getEditorHtml(){var html="";return html+='
',html+='
',html+='
',html+='
',html+='',html+="
",html+='
',html+='
',html+='',html+="
",html+="
",html+='
',html+='",html+="
",html+='',html+="
",html+="
",html+="
"}function initEditor(content,options,items){if(content.querySelector("#selectPlaylistToAddTo").addEventListener("change",function(){this.value?(content.querySelector(".newPlaylistInfo").classList.add("hide"),content.querySelector("#txtNewPlaylistName").removeAttribute("required")):(content.querySelector(".newPlaylistInfo").classList.remove("hide"),content.querySelector("#txtNewPlaylistName").setAttribute("required","required"))}),content.querySelector("form").addEventListener("submit",onSubmit),content.querySelector(".fldSelectedItemIds",content).value=items.join(","),items.length)content.querySelector(".fldSelectPlaylist").classList.remove("hide"),populatePlaylists(options,content);else{content.querySelector(".fldSelectPlaylist").classList.add("hide");var selectPlaylistToAddTo=content.querySelector("#selectPlaylistToAddTo");selectPlaylistToAddTo.innerHTML="",selectPlaylistToAddTo.value="",triggerChange(selectPlaylistToAddTo)}}function centerFocus(elem,horiz,on){require(["scrollHelper"],function(scrollHelper){var fn=on?"on":"off";scrollHelper.centerFocus[fn](elem,horiz)})}function PlaylistEditor(){}var currentServerId;return PlaylistEditor.prototype.show=function(options){var items=options.items||{};currentServerId=options.serverId;var dialogOptions={removeOnClose:!0,scrollY:!1};layoutManager.tv?dialogOptions.size="fullscreen":dialogOptions.size="small";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog");var html="",title=globalize.translate("sharedcomponents#HeaderAddToPlaylist");return html+='
',html+='',html+='

',html+=title,html+="

",html+="
",html+=getEditorHtml(),dlg.innerHTML=html,initEditor(dlg,options,items),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!0),dialogHelper.open(dlg).then(function(){return layoutManager.tv&¢erFocus(dlg.querySelector(".formDialogContent"),!1,!1),dlg.submitted?Promise.resolve():Promise.reject()})},PlaylistEditor}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/scroller/smoothscroller.js b/dashboard-ui/bower_components/emby-webcomponents/scroller/smoothscroller.js index 915f77317f..9f619fe54f 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/scroller/smoothscroller.js +++ b/dashboard-ui/bower_components/emby-webcomponents/scroller/smoothscroller.js @@ -1 +1 @@ -define(["browser","layoutManager","dom","focusManager","scrollStyles"],function(browser,layoutManager,dom,focusManager){"use strict";function type(value){return null==value?String(value):"object"==typeof value||"function"==typeof value?Object.prototype.toString.call(value).match(/\s([a-z]+)/i)[1].toLowerCase()||"object":typeof value}function disableOneEvent(event){event.preventDefault(),event.stopPropagation(),this.removeEventListener(event.type,disableOneEvent)}function within(number,min,max){return numbermax?max:number}var dragMouseEvents=["mousemove","mouseup"],dragTouchEvents=["touchmove","touchend"],wheelEvent=document.implementation.hasFeature("Event.wheel","3.0")?"wheel":"mousewheel",interactiveElements=["INPUT","SELECT","TEXTAREA"],abs=Math.abs,sqrt=Math.sqrt,pow=Math.pow,round=Math.round,max=Math.max,scrollerFactory=(Math.min,function(frame,options){function sibling(n,elem){for(var matched=[];n;n=n.nextSibling)1===n.nodeType&&n!==elem&&matched.push(n);return matched}function ensureSizeInfo(){if(requiresReflow){requiresReflow=!1,frameSize=o.horizontal?frame.offsetWidth:frame.offsetHeight;var slideeSize=o.scrollWidth||Math.max(slideeElement[o.horizontal?"offsetWidth":"offsetHeight"],slideeElement[o.horizontal?"scrollWidth":"scrollHeight"]);self._pos.end=max(slideeSize-frameSize,0)}}function load(isInit){if(requiresReflow=!0,!isInit){ensureSizeInfo();var pos=self._pos;self.slideTo(within(pos.dest,pos.start,pos.end))}}function initFrameResizeObserver(){var observerOptions={};self.frameResizeObserver=new ResizeObserver(onResize,observerOptions),self.frameResizeObserver.observe(frame)}function nativeScrollTo(container,pos,immediate){!immediate&&container.scrollTo?o.horizontal?container.scrollTo(pos,0):container.scrollTo(0,pos):o.horizontal?container.scrollLeft=Math.round(pos):container.scrollTop=Math.round(pos)}function setStyleProperty(elem,name,value,speed,resetTransition){(resetTransition||browser.edge)&&(elem.style.transition="none",void elem.offsetWidth),elem.style.transition="transform "+speed+"ms ease-out",elem.style[name]=value}function renderAnimate(){var speed=o.speed;animation.immediate&&(speed=o.immediateSpeed||50),o.horizontal?setStyleProperty(slideeElement,"transform","translateX("+-round(animation.to)+"px)",speed):setStyleProperty(slideeElement,"transform","translateY("+-round(animation.to)+"px)",speed),self._pos.cur=animation.to,o.dispatchScrollEvent&&frame.dispatchEvent(new CustomEvent("scroll",{bubbles:!0,cancelable:!1}))}function getBoundingClientRect(elem){return elem.getBoundingClientRect?elem.getBoundingClientRect():{top:0,left:0}}function dragInitSlidee(event){var isTouch="touchstart"===event.type;if(!(dragging.init||!isTouch&&isInteractive(event.target))&&(isTouch?o.touchDragging:o.mouseDragging&&event.which<2)){isTouch||event.preventDefault(),dragging.released=0,dragging.init=0,dragging.source=event.target,dragging.touch=isTouch;var pointer=isTouch?event.touches[0]:event;dragging.initX=pointer.pageX,dragging.initY=pointer.pageY,dragging.initPos=self._pos.cur,dragging.start=+new Date,dragging.time=0,dragging.path=0,dragging.delta=0,dragging.locked=0,dragging.pathToLock=isTouch?30:10,transform&&(isTouch?dragTouchEvents.forEach(function(eventName){dom.addEventListener(document,eventName,dragHandler,{passive:!0})}):dragMouseEvents.forEach(function(eventName){dom.addEventListener(document,eventName,dragHandler,{passive:!0})}))}}function dragHandler(event){dragging.released="mouseup"===event.type||"touchend"===event.type;var pointer=dragging.touch?event[dragging.released?"changedTouches":"touches"][0]:event;if(dragging.pathX=pointer.pageX-dragging.initX,dragging.pathY=pointer.pageY-dragging.initY,dragging.path=sqrt(pow(dragging.pathX,2)+pow(dragging.pathY,2)),dragging.delta=o.horizontal?dragging.pathX:dragging.pathY,dragging.released||!(dragging.path<1)){if(!dragging.init){if(dragging.pathabs(dragging.pathY):abs(dragging.pathX)dragging.pathToLock&&(dragging.locked=1,dragging.source.addEventListener("click",disableOneEvent)),dragging.released&&dragEnd(),self.slideTo(round(dragging.initPos-dragging.delta))}}function dragEnd(){dragging.released=!0,dragTouchEvents.forEach(function(eventName){dom.removeEventListener(document,eventName,dragHandler,{passive:!0})}),dragMouseEvents.forEach(function(eventName){dom.removeEventListener(document,eventName,dragHandler,{passive:!0})}),setTimeout(function(){dragging.source.removeEventListener("click",disableOneEvent)}),dragging.init=0}function isInteractive(element){for(;element;){if(interactiveElements.indexOf(element.tagName)!==-1)return!0;element=element.parentNode}return!1}function normalizeWheelDelta(event){return scrolling.curDelta=(o.horizontal?event.deltaY||event.deltaX:event.deltaY)||-event.wheelDelta,transform&&(scrolling.curDelta/=1===event.deltaMode?3:100),scrolling.curDelta}function scrollHandler(event){ensureSizeInfo();var pos=self._pos;if(o.scrollBy&&pos.start!==pos.end){var delta=normalizeWheelDelta(event);transform?(delta>0&&pos.destpos.start,self.slideBy(o.scrollBy*delta)):(isSmoothScrollSupported&&(delta*=12),o.horizontal?nativeScrollElement.scrollLeft+=delta:nativeScrollElement.scrollTop+=delta)}}function onResize(){load(!1)}function resetScroll(){o.horizontal?this.scrollLeft=0:this.scrollTop=0}function onFrameClick(e){if(1===e.which){var focusableParent=focusManager.focusableParent(e.target);focusableParent&&focusableParent!==document.activeElement&&focusableParent.focus()}}var o=Object.assign({},{slidee:null,horizontal:!1,mouseWheel:!0,scrollBy:0,dragSource:null,mouseDragging:1,touchDragging:1,swingSpeed:.2,dragThreshold:3,intervactive:null,speed:0},options),isSmoothScrollSupported="scrollBehavior"in document.documentElement.style,browserSupportsAnimation=!!browser.animate;isSmoothScrollSupported&&browser.firefox?options.enableNativeScroll=!0:options.requireAnimation&&browserSupportsAnimation?options.enableNativeScroll=!1:layoutManager.tv&&browserSupportsAnimation||(options.enableNativeScroll=!0);var self=this;self.options=o;var slideeElement=o.slidee?o.slidee:sibling(frame.firstChild)[0];self._pos={start:0,center:0,end:0,cur:0,dest:0};var transform=!options.enableNativeScroll,scrollSource=frame,dragSourceElement=o.dragSource?o.dragSource:frame,animation={},dragging={released:1},scrolling={last:0,delta:0,resetTime:200};self.initialized=0,self.slidee=slideeElement,self.options=o,self.dragging=dragging;var nativeScrollElement=frame,requiresReflow=!0,frameSize=0;self.reload=function(){load()},self.slideTo=function(newPos,immediate,fullItemPos){ensureSizeInfo();var pos=self._pos;if(newPos=within(newPos,pos.start,pos.end),!transform)return void nativeScrollTo(nativeScrollElement,newPos,immediate);animation.from=pos.cur,animation.to=newPos,animation.immediate=immediate||dragging.init||!o.speed;var now=(new Date).getTime();o.autoImmediate&&!animation.immediate&&now-(animation.lastAnimate||0)<=50&&(animation.immediate=!0),!animation.immediate&&o.skipSlideToWhenVisible&&fullItemPos&&fullItemPos.isVisible||newPos!==pos.dest&&(pos.dest=newPos,renderAnimate(animation),animation.lastAnimate=now)};self.getPos=function(item){var scrollElement=transform?slideeElement:nativeScrollElement,slideeOffset=getBoundingClientRect(scrollElement),itemOffset=getBoundingClientRect(item),offset=(o.horizontal?slideeOffset.left:slideeOffset.top,o.horizontal?slideeOffset.right:slideeOffset.bottom,o.horizontal?itemOffset.left-slideeOffset.left:itemOffset.top-slideeOffset.top),size=o.horizontal?itemOffset.width:itemOffset.height;size||0===size||(size=item[o.horizontal?"offsetWidth":"offsetHeight"]);var centerOffset=o.centerOffset||0;transform||(centerOffset=0,offset+=o.horizontal?nativeScrollElement.scrollLeft:nativeScrollElement.scrollTop),ensureSizeInfo();var currentStart=self._pos.cur,currentEnd=currentStart+frameSize,isVisible=offset>=currentStart&&offset+size<=currentEnd;return{start:offset,center:offset+centerOffset-frameSize/2+size/2,end:offset-frameSize+size,size:size,isVisible:isVisible}},self.getCenterPosition=function(item){ensureSizeInfo();var pos=self.getPos(item);return within(pos.center,pos.start,pos.end)},self.destroy=function(){return dom.removeEventListener(window,"resize",onResize,{passive:!0}),self.frameResizeObserver&&(self.frameResizeObserver.disconnect(),self.frameResizeObserver=null),dom.removeEventListener(frame,"scroll",resetScroll,{passive:!0}),dom.removeEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0}),dom.removeEventListener(dragSourceElement,"touchstart",dragInitSlidee,{passive:!0}),dom.removeEventListener(frame,"click",onFrameClick,{passive:!0,capture:!0}),dom.removeEventListener(dragSourceElement,"mousedown",dragInitSlidee,{}),self.initialized=0,self},self.getScrollPosition=function(){return transform?self._pos.cur:o.horizontal?nativeScrollElement.scrollLeft:nativeScrollElement.scrollTop},self.init=function(){if(!self.initialized)return transform?(frame.style.overflow="hidden",slideeElement.style["will-change"]="transform",slideeElement.style.transition="transform "+o.speed+"ms ease-out",o.horizontal?slideeElement.classList.add("animatedScrollX"):slideeElement.classList.add("animatedScrollY")):o.horizontal?layoutManager.desktop?nativeScrollElement.classList.add("smoothScrollX"):nativeScrollElement.classList.add("hiddenScrollX"):layoutManager.desktop?nativeScrollElement.classList.add("smoothScrollY"):nativeScrollElement.classList.add("hiddenScrollY"),(transform||layoutManager.tv)&&dom.addEventListener(dragSourceElement,"mousedown",dragInitSlidee,{}),transform?(dom.addEventListener(dragSourceElement,"touchstart",dragInitSlidee,{passive:!0}),window.ResizeObserver?initFrameResizeObserver():o.scrollWidth||dom.addEventListener(window,"resize",onResize,{passive:!0}),o.horizontal||dom.addEventListener(frame,"scroll",resetScroll,{passive:!0}),o.mouseWheel&&dom.addEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0})):o.horizontal&&o.mouseWheel&&dom.addEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0}),dom.addEventListener(frame,"click",onFrameClick,{passive:!0,capture:!0}),self.initialized=1,load(!0),self}});return scrollerFactory.prototype.slideBy=function(delta,immediate){delta&&this.slideTo(this._pos.dest+delta,immediate)},scrollerFactory.prototype.to=function(location,item,immediate){if("boolean"===type(item)&&(immediate=item,item=void 0),void 0===item)this.slideTo(this._pos[location],immediate);else{var itemPos=this.getPos(item);itemPos&&this.slideTo(itemPos[location],immediate,itemPos)}},scrollerFactory.prototype.toStart=function(item,immediate){this.to("start",item,immediate)},scrollerFactory.prototype.toEnd=function(item,immediate){this.to("end",item,immediate)},scrollerFactory.prototype.toCenter=function(item,immediate){this.to("center",item,immediate)},scrollerFactory.create=function(frame,options){var instance=new scrollerFactory(frame,options);return Promise.resolve(instance)},scrollerFactory}); \ No newline at end of file +define(["browser","layoutManager","dom","focusManager","ResizeObserver","scrollStyles"],function(browser,layoutManager,dom,focusManager,ResizeObserver){"use strict";function type(value){return null==value?String(value):"object"==typeof value||"function"==typeof value?Object.prototype.toString.call(value).match(/\s([a-z]+)/i)[1].toLowerCase()||"object":typeof value}function disableOneEvent(event){event.preventDefault(),event.stopPropagation(),this.removeEventListener(event.type,disableOneEvent)}function within(number,min,max){return numbermax?max:number}var dragMouseEvents=["mousemove","mouseup"],dragTouchEvents=["touchmove","touchend"],wheelEvent=document.implementation.hasFeature("Event.wheel","3.0")?"wheel":"mousewheel",interactiveElements=["INPUT","SELECT","TEXTAREA"],abs=Math.abs,sqrt=Math.sqrt,pow=Math.pow,round=Math.round,max=Math.max,scrollerFactory=(Math.min,function(frame,options){function sibling(n,elem){for(var matched=[];n;n=n.nextSibling)1===n.nodeType&&n!==elem&&matched.push(n);return matched}function ensureSizeInfo(){requiresReflow&&(requiresReflow=!1,frameSize=o.horizontal?frame.offsetWidth:frame.offsetHeight,slideeSize=o.scrollWidth||Math.max(slideeElement[o.horizontal?"offsetWidth":"offsetHeight"],slideeElement[o.horizontal?"scrollWidth":"scrollHeight"]),self._pos.end=max(slideeSize-frameSize,0))}function load(isInit){if(requiresReflow=!0,!isInit){ensureSizeInfo();var pos=self._pos;self.slideTo(within(pos.dest,pos.start,pos.end))}}function initFrameResizeObserver(){var observerOptions={};self.frameResizeObserver=new ResizeObserver(onResize,observerOptions),self.frameResizeObserver.observe(frame)}function nativeScrollTo(container,pos,immediate){!immediate&&container.scrollTo?o.horizontal?container.scrollTo(pos,0):container.scrollTo(0,pos):o.horizontal?container.scrollLeft=Math.round(pos):container.scrollTop=Math.round(pos)}function setStyleProperty(elem,name,value,speed,resetTransition){(resetTransition||browser.edge)&&(elem.style.transition="none",void elem.offsetWidth),elem.style.transition="transform "+speed+"ms ease-out",elem.style[name]=value}function renderAnimate(){var speed=o.speed;animation.immediate&&(speed=o.immediateSpeed||50),o.horizontal?setStyleProperty(slideeElement,"transform","translateX("+-round(animation.to)+"px)",speed):setStyleProperty(slideeElement,"transform","translateY("+-round(animation.to)+"px)",speed),self._pos.cur=animation.to,o.dispatchScrollEvent&&frame.dispatchEvent(new CustomEvent("scroll",{bubbles:!0,cancelable:!1}))}function getBoundingClientRect(elem){return elem.getBoundingClientRect?elem.getBoundingClientRect():{top:0,left:0}}function dragInitSlidee(event){var isTouch="touchstart"===event.type;if(!(dragging.init||!isTouch&&isInteractive(event.target))&&(isTouch?o.touchDragging:o.mouseDragging&&event.which<2)){isTouch||event.preventDefault(),dragging.released=0,dragging.init=0,dragging.source=event.target,dragging.touch=isTouch;var pointer=isTouch?event.touches[0]:event;dragging.initX=pointer.pageX,dragging.initY=pointer.pageY,dragging.initPos=self._pos.cur,dragging.start=+new Date,dragging.time=0,dragging.path=0,dragging.delta=0,dragging.locked=0,dragging.pathToLock=isTouch?30:10,transform&&(isTouch?dragTouchEvents.forEach(function(eventName){dom.addEventListener(document,eventName,dragHandler,{passive:!0})}):dragMouseEvents.forEach(function(eventName){dom.addEventListener(document,eventName,dragHandler,{passive:!0})}))}}function dragHandler(event){dragging.released="mouseup"===event.type||"touchend"===event.type;var pointer=dragging.touch?event[dragging.released?"changedTouches":"touches"][0]:event;if(dragging.pathX=pointer.pageX-dragging.initX,dragging.pathY=pointer.pageY-dragging.initY,dragging.path=sqrt(pow(dragging.pathX,2)+pow(dragging.pathY,2)),dragging.delta=o.horizontal?dragging.pathX:dragging.pathY,dragging.released||!(dragging.path<1)){if(!dragging.init){if(dragging.pathabs(dragging.pathY):abs(dragging.pathX)dragging.pathToLock&&(dragging.locked=1,dragging.source.addEventListener("click",disableOneEvent)),dragging.released&&dragEnd(),self.slideTo(round(dragging.initPos-dragging.delta))}}function dragEnd(){dragging.released=!0,dragTouchEvents.forEach(function(eventName){dom.removeEventListener(document,eventName,dragHandler,{passive:!0})}),dragMouseEvents.forEach(function(eventName){dom.removeEventListener(document,eventName,dragHandler,{passive:!0})}),setTimeout(function(){dragging.source.removeEventListener("click",disableOneEvent)}),dragging.init=0}function isInteractive(element){for(;element;){if(interactiveElements.indexOf(element.tagName)!==-1)return!0;element=element.parentNode}return!1}function normalizeWheelDelta(event){return scrolling.curDelta=(o.horizontal?event.deltaY||event.deltaX:event.deltaY)||-event.wheelDelta,transform&&(scrolling.curDelta/=1===event.deltaMode?3:100),scrolling.curDelta}function scrollHandler(event){ensureSizeInfo();var pos=self._pos;if(o.scrollBy&&pos.start!==pos.end){var delta=normalizeWheelDelta(event);transform?(delta>0&&pos.destpos.start,self.slideBy(o.scrollBy*delta)):(isSmoothScrollSupported&&(delta*=12),o.horizontal?nativeScrollElement.scrollLeft+=delta:nativeScrollElement.scrollTop+=delta)}}function onResize(){load(!1)}function resetScroll(){o.horizontal?this.scrollLeft=0:this.scrollTop=0}function onFrameClick(e){if(1===e.which){var focusableParent=focusManager.focusableParent(e.target);focusableParent&&focusableParent!==document.activeElement&&focusableParent.focus()}}var o=Object.assign({},{slidee:null,horizontal:!1,mouseWheel:!0,scrollBy:0,dragSource:null,mouseDragging:1,touchDragging:1,swingSpeed:.2,dragThreshold:3,intervactive:null,speed:0},options),isSmoothScrollSupported="scrollBehavior"in document.documentElement.style,browserSupportsAnimation=!!browser.animate;isSmoothScrollSupported&&browser.firefox?options.enableNativeScroll=!0:options.requireAnimation&&browserSupportsAnimation?options.enableNativeScroll=!1:layoutManager.tv&&browserSupportsAnimation||(options.enableNativeScroll=!0);var self=this;self.options=o;var slideeElement=o.slidee?o.slidee:sibling(frame.firstChild)[0];self._pos={start:0,center:0,end:0,cur:0,dest:0};var transform=!options.enableNativeScroll,scrollSource=frame,dragSourceElement=o.dragSource?o.dragSource:frame,animation={},dragging={released:1},scrolling={last:0,delta:0,resetTime:200};self.initialized=0,self.slidee=slideeElement,self.options=o,self.dragging=dragging;var nativeScrollElement=frame,requiresReflow=!0,frameSize=0,slideeSize=0;self.reload=function(){load()},self.slideTo=function(newPos,immediate,fullItemPos){ensureSizeInfo();var pos=self._pos;if(newPos=within(newPos,pos.start,pos.end),!transform)return void nativeScrollTo(nativeScrollElement,newPos,immediate);animation.from=pos.cur,animation.to=newPos,animation.immediate=immediate||dragging.init||!o.speed;var now=(new Date).getTime();o.autoImmediate&&!animation.immediate&&now-(animation.lastAnimate||0)<=50&&(animation.immediate=!0),!animation.immediate&&o.skipSlideToWhenVisible&&fullItemPos&&fullItemPos.isVisible||newPos!==pos.dest&&(pos.dest=newPos,renderAnimate(animation),animation.lastAnimate=now)};self.getPos=function(item){var scrollElement=transform?slideeElement:nativeScrollElement,slideeOffset=getBoundingClientRect(scrollElement),itemOffset=getBoundingClientRect(item),offset=(o.horizontal?slideeOffset.left:slideeOffset.top,o.horizontal?slideeOffset.right:slideeOffset.bottom,o.horizontal?itemOffset.left-slideeOffset.left:itemOffset.top-slideeOffset.top),size=o.horizontal?itemOffset.width:itemOffset.height;size||0===size||(size=item[o.horizontal?"offsetWidth":"offsetHeight"]);var centerOffset=o.centerOffset||0;transform||(centerOffset=0,offset+=o.horizontal?nativeScrollElement.scrollLeft:nativeScrollElement.scrollTop),ensureSizeInfo();var currentStart=self._pos.cur,currentEnd=currentStart+frameSize,isVisible=offset>=currentStart&&offset+size<=currentEnd;return{start:offset,center:offset+centerOffset-frameSize/2+size/2,end:offset-frameSize+size,size:size,isVisible:isVisible}},self.getCenterPosition=function(item){ensureSizeInfo();var pos=self.getPos(item);return within(pos.center,pos.start,pos.end)},self.destroy=function(){return self.frameResizeObserver&&(self.frameResizeObserver.disconnect(),self.frameResizeObserver=null),dom.removeEventListener(frame,"scroll",resetScroll,{passive:!0}),dom.removeEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0}),dom.removeEventListener(dragSourceElement,"touchstart",dragInitSlidee,{passive:!0}),dom.removeEventListener(frame,"click",onFrameClick,{passive:!0,capture:!0}),dom.removeEventListener(dragSourceElement,"mousedown",dragInitSlidee,{}),self.initialized=0,self},self.getScrollPosition=function(){return transform?self._pos.cur:o.horizontal?nativeScrollElement.scrollLeft:nativeScrollElement.scrollTop},self.getScrollSize=function(){return transform?slideeSize:o.horizontal?nativeScrollElement.scrollWidth:nativeScrollElement.scrollHeight},self.init=function(){if(!self.initialized)return transform?(frame.style.overflow="hidden",slideeElement.style["will-change"]="transform",slideeElement.style.transition="transform "+o.speed+"ms ease-out",o.horizontal?slideeElement.classList.add("animatedScrollX"):slideeElement.classList.add("animatedScrollY")):o.horizontal?layoutManager.desktop?nativeScrollElement.classList.add("smoothScrollX"):nativeScrollElement.classList.add("hiddenScrollX"):layoutManager.desktop?nativeScrollElement.classList.add("smoothScrollY"):nativeScrollElement.classList.add("hiddenScrollY"),(transform||layoutManager.tv)&&dom.addEventListener(dragSourceElement,"mousedown",dragInitSlidee,{}),initFrameResizeObserver(),transform?(dom.addEventListener(dragSourceElement,"touchstart",dragInitSlidee,{passive:!0}),o.horizontal||dom.addEventListener(frame,"scroll",resetScroll,{passive:!0}),o.mouseWheel&&dom.addEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0})):o.horizontal&&o.mouseWheel&&dom.addEventListener(scrollSource,wheelEvent,scrollHandler,{passive:!0}),dom.addEventListener(frame,"click",onFrameClick,{passive:!0,capture:!0}),self.initialized=1,load(!0),self}});return scrollerFactory.prototype.slideBy=function(delta,immediate){delta&&this.slideTo(this._pos.dest+delta,immediate)},scrollerFactory.prototype.to=function(location,item,immediate){if("boolean"===type(item)&&(immediate=item,item=void 0),void 0===item)this.slideTo(this._pos[location],immediate);else{var itemPos=this.getPos(item);itemPos&&this.slideTo(itemPos[location],immediate,itemPos)}},scrollerFactory.prototype.toStart=function(item,immediate){this.to("start",item,immediate)},scrollerFactory.prototype.toEnd=function(item,immediate){this.to("end",item,immediate)},scrollerFactory.prototype.toCenter=function(item,immediate){this.to("center",item,immediate)},scrollerFactory.create=function(frame,options){var instance=new scrollerFactory(frame,options);return Promise.resolve(instance)},scrollerFactory}); \ No newline at end of file diff --git a/dashboard-ui/bower_components/emby-webcomponents/shortcuts.js b/dashboard-ui/bower_components/emby-webcomponents/shortcuts.js index 2f2db0ab02..ccef88a2b3 100644 --- a/dashboard-ui/bower_components/emby-webcomponents/shortcuts.js +++ b/dashboard-ui/bower_components/emby-webcomponents/shortcuts.js @@ -1 +1 @@ -define(["playbackManager","inputManager","connectionManager","embyRouter","globalize","loading","dom","recordingHelper"],function(playbackManager,inputManager,connectionManager,embyRouter,globalize,loading,dom,recordingHelper){"use strict";function playAllFromHere(card,serverId,queue){for(var parent=card.parentNode,className=card.classList.length?"."+card.classList[0]:"",cards=parent.querySelectorAll(className+"[data-id]"),ids=[],foundCard=!1,i=0,length=cards.length;i0},ResizeObserverController.prototype.connect_=function(){isBrowser&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),mutationObserverSupported?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},ResizeObserverController.prototype.disconnect_=function(){isBrowser&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},ResizeObserverController.prototype.onTransitionEnd_=function(ref){var propertyName=ref.propertyName,isReflowProperty=transitionKeys.some(function(key){return!!~propertyName.indexOf(key)});isReflowProperty&&this.refresh()},ResizeObserverController.getInstance=function(){return this.instance_||(this.instance_=new ResizeObserverController),this.instance_},ResizeObserverController.instance_=null;var defineConfigurable=function(target,props){for(var i=0,list=Object.keys(props);i0};var observers="undefined"!=typeof WeakMap?new WeakMap:new MapShim,ResizeObserver$1=function(callback){if(!(this instanceof ResizeObserver$1))throw new TypeError("Cannot call a class as a function");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var controller=ResizeObserverController.getInstance(),observer=new ResizeObserverSPI(callback,controller,this);observers.set(this,observer)};["observe","unobserve","disconnect"].forEach(function(method){ResizeObserver$1.prototype[method]=function(){return(ref=observers.get(this))[method].apply(ref,arguments);var ref}});var index=function(){return"undefined"!=typeof ResizeObserver?ResizeObserver:ResizeObserver$1}();return index}); \ No newline at end of file diff --git a/dashboard-ui/css/librarymenu.css b/dashboard-ui/css/librarymenu.css index 33701aaf45..167248bf43 100644 --- a/dashboard-ui/css/librarymenu.css +++ b/dashboard-ui/css/librarymenu.css @@ -1 +1 @@ -.libraryMenuButtonText,.viewMenuLink{vertical-align:middle;text-decoration:none}.libraryPage{padding-top:4.6em!important}.libraryPage:not(.noSecondaryNavPage){padding-top:6.6em!important}.absolutePageTabContent{position:absolute;left:0;right:0;bottom:0;z-index:1;margin:0!important;top:6.5em!important;-webkit-transition:-webkit-transform .2s ease-out;-o-transition:transform .2s ease-out;transition:transform .2s ease-out}.pageTabContent:not(.is-active){display:none!important}.sidebarDivider{height:1px;background:#eaeaea;margin:.5em 0}.headerUserImage{-webkit-background-size:contain;background-size:contain;background-repeat:no-repeat;background-position:center center;-webkit-border-radius:100em;border-radius:100em;vertical-align:middle;display:inline-block}.headerUserButtonRound img{-webkit-border-radius:100em;border-radius:100em}.headerButton{-webkit-flex-shrink:0;flex-shrink:0}.hideMainDrawer .mainDrawerButton{display:none}.libraryMenuButtonText{display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;padding-left:0!important;cursor:default;white-space:nowrap;overflow:hidden;-o-text-overflow:ellipsis;text-overflow:ellipsis;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin:0 0 0 .5em;-webkit-flex-shrink:1;flex-shrink:1;color:#ddd}.skinHeader{position:fixed;right:0;left:0;z-index:999;top:0;border:0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;background-color:#101010;color:#ddd}.hiddenViewMenuBar .skinHeader{display:none}.headerLeft,.headerRight{display:-webkit-box;display:-webkit-flex;-webkit-box-align:center}.headerTop{padding:.3em 0}.headerLeft{display:flex;-webkit-align-items:center;align-items:center}@supports (backdrop-filter:blur(1.5em)) or (-webkit-backdrop-filter:blur(1.5em)){.skinHeader-blurred{background:rgba(24,24,24,.7);-webkit-backdrop-filter:blur(1.5em);backdrop-filter:blur(1.5em)}}.headerTabs{width:100%;text-align:center;font-size:92%}.skinHeader.semiTransparent{background-color:rgba(15,15,15,.3)}.viewMenuLink{color:#eee!important;padding:.5em;display:inline-block}.viewMenuLink:hover{color:#fff}.viewMenuLink img{height:1.5em;vertical-align:top}.headerRight{display:flex;-webkit-align-items:center;align-items:center;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;-webkit-box-pack:end;-webkit-justify-content:flex-end;justify-content:flex-end}.selectedMediaFolder{background-color:#f2f2f2!important}.sidebarLink{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;text-decoration:none;color:#111!important;font-weight:400!important;vertical-align:middle;padding:1em 0 1em 2.4em}.sidebarLink:hover{background:#f2f2f2}.sidebarLink.selectedSidebarLink{background:#f2f2f2!important}.sidebarLinkIcon{margin-right:1em;color:#444!important}.sidebarHeader{padding-left:1.4em;margin:1.2em 0 .7em;color:#555}body:not(.dashboardDocument) .btnNotifications{display:none!important}.darkDrawer{background-color:#181818!important}.darkDrawer .sidebarLinkIcon{color:#bbb!important}.darkDrawer .sidebarLink{color:#fff!important}.darkDrawer .sidebarHeader{color:#bbb!important}.darkDrawer .sidebarDivider{background:#262626!important}.darkDrawer .sidebarLink:hover{background:#252528}.darkDrawer .selectedMediaFolder,.darkDrawer .sidebarLink.selectedSidebarLink{background:#252528!important;color:#52B54B!important}body:not(.dashboardDocument) .headerAppsButton{display:none}.mainDrawer-scrollContainer{padding-bottom:10vh}.dashboardDocument .skinBody{-webkit-transition:left ease-in-out .3s,padding ease-in-out .3s;-o-transition:left ease-in-out .3s,padding ease-in-out .3s;transition:left ease-in-out .3s,padding ease-in-out .3s;position:absolute;top:0;right:0;bottom:0;left:0}@media all and (max-width:40em){.sidebarLink{font-size:110%}}@media all and (min-width:40em){.dashboardDocument .adminDrawerLogo,.dashboardDocument .mainDrawerButton,.dashboardDocument .tmla-mask{display:none!important}.dashboardDocument .headerTabs{width:auto;padding-left:21em;text-align:left!important}.dashboardDocument .sidebarLink{padding-top:.7em;padding-bottom:.7em}.dashboardDocument .mainDrawer{z-index:inherit!important;left:0!important;top:0!important;-webkit-transform:none!important;transform:none!important;font-size:92%;width:20.07em!important}.dashboardDocument .mainDrawer-scrollContainer{margin-top:4.3em!important}.dashboardDocument.withTallToolbar .mainDrawer-scrollContainer{margin-top:7em!important}.dashboardDocument .skinBody{left:18.5em}.dashboardDocument .darkDrawer{background-color:rgba(28,28,31,.3)!important}}@media all and (min-width:84em){.libraryDocument .headerTabs{-webkit-align-self:center;align-self:center;width:auto;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;font-size:inherit;margin-top:-3.34em;position:relative;top:-.39em}.headerTop{padding:.9em 0}.libraryPage:not(.noSecondaryNavPage){padding-top:5em!important}.absolutePageTabContent{top:4.8em!important}} \ No newline at end of file +.libraryMenuButtonText,.viewMenuLink{vertical-align:middle;text-decoration:none}.libraryPage{padding-top:4.6em!important}.libraryPage:not(.noSecondaryNavPage){padding-top:6.6em!important}.absolutePageTabContent{position:absolute;left:0;right:0;bottom:0;z-index:1;margin:0!important;top:6.5em!important;-webkit-transition:-webkit-transform .2s ease-out;-o-transition:transform .2s ease-out;transition:transform .2s ease-out}.pageTabContent:not(.is-active){display:none!important}.sidebarDivider{height:1px;background:#eaeaea;margin:.5em 0}.headerUserImage{-webkit-background-size:contain;background-size:contain;background-repeat:no-repeat;background-position:center center;-webkit-border-radius:100em;border-radius:100em;vertical-align:middle;display:inline-block}.headerUserButtonRound img{-webkit-border-radius:100em;border-radius:100em}.headerButton{-webkit-flex-shrink:0;flex-shrink:0}.hideMainDrawer .mainDrawerButton{display:none}.libraryMenuButtonText{display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;padding-left:0!important;cursor:default;white-space:nowrap;overflow:hidden;-o-text-overflow:ellipsis;text-overflow:ellipsis;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin:0 0 0 .5em;-webkit-flex-shrink:1;flex-shrink:1;color:#ddd}.skinHeader{position:fixed;right:0;left:0;z-index:999;top:0;border:0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;background-color:#101010;color:#ddd}.hiddenViewMenuBar .skinHeader{display:none}.headerLeft,.headerRight{display:-webkit-box;display:-webkit-flex;-webkit-box-align:center}.headerTop{padding:.3em 0}.headerLeft{display:flex;-webkit-align-items:center;align-items:center}@supports (backdrop-filter:blur(1.5em)) or (-webkit-backdrop-filter:blur(1.5em)){.skinHeader-blurred{background:rgba(24,24,24,.7);-webkit-backdrop-filter:blur(1.5em);backdrop-filter:blur(1.5em)}}.headerTabs{width:100%;text-align:center;font-size:92%}.skinHeader.semiTransparent{background-color:rgba(15,15,15,.3)}.viewMenuLink{color:#eee!important;padding:.5em;display:inline-block}.viewMenuLink:hover{color:#fff}.viewMenuLink img{height:1.5em;vertical-align:top}.headerRight{display:flex;-webkit-align-items:center;align-items:center;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;-webkit-box-pack:end;-webkit-justify-content:flex-end;justify-content:flex-end}.selectedMediaFolder{background-color:#f2f2f2!important}.sidebarLink{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;text-decoration:none;color:#111!important;font-weight:400!important;vertical-align:middle;padding:1em 0 1em 2.4em}.sidebarLink:hover{background:#f2f2f2}.sidebarLink.selectedSidebarLink{background:#f2f2f2!important}.sidebarLinkIcon{margin-right:1em;color:#444!important}.sidebarHeader{padding-left:1.4em;margin:1.2em 0 .7em;color:#555}body:not(.dashboardDocument) .btnNotifications{display:none!important}.darkDrawer{background-color:#181818!important}.darkDrawer .sidebarLinkIcon{color:#bbb!important}.darkDrawer .sidebarLink{color:#fff!important}.darkDrawer .sidebarHeader{color:#bbb!important}.darkDrawer .sidebarDivider{background:#262626!important}.darkDrawer .sidebarLink:hover{background:#252528}.darkDrawer .selectedMediaFolder,.darkDrawer .sidebarLink.selectedSidebarLink{background:#252528!important;color:#52B54B!important}body:not(.dashboardDocument) .headerAppsButton{display:none}.mainDrawer-scrollContainer{padding-bottom:10vh}.dashboardDocument .skinBody{-webkit-transition:left ease-in-out .3s,padding ease-in-out .3s;-o-transition:left ease-in-out .3s,padding ease-in-out .3s;transition:left ease-in-out .3s,padding ease-in-out .3s;position:absolute;top:0;right:0;bottom:0;left:0}@media all and (max-width:40em){.sidebarLink{font-size:110%}}@media all and (min-width:40em){.dashboardDocument .adminDrawerLogo,.dashboardDocument .mainDrawerButton,.dashboardDocument .tmla-mask{display:none!important}.dashboardDocument .sidebarLink{padding-top:.7em;padding-bottom:.7em}.dashboardDocument .mainDrawer{z-index:inherit!important;left:0!important;top:0!important;-webkit-transform:none!important;transform:none!important;font-size:92%;width:20.07em!important}.dashboardDocument .mainDrawer-scrollContainer{margin-top:4.3em!important}.dashboardDocument.withTallToolbar .mainDrawer-scrollContainer{margin-top:7em!important}.dashboardDocument .skinBody{left:18.5em}.dashboardDocument .darkDrawer{background-color:rgba(28,28,31,.3)!important}}@media all and (min-width:84em){.headerTabs{-webkit-align-self:center;align-self:center;width:auto;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;font-size:inherit;margin-top:-3.34em;position:relative;top:-.39em}.headerTop{padding:.9em 0}.libraryPage:not(.noSecondaryNavPage){padding-top:5em!important}.absolutePageTabContent{top:4.8em!important}} \ No newline at end of file diff --git a/dashboard-ui/itemdetails.html b/dashboard-ui/itemdetails.html index 34b19d23a7..d10a042abc 100644 --- a/dashboard-ui/itemdetails.html +++ b/dashboard-ui/itemdetails.html @@ -172,7 +172,6 @@ ${HeaderAwardsAndReviews}
-

diff --git a/dashboard-ui/scripts/autobackdrops.js b/dashboard-ui/scripts/autobackdrops.js index 04a608fd55..c43e1f4541 100644 --- a/dashboard-ui/scripts/autobackdrops.js +++ b/dashboard-ui/scripts/autobackdrops.js @@ -1 +1 @@ -define(["backdrop","appStorage"],function(backdrop,appStorage){"use strict";function enabled(){var apiClient=window.ApiClient;if(!apiClient)return!1;var userId=apiClient.getCurrentUserId(),val=appStorage.getItem("enableBackdrops-"+userId);return"1"==val}function getBackdropItemIds(apiClient,userId,types,parentId){var key="backdrops2_"+userId+(types||"")+(parentId||""),data=cache[key];if(data)return console.log("Found backdrop id list in cache. Key: "+key),data=JSON.parse(data),Promise.resolve(data);var options={SortBy:"IsFavoriteOrLiked,Random",Limit:20,Recursive:!0,IncludeItemTypes:types,ImageTypes:"Backdrop",ParentId:parentId};return apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var images=result.Items.map(function(i){return{Id:i.Id,tag:i.BackdropImageTags[0],ServerId:i.ServerId}});return cache[key]=JSON.stringify(images),images})}function showBackdrop(type,parentId){var apiClient=window.ApiClient;apiClient&&getBackdropItemIds(apiClient,apiClient.getCurrentUserId(),type,parentId).then(function(images){images.length?backdrop.setBackdrops(images.map(function(i){return i.BackdropImageTags=[i.tag],i})):backdrop.clear()})}var cache={};pageClassOn("pagebeforeshow","page",function(){var page=this;if(!page.classList.contains("selfBackdropPage"))if(page.classList.contains("backdropPage"))if(enabled()){var type=page.getAttribute("data-backdroptype"),parentId=page.classList.contains("globalBackdropPage")?"":LibraryMenu.getTopParentId();showBackdrop(type,parentId)}else page.classList.remove("backdropPage"),backdrop.clear();else backdrop.clear()})}); \ No newline at end of file +define(["backdrop","appStorage"],function(backdrop,appStorage){"use strict";function enabled(){var apiClient=window.ApiClient;if(!apiClient)return!1;var userId=apiClient.getCurrentUserId(),val=appStorage.getItem("enableBackdrops-"+userId);return"1"==val}function getBackdropItemIds(apiClient,userId,types,parentId){var key="backdrops2_"+userId+(types||"")+(parentId||""),data=cache[key];if(data)return console.log("Found backdrop id list in cache. Key: "+key),data=JSON.parse(data),Promise.resolve(data);var options={SortBy:"IsFavoriteOrLiked,Random",Limit:20,Recursive:!0,IncludeItemTypes:types,ImageTypes:"Backdrop",ParentId:parentId,EnableTotalRecordCount:!1};return apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var images=result.Items.map(function(i){return{Id:i.Id,tag:i.BackdropImageTags[0],ServerId:i.ServerId}});return cache[key]=JSON.stringify(images),images})}function showBackdrop(type,parentId){var apiClient=window.ApiClient;apiClient&&getBackdropItemIds(apiClient,apiClient.getCurrentUserId(),type,parentId).then(function(images){images.length?backdrop.setBackdrops(images.map(function(i){return i.BackdropImageTags=[i.tag],i})):backdrop.clear()})}var cache={};pageClassOn("pagebeforeshow","page",function(){var page=this;if(!page.classList.contains("selfBackdropPage"))if(page.classList.contains("backdropPage"))if(enabled()){var type=page.getAttribute("data-backdroptype"),parentId=page.classList.contains("globalBackdropPage")?"":LibraryMenu.getTopParentId();showBackdrop(type,parentId)}else page.classList.remove("backdropPage"),backdrop.clear();else backdrop.clear()})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/episodes.js b/dashboard-ui/scripts/episodes.js new file mode 100644 index 0000000000..039d6f00bc --- /dev/null +++ b/dashboard-ui/scripts/episodes.js @@ -0,0 +1 @@ +define(["loading","events","libraryBrowser","imageLoader","listView","cardBuilder","emby-itemscontainer"],function(loading,events,libraryBrowser,imageLoader,listView,cardBuilder){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SeriesSortName,SortName",SortOrder:"Ascending",IncludeItemTypes:"Episode",Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,UserData",IsMissing:!1,IsVirtualUnaired:!1,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||"Poster"},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("episodes")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){loading.show();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");html="List"==viewStyle?listView.getListViewHtml({items:result.Items,sortBy:query.SortBy,showParentTitle:!0}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,showParentTitle:!0,scalable:!0,cardLayout:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!0,scalable:!0,overlayPlayButton:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i"}function renderSeriesTimerSchedule(page,seriesTimerId){ApiClient.getLiveTvTimers({UserId:ApiClient.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",SortBy:"StartDate",EnableTotalRecordCount:!1,EnableUserData:!1,SeriesTimerId:seriesTimerId,Fields:"ChannelInfo"}).then(function(result){result.Items.length&&result.Items[0].SeriesTimerId!=seriesTimerId&&(result.Items=[]);var html=getProgramScheduleHtml(result.Items),scheduleTab=page.querySelector(".seriesTimerSchedule");scheduleTab.innerHTML=html,imageLoader.lazyChildren(scheduleTab)})}function renderSeriesTimerEditor(page,item,user){if("SeriesTimer"===item.Type){if(!user.Policy.EnableLiveTvManagement)return page.querySelector(".seriesTimerScheduleSection").classList.add("hide"),void page.querySelector(".btnCancelSeriesTimer").classList.add("hide");require(["seriesRecordingEditor"],function(seriesRecordingEditor){seriesRecordingEditor.embed(item,ApiClient.serverId(),{context:page.querySelector(".seriesRecordingEditor")})}),page.querySelector(".seriesTimerScheduleSection").classList.remove("hide"),page.querySelector(".btnCancelSeriesTimer").classList.remove("hide"),renderSeriesTimerSchedule(page,item.Id)}}function reloadPlayButtons(page,item){var canPlay=!1;if("Program"==item.Type){var now=new Date;now>=datetime.parseISO8601Date(item.StartDate,!0)&&now0)}else hideAll(page,"btnPlay"),hideAll(page,"btnResume"),hideAll(page,"btnInstantMix"),hideAll(page,"btnShuffle");return canPlay}function reloadFromItem(page,params,item){currentItem=item;var context=params.context;LibraryBrowser.renderName(item,page.querySelector(".itemName"),!1,context),LibraryBrowser.renderParentName(item,page.querySelector(".parentName"),context),libraryMenu.setTitle(""),Dashboard.getCurrentUser().then(function(user){window.scrollTo(0,0),renderSeriesTimerEditor(page,item,user),renderImage(page,item,user),renderLogo(page,item,ApiClient),setInitialCollapsibleState(page,item,context,user),renderDetails(page,item,context),dom.getWindowSize().innerWidth>=800?backdrop.setBackdrops([item]):backdrop.clear(),LibraryBrowser.renderDetailPageBackdrop(page,item,imageLoader),libraryMenu.setTransparentMenu(!0);var canPlay=reloadPlayButtons(page,item),hasAnyButton=canPlay;item.LocalTrailerCount||item.RemoteTrailers&&item.RemoteTrailers.length?(hideAll(page,"btnPlayTrailer",!0),hasAnyButton=!0):hideAll(page,"btnPlayTrailer"),item.CanDelete&&!item.IsFolder?(hideAll(page,"btnDeleteItem",!0),hasAnyButton=!0):hideAll(page,"btnDeleteItem"),renderSyncLocalContainer(page,params,user,item),hasAnyButton||"Program"!==item.Type?hideAll(page,"mainDetailButtons",!0):hideAll(page,"mainDetailButtons"),showRecordingFields(page,item,user);var groupedVersions=(item.MediaSources||[]).filter(function(g){return"Grouping"==g.Type});user.Policy.IsAdministrator&&groupedVersions.length?page.querySelector(".splitVersionContainer").classList.remove("hide"):page.querySelector(".splitVersionContainer").classList.add("hide");var commands=itemContextMenu.getCommands(getContextMenuOptions(item,user));commands.length?hideAll(page,"btnMoreCommands",!0):hideAll(page,"btnMoreCommands");var itemBirthday=page.querySelector("#itemBirthday");if("Person"==item.Type&&item.PremiereDate)try{var birthday=datetime.parseISO8601Date(item.PremiereDate,!0).toDateString();itemBirthday.classList.remove("hide"),itemBirthday.innerHTML=globalize.translate("BirthDateValue").replace("{0}",birthday)}catch(err){itemBirthday.classList.add("hide")}else itemBirthday.classList.add("hide");var itemDeathDate=page.querySelector("#itemDeathDate");if("Person"==item.Type&&item.EndDate)try{var deathday=datetime.parseISO8601Date(item.EndDate,!0).toDateString();itemDeathDate.classList.remove("hide"),itemDeathDate.innerHTML=globalize.translate("DeathDateValue").replace("{0}",deathday)}catch(err){itemDeathDate.classList.add("hide")}var itemBirthLocation=page.querySelector("#itemBirthLocation");if("Person"==item.Type&&item.ProductionLocations&&item.ProductionLocations.length){var gmap=''+item.ProductionLocations[0]+"";itemBirthLocation.classList.remove("hide"),itemBirthLocation.innerHTML=globalize.translate("BirthPlaceValue").replace("{0}",gmap)}else itemBirthLocation.classList.add("hide")}),setPeopleHeader(page,item),page.dispatchEvent(new CustomEvent("displayingitem",{detail:{item:item,context:context},bubbles:!0})),loading.hide()}function logoImageUrl(item,apiClient,options){return options=options||{},options.type="Logo",item.ImageTags&&item.ImageTags.Logo?(options.tag=item.ImageTags.Logo,apiClient.getScaledImageUrl(item.Id,options)):item.ParentLogoImageTag?(options.tag=item.ParentLogoImageTag,apiClient.getScaledImageUrl(item.ParentLogoItemId,options)):null}function renderLogo(page,item,apiClient){var url=logoImageUrl(item,apiClient,{maxWidth:300}),detailLogo=page.querySelector(".detailLogo");url?(detailLogo.classList.remove("hide"),detailLogo.classList.add("lazy"),detailLogo.setAttribute("data-src",url),imageLoader.lazyImage(detailLogo)):detailLogo.classList.add("hide")}function showRecordingFields(page,item,user){if(!currentRecordingFields){var recordingFieldsElement=page.querySelector(".recordingFields");"Program"==item.Type&&user.Policy.EnableLiveTvManagement?require(["recordingFields"],function(recordingFields){currentRecordingFields=new recordingFields({parent:recordingFieldsElement,programId:item.Id,serverId:item.ServerId}),recordingFieldsElement.classList.remove("hide")}):(recordingFieldsElement.classList.add("hide"),recordingFieldsElement.innerHTML="")}}function renderLinks(linksElem,item){var links=[];if(item.HomePageUrl&&links.push(''+globalize.translate("ButtonWebsite")+""),item.ExternalUrls)for(var i=0,length=item.ExternalUrls.length;i'+url.Name+"")}if(links.length){var html=links.join('');linksElem.innerHTML=html,linksElem.classList.remove("hide")}else linksElem.classList.add("hide")}function renderImage(page,item,user){var container=page.querySelector(".detailImageContainer");LibraryBrowser.renderDetailImage(page,container,item,user.Policy.IsAdministrator&&"Photo"!=item.MediaType,null,imageLoader,indicators)}function refreshDetailImageUserData(elem,item){var detailImageProgressContainer=elem.querySelector(".detailImageProgressContainer");detailImageProgressContainer.innerHTML=indicators.getProgressBarHtml(item)}function refreshImage(page,item,user){refreshDetailImageUserData(page.querySelector(".detailImageContainer"),item)}function setPeopleHeader(page,item){"Audio"==item.MediaType||"MusicAlbum"==item.Type||"Book"==item.MediaType||"Photo"==item.MediaType?page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderPeople"):page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderCastAndCrew")}function renderNextUp(page,item,user){var section=page.querySelector(".nextUpSection");return"Series"!=item.Type?void section.classList.add("hide"):void ApiClient.getNextUpEpisodes({SeriesId:item.Id,UserId:user.Id}).then(function(result){result.Items.length?section.classList.remove("hide"):section.classList.add("hide");var html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(!1),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,overlayText:!0,lazy:!0,overlayPlayButton:!0}),itemsContainer=section.querySelector(".nextUpItems");itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer)})}function setInitialCollapsibleState(page,item,context,user){page.querySelector(".collectionItems").innerHTML="","TvChannel"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderChannelGuide(page,item,user)):"Playlist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderPlaylistItems(page,item,user)):"Studio"==item.Type||"Person"==item.Type||"Genre"==item.Type||"MusicGenre"==item.Type||"GameGenre"==item.Type||"MusicArtist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderItemsByName(page,item,user)):item.IsFolder||"Episode"==item.Type&&item.SeasonId&&item.SeriesId?("BoxSet"==item.Type&&page.querySelector("#childrenCollapsible").classList.add("hide"),renderChildren(page,item)):page.querySelector("#childrenCollapsible").classList.add("hide"),"Series"==item.Type&&renderSeriesSchedule(page,item,user),"Series"==item.Type?renderNextUp(page,item,user):page.querySelector(".nextUpSection").classList.add("hide"),item.MediaSources&&item.MediaSources.length&&renderMediaSources(page,user,item),renderScenes(page,item),item.SpecialFeatureCount&&0!=item.SpecialFeatureCount&&"Series"!=item.Type?(page.querySelector("#specialsCollapsible").classList.remove("hide"),renderSpecials(page,item,user,6)):page.querySelector("#specialsCollapsible").classList.add("hide"),item.People&&item.People.length?(page.querySelector("#castCollapsible").classList.remove("hide"),renderCast(page,item,context,enableScrollX()?null:12)):page.querySelector("#castCollapsible").classList.add("hide"),item.PartCount&&item.PartCount>1?(page.querySelector("#additionalPartsCollapsible").classList.remove("hide"),renderAdditionalParts(page,item,user)):page.querySelector("#additionalPartsCollapsible").classList.add("hide"),page.querySelector("#themeSongsCollapsible").classList.add("hide"),page.querySelector("#themeVideosCollapsible").classList.add("hide"),"MusicAlbum"==item.Type?renderMusicVideos(page,item,user):page.querySelector("#musicVideosCollapsible").classList.add("hide"),renderThemeMedia(page,item,user),enableScrollX()?renderCriticReviews(page,item):renderCriticReviews(page,item,1)}function renderOverview(elems,item){for(var i=0,length=elems.length;i'+text+"
":'
'+text+"
"}).join("");return view.querySelector(".mediaInfoIcons").innerHTML=html,html}function renderPhotoInfo(page,item){var html="",attributes=[];if(item.CameraMake&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraMake"),item.CameraMake)),item.CameraModel&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraModel"),item.CameraModel)),item.Altitude&&attributes.push(createAttribute(globalize.translate("MediaInfoAltitude"),item.Altitude.toFixed(1))),item.Aperture&&attributes.push(createAttribute(globalize.translate("MediaInfoAperture"),"F"+item.Aperture.toFixed(1))),item.ExposureTime){var val=1/item.ExposureTime;attributes.push(createAttribute(globalize.translate("MediaInfoExposureTime"),"1/"+val+" s"))}item.FocalLength&&attributes.push(createAttribute(globalize.translate("MediaInfoFocalLength"),item.FocalLength.toFixed(1)+" mm")),item.ImageOrientation,item.IsoSpeedRating&&attributes.push(createAttribute(globalize.translate("MediaInfoIsoSpeedRating"),item.IsoSpeedRating)),item.Latitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLatitude"),item.Latitude.toFixed(1))),item.Longitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLongitude"),item.Longitude.toFixed(1))),item.ShutterSpeed&&attributes.push(createAttribute(globalize.translate("MediaInfoShutterSpeed"),item.ShutterSpeed)),item.Software&&attributes.push(createAttribute(globalize.translate("MediaInfoSoftware"),item.Software)),html+=attributes.join("
"),page.querySelector(".photoInfoContent").innerHTML=html}function getArtistLinksHtml(artists,context){for(var html=[],i=0,length=artists.length;i'+artist.Name+"")}return html=html.join(" / "),1==artists.length?globalize.translate("ValueArtist",html):artists.length>1?globalize.translate("ValueArtists",html):html}function enableScrollX(){return browserInfo.mobile&&screen.availWidth<=1e3}function getPortraitShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowPortrait":"portrait"}function getSquareShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowSquare":"square"}function getThumbShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowBackdrop":"backdrop"}function renderMoreFromItems(page,item){var moreFromSection=page.querySelector("#moreFromSection");if(moreFromSection)return"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length?void ApiClient.getItems(Dashboard.getCurrentUserId(),{IncludeItemTypes:"MusicAlbum",ArtistIds:item.AlbumArtists[0].Id,Recursive:!0,ExcludeItemIds:item.Id}).then(function(result){if(!result.Items.length)return void moreFromSection.classList.add("hide");moreFromSection.classList.remove("hide"),moreFromSection.querySelector(".moreFromHeader").innerHTML=globalize.translate("MoreFromValue",item.AlbumArtists[0].Name);var html="";html+=enableScrollX()?'
':'
';var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),supportsImageAnalysis=appHost.supports("imageanalysis");supportsImageAnalysis=!1,html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!supportsImageAnalysis,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
";var similarContent=page.querySelector("#moreFromItems");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)}):void moreFromSection.classList.add("hide")}function renderSimilarItems(page,item,context){var similarCollapsible=page.querySelector("#similarCollapsible");if(similarCollapsible){if("Movie"!=item.Type&&"Trailer"!=item.Type&&"Series"!=item.Type&&"Program"!=item.Type&&"Recording"!=item.Type&&"Game"!=item.Type&&"MusicAlbum"!=item.Type&&"MusicArtist"!=item.Type&&"ChannelVideoItem"!=item.Type)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),options={userId:Dashboard.getCurrentUserId(),limit:"MusicAlbum"==item.Type||"MusicArtist"==item.Type?8:10,fields:"PrimaryImageAspectRatio,UserData,CanDelete"};"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length&&(options.ExcludeArtistIds=item.AlbumArtists[0].Id),enableScrollX()&&(options.limit=12),ApiClient.getSimilarItems(item.Id,options).then(function(result){if(!result.Items.length)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var html="";html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis&&("MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type);cardLayout=!1,html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!cardLayout,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,context:context,lazy:!0,showDetailsMenu:!0,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis}),html+="
";var similarContent=similarCollapsible.querySelector(".similarContent");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)})}}function renderSeriesAirTime(page,item,isStatic){var seriesAirTime=page.querySelector("#seriesAirTime");if("Series"!=item.Type)return void seriesAirTime.classList.add("hide");var html="";if(item.AirDays&&item.AirDays.length&&(html+=7==item.AirDays.length?"daily":item.AirDays.map(function(a){return a+"s"}).join(",")),item.AirTime&&(html+=" at "+item.AirTime),item.Studios.length)if(isStatic)html+=" on "+item.Studios[0].Name;else{var context=inferContext(item),href=embyRouter.getRouteUrl(item.Studios[0],{context:context,itemType:"Studio"});html+=' on '+item.Studios[0].Name+""}html?(html=("Ended"==item.Status?"Aired ":"Airs ")+html,seriesAirTime.innerHTML=html,seriesAirTime.classList.remove("hide")):seriesAirTime.classList.add("hide")}function renderTags(page,item){var itemTags=page.querySelector(".itemTags");if(item.Tags&&item.Tags.length){for(var html="",i=0,length=item.Tags.length;i'+item.Tags[i]+"
";itemTags.innerHTML=html,itemTags.classList.remove("hide")}else itemTags.classList.add("hide")}function getEpisodesFunction(seriesId,query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getEpisodes(seriesId,query)}}function getAlbumSongsFunction(query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getItems(Dashboard.getCurrentUserId(),query)}}function renderChildren(page,item){_childrenItemsFunction=null;var fields="ItemCounts,PrimaryImageAspectRatio,BasicSyncInfo,CanDelete",query={ParentId:item.Id,Fields:fields};"BoxSet"!==item.Type&&(query.SortBy="SortName");var promise,userId=Dashboard.getCurrentUserId();"Series"==item.Type?promise=ApiClient.getSeasons(item.Id,{userId:userId,Fields:fields}):"Season"==item.Type?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields})):"Episode"==item.Type&&item.SeriesId&&item.SeasonId?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields})):"MusicAlbum"==item.Type&&(_childrenItemsFunction=getAlbumSongsFunction(query)),promise=promise||ApiClient.getItems(Dashboard.getCurrentUserId(),query),promise.then(function(result){var html="",scrollX=!1,isList=!1,scrollClass="hiddenScrollX",childrenItemsContainer=page.querySelector(".childrenItemsContainer");if("MusicAlbum"==item.Type)html=listView.getListViewHtml({items:result.Items,smallIcon:!0,showIndex:!0,index:"disc",showIndexNumber:!0,playFromHere:!0,action:"playallfromhere",image:!1,artist:"auto",containerAlbumArtist:item.AlbumArtist,addToListButton:!0}),isList=!0;else if("Series"==item.Type)scrollX=enableScrollX(),html=cardBuilder.getCardsHtml({items:result.Items,shape:getPortraitShape(),showTitle:!0,centerText:!0,lazy:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX});else if("Season"==item.Type||"Episode"==item.Type){if("Episode"===item.Type&&childrenItemsContainer.classList.add("darkScroller"),scrollX="Episode"==item.Type,browser.touch||(scrollClass="smoothScrollX"),result.Items.length<2&&"Episode"===item.Type)return;html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(scrollX),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,playFromHere:!0,overlayText:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX,includeParentInfoInTitle:!1})}else"GameSystem"==item.Type&&(html=cardBuilder.getCardsHtml({items:result.Items,shape:"auto",showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0}));if("BoxSet"!==item.Type&&page.querySelector("#childrenCollapsible").classList.remove("hide"),scrollX?(childrenItemsContainer.classList.add(scrollClass),childrenItemsContainer.classList.remove("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list")):(childrenItemsContainer.classList.remove("hiddenScrollX"),childrenItemsContainer.classList.remove("smoothScrollX"),isList?(childrenItemsContainer.classList.add("vertical-list"),childrenItemsContainer.classList.remove("vertical-wrap")):(childrenItemsContainer.classList.add("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list"))),childrenItemsContainer.innerHTML=html,imageLoader.lazyChildren(childrenItemsContainer),"BoxSet"==item.Type){var collectionItemTypes=[{name:globalize.translate("HeaderVideos"),mediaType:"Video"},{name:globalize.translate("HeaderSeries"),type:"Series"},{name:globalize.translate("HeaderAlbums"),type:"MusicAlbum"},{name:globalize.translate("HeaderGames"),type:"Game"},{name:globalize.translate("HeaderBooks"),type:"Book"}];renderCollectionItems(page,item,collectionItemTypes,result.Items)}else if("Episode"===item.Type){var card=childrenItemsContainer.querySelector('.card[data-id="'+item.Id+'"]');card&&scrollHelper.toStart(childrenItemsContainer,card.previousSibling||card,!0)}}),"Season"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderEpisodes"):"Episode"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("MoreFromValue",item.SeasonName):"Series"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderSeasons"):"MusicAlbum"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderTracks"):"GameSystem"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderGames"):page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderItems"),"MusicAlbum"==item.Type?page.querySelector(".childrenSectionHeader",page).classList.add("hide"):page.querySelector(".childrenSectionHeader",page).classList.remove("hide")}function renderItemsByName(page,item,user){require("scripts/itembynamedetailpage".split(","),function(){window.ItemsByName.renderItems(page,item)})}function renderPlaylistItems(page,item,user){require("scripts/playlistedit".split(","),function(){PlaylistViewer.render(page,item)})}function renderChannelGuide(page,item,user){require("scripts/livetvchannel,scripts/livetvcomponents,livetvcss".split(","),function(liveTvChannelPage){liveTvChannelPage.renderPrograms(page,item.Id)})}function renderSeriesSchedule(page,item,user){}function inferContext(item){return"Movie"==item.Type||"BoxSet"==item.Type?"movies":"Series"==item.Type||"Season"==item.Type||"Episode"==item.Type?"tvshows":"Game"==item.Type||"GameSystem"==item.Type?"games":"Game"==item.Type||"GameSystem"==item.Type?"games":"MusicArtist"==item.Type||"MusicAlbum"==item.Type?"music":null}function renderStudios(elem,item,isStatic){var context=inferContext(item);if(item.Studios&&item.Studios.length&&"Series"!=item.Type,1)elem.classList.add("hide");else{for(var html="",i=0,length=item.Studios.length;i0&&(html+="  /  "),isStatic)html+=item.Studios[i].Name;else{item.Studios[i].Type="Studio";var href=embyRouter.getRouteUrl(item.Studios[0],{context:context});html+=''+item.Studios[i].Name+""}var translationKey=item.Studios.length>1?"ValueStudios":"ValueStudio";html=globalize.translate(translationKey,html),elem.innerHTML=html,elem.classList.remove("hide")}}function renderGenres(elem,item,limit,isStatic){for(var context=inferContext(item),html="",genres=item.Genres||[],i=0,length=genres.length;i=limit);i++){i>0&&(html+='');var param="Audio"==item.Type||"MusicArtist"==item.Type||"MusicAlbum"==item.Type||"MusicVideo"==item.Type?"musicgenre":"genre";if("Game"==item.MediaType&&(param="gamegenre"),isStatic)html+=genres[i];else{var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;case"music":type="MusicAlbum";break;default:type="Movie"}var url="secondaryitems.html?type="+type+"&"+param+"="+ApiClient.encodeName(genres[i]);html+=''+genres[i]+""}}elem.innerHTML=html}function renderAwardSummary(elem,item){item.AwardSummary?(elem.classList.remove("hide"),elem.innerHTML=globalize.translate("ValueAwards",item.AwardSummary)):elem.classList.add("hide")}function filterItemsByCollectionItemType(items,typeInfo){return items.filter(function(item){return typeInfo.mediaType?item.MediaType==typeInfo.mediaType:item.Type==typeInfo.type})}function renderCollectionItems(page,parentItem,types,items){page.querySelector(".collectionItems").innerHTML="";var i,length;for(i=0,length=types.length;i0}).length});otherTypeItems.length&&renderCollectionItemType(page,parentItem,otherType,otherTypeItems),items.length||renderCollectionItemType(page,parentItem,{name:globalize.translate("HeaderItems")},items)}function renderCollectionItemType(page,parentItem,type,items){var html="";html+='
',html+='
',html+="

",html+=""+type.name+"",html+="

",html+='',html+="
",html+='
'; -var shape="MusicAlbum"==type.type?getSquareShape(!1):getPortraitShape(!1);html+=cardBuilder.getCardsHtml({items:items,shape:shape,showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0,overlayMoreButton:!0,showAddToCollection:!1,showRemoveFromCollection:!0,collectionId:parentItem.Id}),html+="
",html+="
";var collectionItems=page.querySelector(".collectionItems");collectionItems.insertAdjacentHTML("beforeend",html),imageLoader.lazyChildren(collectionItems),collectionItems.querySelector(".btnAddToCollection").addEventListener("click",function(){require(["alert"],function(alert){alert({text:globalize.translate("AddItemToCollectionHelp"),html:globalize.translate("AddItemToCollectionHelp")+'

'+globalize.translate("ButtonLearnMore")+""})})})}function renderUserDataIcons(page,item){for(var userDataIcons=page.querySelectorAll(".userDataIcons"),i=0,length=userDataIcons.length;i',html+='
',null!=review.Score||null!=review.Likes&&(html+=review.Likes?"
":"
"),html+='
',html+='

'+review.Caption+"

";var vals=[];if(review.ReviewerName&&vals.push(review.ReviewerName),review.Publisher&&vals.push(review.Publisher),html+='
'+vals.join(", ")+".",review.Date)try{var date=datetime.toLocaleDateString(datetime.parseISO8601Date(review.Date,!0));html+=''+date+""}catch(error){}html+="
",review.Url&&(html+='"),html+="
",html+="
",html+="
"}limit&&result.TotalRecordCount>limit&&(html+='

");var criticReviewsContent=page.querySelector("#criticReviewsContent");criticReviewsContent.innerHTML=html,enableScrollX()?criticReviewsContent.classList.add("hiddenScrollX"):criticReviewsContent.classList.remove("hiddenScrollX")}function renderThemeMedia(page,item){"SeriesTimer"!==item.Type&&"Timer"!==item.Type&&"Genre"!==item.Type&&"MusicGenre"!==item.Type&&"GameGenre"!==item.Type&&"Studio"!==item.Type&&"Person"!==item.Type&&ApiClient.getThemeMedia(Dashboard.getCurrentUserId(),item.Id,!0).then(function(result){var themeSongs=result.ThemeSongsResult.OwnerId==item.Id?result.ThemeSongsResult.Items:[],themeVideos=result.ThemeVideosResult.OwnerId==item.Id?result.ThemeVideosResult.Items:[];renderThemeSongs(page,themeSongs),renderThemeVideos(page,themeVideos)})}function renderThemeSongs(page,items){if(items.length){page.querySelector("#themeSongsCollapsible").classList.remove("hide");var html=listView.getListViewHtml({items:items});page.querySelector("#themeSongsContent").innerHTML=html}else page.querySelector("#themeSongsCollapsible").classList.add("hide")}function renderThemeVideos(page,items,user){if(items.length){page.querySelector("#themeVideosCollapsible").classList.remove("hide");var themeVideosContent=page.querySelector("#themeVideosContent");themeVideosContent.innerHTML=getVideosHtml(items,user),imageLoader.lazyChildren(themeVideosContent)}else page.querySelector("#themeVideosCollapsible").classList.add("hide")}function renderMusicVideos(page,item,user){ApiClient.getItems(user.Id,{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"MusicVideo",Recursive:!0,Fields:"DateCreated,CanDelete",AlbumIds:item.Id}).then(function(result){if(result.Items.length){page.querySelector("#musicVideosCollapsible").classList.remove("hide");var musicVideosContent=page.querySelector(".musicVideosContent");musicVideosContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(musicVideosContent)}else page.querySelector("#musicVideosCollapsible").classList.add("hide")})}function renderAdditionalParts(page,item,user){ApiClient.getAdditionalVideoParts(user.Id,item.Id).then(function(result){if(result.Items.length){page.querySelector("#additionalPartsCollapsible").classList.remove("hide");var additionalPartsContent=page.querySelector("#additionalPartsContent");additionalPartsContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(additionalPartsContent)}else page.querySelector("#additionalPartsCollapsible").classList.add("hide")})}function renderScenes(page,item){var chapters=item.Chapters||[];if(chapters.length&&!chapters[0].ImageTag&&(chapters=[]),chapters.length){page.querySelector("#scenesCollapsible").classList.remove("hide");var scenesContent=page.querySelector("#scenesContent");enableScrollX()?scenesContent.classList.add("smoothScrollX"):scenesContent.classList.add("vertical-wrap"),require(["chaptercardbuilder"],function(chaptercardbuilder){chaptercardbuilder.buildChapterCards(item,chapters,{itemsContainer:scenesContent,width:400,backdropShape:getThumbShape(),squareShape:getSquareShape()})})}else page.querySelector("#scenesCollapsible").classList.add("hide")}function renderMediaSources(page,user,item){var html=item.MediaSources.map(function(v){return getMediaSourceHtml(user,item,v)}).join('
');item.MediaSources.length>1&&(html="
"+html);var mediaInfoContent=page.querySelector("#mediaInfoContent");mediaInfoContent.innerHTML=html}function getMediaSourceHtml(user,item,version){var html="";version.Name&&item.MediaSources.length>1&&(html+='
'+version.Name+"

");for(var i=0,length=version.MediaStreams.length;i';var displayType=globalize.translate("MediaInfoStreamType"+stream.Type);html+='

'+displayType+"

";var attributes=[];stream.Language&&"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoLanguage"),stream.Language)),stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoCodec"),stream.Codec.toUpperCase())),stream.CodecTag&&attributes.push(createAttribute(globalize.translate("MediaInfoCodecTag"),stream.CodecTag)),null!=stream.IsAVC&&attributes.push(createAttribute("AVC",stream.IsAVC?"Yes":"No")),stream.Profile&&attributes.push(createAttribute(globalize.translate("MediaInfoProfile"),stream.Profile)),stream.Level&&attributes.push(createAttribute(globalize.translate("MediaInfoLevel"),stream.Level)),(stream.Width||stream.Height)&&attributes.push(createAttribute(globalize.translate("MediaInfoResolution"),stream.Width+"x"+stream.Height)),stream.AspectRatio&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoAspectRatio"),stream.AspectRatio)),"Video"==stream.Type&&(null!=stream.IsAnamorphic&&attributes.push(createAttribute(globalize.translate("MediaInfoAnamorphic"),stream.IsAnamorphic?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoInterlaced"),stream.IsInterlaced?"Yes":"No"))),(stream.AverageFrameRate||stream.RealFrameRate)&&attributes.push(createAttribute(globalize.translate("MediaInfoFramerate"),stream.AverageFrameRate||stream.RealFrameRate)),stream.ChannelLayout&&attributes.push(createAttribute(globalize.translate("MediaInfoLayout"),stream.ChannelLayout)),stream.Channels&&attributes.push(createAttribute(globalize.translate("MediaInfoChannels"),stream.Channels+" ch")),stream.BitRate&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoBitrate"),parseInt(stream.BitRate/1e3)+" kbps")),stream.SampleRate&&attributes.push(createAttribute(globalize.translate("MediaInfoSampleRate"),stream.SampleRate+" Hz")),stream.BitDepth&&attributes.push(createAttribute(globalize.translate("MediaInfoBitDepth"),stream.BitDepth+" bit")),stream.PixelFormat&&attributes.push(createAttribute(globalize.translate("MediaInfoPixelFormat"),stream.PixelFormat)),stream.RefFrames&&attributes.push(createAttribute(globalize.translate("MediaInfoRefFrames"),stream.RefFrames)),stream.NalLengthSize&&attributes.push(createAttribute("NAL",stream.NalLengthSize)),"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoDefault"),stream.IsDefault?"Yes":"No")),"Subtitle"==stream.Type&&(attributes.push(createAttribute(globalize.translate("MediaInfoForced"),stream.IsForced?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoExternal"),stream.IsExternal?"Yes":"No"))),"Video"==stream.Type&&version.Timestamp&&attributes.push(createAttribute(globalize.translate("MediaInfoTimestamp"),version.Timestamp)),stream.DisplayTitle&&attributes.push(createAttribute("Title",stream.DisplayTitle)),html+=attributes.join("
"),html+="
"}}if(version.Container&&(html+='
'+globalize.translate("MediaInfoContainer")+''+version.Container+"
"),version.Formats&&version.Formats.length,version.Path&&"Http"!=version.Protocol&&user&&user.Policy.IsAdministrator&&(html+='
'+globalize.translate("MediaInfoPath")+''+version.Path+"
"),version.Size){var size=(version.Size/1048576).toFixed(0);html+='
'+globalize.translate("MediaInfoSize")+''+size+" MB
"}return html}function createAttribute(label,value){return''+label+''+value+""}function getVideosHtml(items,user,limit,moreButtonClass){var html=cardBuilder.getCardsHtml({items:items,shape:"auto",showTitle:!0,action:"play",overlayText:!0,showRuntime:!0});return limit&&items.length>limit&&(html+='

"),html}function renderSpecials(page,item,user,limit){ApiClient.getSpecialFeatures(user.Id,item.Id).then(function(specials){var specialsContent=page.querySelector("#specialsContent");specialsContent.innerHTML=getVideosHtml(specials,user,limit,"moreSpecials"),imageLoader.lazyChildren(specialsContent)})}function renderCast(page,item,context,limit,isStatic){var people=item.People||[],castContent=page.querySelector("#castContent");enableScrollX()?(castContent.classList.add("smoothScrollX"),limit=32):castContent.classList.add("vertical-wrap");var limitExceeded=limit&&people.length>limit;limitExceeded&&(people=people.slice(0),people.length=Math.min(limit,people.length)),require(["peoplecardbuilder"],function(peoplecardbuilder){peoplecardbuilder.buildPeopleCards(people,{itemsContainer:castContent,coverImage:!0,serverId:item.ServerId,width:160,shape:getPortraitShape()})});var morePeopleButton=page.querySelector(".morePeople");morePeopleButton&&(limitExceeded&&!enableScrollX()?morePeopleButton.classList.remove("hide"):morePeopleButton.classList.add("hide"))}function play(startPosition){playbackManager.play({items:[currentItem],startPositionTicks:startPosition})}function splitVersions(page,params){require(["confirm"],function(confirm){confirm("Are you sure you wish to split the media sources into separate items?","Split Media Apart").then(function(){loading.show(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Videos/"+params.id+"/AlternateSources")}).then(function(){loading.hide(),reload(page,params)})})})}function playTrailer(page){playbackManager.playTrailers(currentItem)}function showPlayMenu(item,target){require(["playMenu"],function(playMenu){playMenu.show({item:item,positionTo:target})})}function playCurrentItem(button,mode){var item=currentItem;return"Program"===item.Type?void ApiClient.getLiveTvChannel(item.ChannelId,Dashboard.getCurrentUserId()).then(function(channel){playbackManager.play({items:[channel]})}):void("playmenu"===mode?showPlayMenu(item,button):playbackManager.play({items:[item],startPositionTicks:item.UserData&&"resume"===mode?item.UserData.PlaybackPositionTicks:0}))}function itemDetailPage(){var self=this;self.play=play,self.setInitialCollapsibleState=setInitialCollapsibleState,self.renderDetails=renderDetails,self.renderCriticReviews=renderCriticReviews,self.renderCast=renderCast,self.renderScenes=renderScenes,self.renderMediaSources=renderMediaSources}function onPlayClick(){var mode=this.getAttribute("data-mode");playCurrentItem(this,mode)}function onInstantMixClick(){playbackManager.instantMix(currentItem)}function onShuffleClick(){playbackManager.shuffle(currentItem)}function onDeleteClick(){require(["deleteHelper"],function(deleteHelper){deleteHelper.deleteItem({item:currentItem,navigate:!0})})}function onCancelSeriesTimerClick(){require(["recordingHelper"],function(recordingHelper){recordingHelper.cancelSeriesTimerWithConfirmation(currentItem.Id,currentItem.ServerId).then(function(){Dashboard.navigate("livetv.html")})})}var currentItem,currentRecordingFields,_childrenItemsFunction=null;return window.ItemDetailPage=new itemDetailPage,function(view,params){function onPlayTrailerClick(){playTrailer(view)}function onMoreCommandsClick(){var button=this;connectionManager.getApiClient(currentItem.ServerId).getCurrentUser().then(function(user){itemContextMenu.show(getContextMenuOptions(currentItem,user,button)).then(function(result){result.deleted?embyRouter.goHome():result.updated&&reload(view,params)})})}function editImages(){return new Promise(function(resolve,reject){require(["imageEditor"],function(imageEditor){imageEditor.show({itemId:currentItem.Id,serverId:currentItem.ServerId}).then(resolve,reject)})})}function onWebSocketMessage(e,data){var msg=data;if("UserDataChanged"===msg.MessageType&¤tItem&&msg.Data.UserId==Dashboard.getCurrentUserId()){var key=currentItem.UserData.Key,userData=msg.Data.UserDataList.filter(function(u){return u.Key==key})[0];userData&&(currentItem.UserData=userData,reloadPlayButtons(view,currentItem),Dashboard.getCurrentUser().then(function(user){refreshImage(view,currentItem,user)}))}}var i,length,elems=view.querySelectorAll(".btnPlay");for(i=0,length=elems.length;i"}function renderSeriesTimerSchedule(page,seriesTimerId){ApiClient.getLiveTvTimers({UserId:ApiClient.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",SortBy:"StartDate",EnableTotalRecordCount:!1,EnableUserData:!1,SeriesTimerId:seriesTimerId,Fields:"ChannelInfo"}).then(function(result){result.Items.length&&result.Items[0].SeriesTimerId!=seriesTimerId&&(result.Items=[]);var html=getProgramScheduleHtml(result.Items),scheduleTab=page.querySelector(".seriesTimerSchedule");scheduleTab.innerHTML=html,imageLoader.lazyChildren(scheduleTab)})}function renderSeriesTimerEditor(page,item,user){if("SeriesTimer"===item.Type){if(!user.Policy.EnableLiveTvManagement)return page.querySelector(".seriesTimerScheduleSection").classList.add("hide"),void page.querySelector(".btnCancelSeriesTimer").classList.add("hide");require(["seriesRecordingEditor"],function(seriesRecordingEditor){seriesRecordingEditor.embed(item,ApiClient.serverId(),{context:page.querySelector(".seriesRecordingEditor")})}),page.querySelector(".seriesTimerScheduleSection").classList.remove("hide"),page.querySelector(".btnCancelSeriesTimer").classList.remove("hide"),renderSeriesTimerSchedule(page,item.Id)}}function reloadPlayButtons(page,item){var canPlay=!1;if("Program"==item.Type){var now=new Date;now>=datetime.parseISO8601Date(item.StartDate,!0)&&now0)}else hideAll(page,"btnPlay"),hideAll(page,"btnResume"),hideAll(page,"btnInstantMix"),hideAll(page,"btnShuffle");return canPlay}function reloadFromItem(page,params,item){currentItem=item;var context=params.context;LibraryBrowser.renderName(item,page.querySelector(".itemName"),!1,context),LibraryBrowser.renderParentName(item,page.querySelector(".parentName"),context),libraryMenu.setTitle(""),Dashboard.getCurrentUser().then(function(user){window.scrollTo(0,0),renderSeriesTimerEditor(page,item,user),renderImage(page,item,user),renderLogo(page,item,ApiClient),setInitialCollapsibleState(page,item,context,user),renderDetails(page,item,context),dom.getWindowSize().innerWidth>=800?backdrop.setBackdrops([item]):backdrop.clear(),LibraryBrowser.renderDetailPageBackdrop(page,item,imageLoader),libraryMenu.setTransparentMenu(!0);var canPlay=reloadPlayButtons(page,item),hasAnyButton=canPlay;item.LocalTrailerCount||item.RemoteTrailers&&item.RemoteTrailers.length?(hideAll(page,"btnPlayTrailer",!0),hasAnyButton=!0):hideAll(page,"btnPlayTrailer"),item.CanDelete&&!item.IsFolder?(hideAll(page,"btnDeleteItem",!0),hasAnyButton=!0):hideAll(page,"btnDeleteItem"),renderSyncLocalContainer(page,params,user,item),hasAnyButton||"Program"!==item.Type?hideAll(page,"mainDetailButtons",!0):hideAll(page,"mainDetailButtons"),showRecordingFields(page,item,user);var groupedVersions=(item.MediaSources||[]).filter(function(g){return"Grouping"==g.Type});user.Policy.IsAdministrator&&groupedVersions.length?page.querySelector(".splitVersionContainer").classList.remove("hide"):page.querySelector(".splitVersionContainer").classList.add("hide");var commands=itemContextMenu.getCommands(getContextMenuOptions(item,user));commands.length?hideAll(page,"btnMoreCommands",!0):hideAll(page,"btnMoreCommands");var itemBirthday=page.querySelector("#itemBirthday");if("Person"==item.Type&&item.PremiereDate)try{var birthday=datetime.parseISO8601Date(item.PremiereDate,!0).toDateString();itemBirthday.classList.remove("hide"),itemBirthday.innerHTML=globalize.translate("BirthDateValue").replace("{0}",birthday)}catch(err){itemBirthday.classList.add("hide")}else itemBirthday.classList.add("hide");var itemDeathDate=page.querySelector("#itemDeathDate");if("Person"==item.Type&&item.EndDate)try{var deathday=datetime.parseISO8601Date(item.EndDate,!0).toDateString();itemDeathDate.classList.remove("hide"),itemDeathDate.innerHTML=globalize.translate("DeathDateValue").replace("{0}",deathday)}catch(err){itemDeathDate.classList.add("hide")}var itemBirthLocation=page.querySelector("#itemBirthLocation");if("Person"==item.Type&&item.ProductionLocations&&item.ProductionLocations.length){var gmap=''+item.ProductionLocations[0]+"";itemBirthLocation.classList.remove("hide"),itemBirthLocation.innerHTML=globalize.translate("BirthPlaceValue").replace("{0}",gmap)}else itemBirthLocation.classList.add("hide")}),setPeopleHeader(page,item),page.dispatchEvent(new CustomEvent("displayingitem",{detail:{item:item,context:context},bubbles:!0})),loading.hide()}function logoImageUrl(item,apiClient,options){return options=options||{},options.type="Logo",item.ImageTags&&item.ImageTags.Logo?(options.tag=item.ImageTags.Logo,apiClient.getScaledImageUrl(item.Id,options)):item.ParentLogoImageTag?(options.tag=item.ParentLogoImageTag,apiClient.getScaledImageUrl(item.ParentLogoItemId,options)):null}function renderLogo(page,item,apiClient){var url=logoImageUrl(item,apiClient,{maxWidth:300}),detailLogo=page.querySelector(".detailLogo");url?(detailLogo.classList.remove("hide"),detailLogo.classList.add("lazy"),detailLogo.setAttribute("data-src",url),imageLoader.lazyImage(detailLogo)):detailLogo.classList.add("hide")}function showRecordingFields(page,item,user){if(!currentRecordingFields){var recordingFieldsElement=page.querySelector(".recordingFields");"Program"==item.Type&&user.Policy.EnableLiveTvManagement?require(["recordingFields"],function(recordingFields){currentRecordingFields=new recordingFields({parent:recordingFieldsElement,programId:item.Id,serverId:item.ServerId}),recordingFieldsElement.classList.remove("hide")}):(recordingFieldsElement.classList.add("hide"),recordingFieldsElement.innerHTML="")}}function renderLinks(linksElem,item){var links=[];if(item.HomePageUrl&&links.push(''+globalize.translate("ButtonWebsite")+""),item.ExternalUrls)for(var i=0,length=item.ExternalUrls.length;i'+url.Name+"")}if(links.length){var html=links.join('');linksElem.innerHTML=html,linksElem.classList.remove("hide")}else linksElem.classList.add("hide")}function renderImage(page,item,user){var container=page.querySelector(".detailImageContainer");LibraryBrowser.renderDetailImage(page,container,item,user.Policy.IsAdministrator&&"Photo"!=item.MediaType,null,imageLoader,indicators)}function refreshDetailImageUserData(elem,item){var detailImageProgressContainer=elem.querySelector(".detailImageProgressContainer");detailImageProgressContainer.innerHTML=indicators.getProgressBarHtml(item)}function refreshImage(page,item,user){refreshDetailImageUserData(page.querySelector(".detailImageContainer"),item)}function setPeopleHeader(page,item){"Audio"==item.MediaType||"MusicAlbum"==item.Type||"Book"==item.MediaType||"Photo"==item.MediaType?page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderPeople"):page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderCastAndCrew")}function renderNextUp(page,item,user){var section=page.querySelector(".nextUpSection");return"Series"!=item.Type?void section.classList.add("hide"):void ApiClient.getNextUpEpisodes({SeriesId:item.Id,UserId:user.Id}).then(function(result){result.Items.length?section.classList.remove("hide"):section.classList.add("hide");var html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(!1),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,overlayText:!0,lazy:!0,overlayPlayButton:!0}),itemsContainer=section.querySelector(".nextUpItems");itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer)})}function setInitialCollapsibleState(page,item,context,user){page.querySelector(".collectionItems").innerHTML="","TvChannel"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderChannelGuide(page,item,user)):"Playlist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderPlaylistItems(page,item,user)):"Studio"==item.Type||"Person"==item.Type||"Genre"==item.Type||"MusicGenre"==item.Type||"GameGenre"==item.Type||"MusicArtist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderItemsByName(page,item,user)):item.IsFolder||"Episode"==item.Type&&item.SeasonId&&item.SeriesId?("BoxSet"==item.Type&&page.querySelector("#childrenCollapsible").classList.add("hide"),renderChildren(page,item)):page.querySelector("#childrenCollapsible").classList.add("hide"),"Series"==item.Type&&renderSeriesSchedule(page,item,user),"Series"==item.Type?renderNextUp(page,item,user):page.querySelector(".nextUpSection").classList.add("hide"),item.MediaSources&&item.MediaSources.length&&renderMediaSources(page,user,item),renderScenes(page,item),item.SpecialFeatureCount&&0!=item.SpecialFeatureCount&&"Series"!=item.Type?(page.querySelector("#specialsCollapsible").classList.remove("hide"),renderSpecials(page,item,user,6)):page.querySelector("#specialsCollapsible").classList.add("hide"),item.People&&item.People.length?(page.querySelector("#castCollapsible").classList.remove("hide"),renderCast(page,item,context,enableScrollX()?null:12)):page.querySelector("#castCollapsible").classList.add("hide"),item.PartCount&&item.PartCount>1?(page.querySelector("#additionalPartsCollapsible").classList.remove("hide"),renderAdditionalParts(page,item,user)):page.querySelector("#additionalPartsCollapsible").classList.add("hide"),page.querySelector("#themeSongsCollapsible").classList.add("hide"),page.querySelector("#themeVideosCollapsible").classList.add("hide"),"MusicAlbum"==item.Type?renderMusicVideos(page,item,user):page.querySelector("#musicVideosCollapsible").classList.add("hide"),renderThemeMedia(page,item,user),enableScrollX()?renderCriticReviews(page,item):renderCriticReviews(page,item,1)}function renderOverview(elems,item){for(var i=0,length=elems.length;i'+text+"
":'
'+text+"
"}).join("");return view.querySelector(".mediaInfoIcons").innerHTML=html,html}function renderPhotoInfo(page,item){var html="",attributes=[];if(item.CameraMake&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraMake"),item.CameraMake)),item.CameraModel&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraModel"),item.CameraModel)),item.Altitude&&attributes.push(createAttribute(globalize.translate("MediaInfoAltitude"),item.Altitude.toFixed(1))),item.Aperture&&attributes.push(createAttribute(globalize.translate("MediaInfoAperture"),"F"+item.Aperture.toFixed(1))),item.ExposureTime){var val=1/item.ExposureTime;attributes.push(createAttribute(globalize.translate("MediaInfoExposureTime"),"1/"+val+" s"))}item.FocalLength&&attributes.push(createAttribute(globalize.translate("MediaInfoFocalLength"),item.FocalLength.toFixed(1)+" mm")),item.ImageOrientation,item.IsoSpeedRating&&attributes.push(createAttribute(globalize.translate("MediaInfoIsoSpeedRating"),item.IsoSpeedRating)),item.Latitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLatitude"),item.Latitude.toFixed(1))),item.Longitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLongitude"),item.Longitude.toFixed(1))),item.ShutterSpeed&&attributes.push(createAttribute(globalize.translate("MediaInfoShutterSpeed"),item.ShutterSpeed)),item.Software&&attributes.push(createAttribute(globalize.translate("MediaInfoSoftware"),item.Software)),html+=attributes.join("
"),page.querySelector(".photoInfoContent").innerHTML=html}function getArtistLinksHtml(artists,context){for(var html=[],i=0,length=artists.length;i'+artist.Name+"")}return html=html.join(" / "),1==artists.length?globalize.translate("ValueArtist",html):artists.length>1?globalize.translate("ValueArtists",html):html}function enableScrollX(){return browserInfo.mobile&&screen.availWidth<=1e3}function getPortraitShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowPortrait":"portrait"}function getSquareShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowSquare":"square"}function getThumbShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowBackdrop":"backdrop"}function renderMoreFromItems(page,item){var moreFromSection=page.querySelector("#moreFromSection");if(moreFromSection)return"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length?void ApiClient.getItems(Dashboard.getCurrentUserId(),{IncludeItemTypes:"MusicAlbum",ArtistIds:item.AlbumArtists[0].Id,Recursive:!0,ExcludeItemIds:item.Id}).then(function(result){if(!result.Items.length)return void moreFromSection.classList.add("hide");moreFromSection.classList.remove("hide"),moreFromSection.querySelector(".moreFromHeader").innerHTML=globalize.translate("MoreFromValue",item.AlbumArtists[0].Name);var html="";html+=enableScrollX()?'
':'
';var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),supportsImageAnalysis=appHost.supports("imageanalysis");supportsImageAnalysis=!1,html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!supportsImageAnalysis,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
";var similarContent=page.querySelector("#moreFromItems");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)}):void moreFromSection.classList.add("hide")}function renderSimilarItems(page,item,context){var similarCollapsible=page.querySelector("#similarCollapsible");if(similarCollapsible){if("Movie"!=item.Type&&"Trailer"!=item.Type&&"Series"!=item.Type&&"Program"!=item.Type&&"Recording"!=item.Type&&"Game"!=item.Type&&"MusicAlbum"!=item.Type&&"MusicArtist"!=item.Type&&"ChannelVideoItem"!=item.Type)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),options={userId:Dashboard.getCurrentUserId(),limit:"MusicAlbum"==item.Type||"MusicArtist"==item.Type?8:10,fields:"PrimaryImageAspectRatio,UserData,CanDelete"};"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length&&(options.ExcludeArtistIds=item.AlbumArtists[0].Id),enableScrollX()&&(options.limit=12),ApiClient.getSimilarItems(item.Id,options).then(function(result){if(!result.Items.length)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var html="";html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis&&("MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type);cardLayout=!1,html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!cardLayout,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,context:context,lazy:!0,showDetailsMenu:!0,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis}),html+="
";var similarContent=similarCollapsible.querySelector(".similarContent");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)})}}function renderSeriesAirTime(page,item,isStatic){var seriesAirTime=page.querySelector("#seriesAirTime");if("Series"!=item.Type)return void seriesAirTime.classList.add("hide");var html="";if(item.AirDays&&item.AirDays.length&&(html+=7==item.AirDays.length?"daily":item.AirDays.map(function(a){return a+"s"}).join(",")),item.AirTime&&(html+=" at "+item.AirTime),item.Studios.length)if(isStatic)html+=" on "+item.Studios[0].Name;else{var context=inferContext(item),href=embyRouter.getRouteUrl(item.Studios[0],{context:context,itemType:"Studio"});html+=' on '+item.Studios[0].Name+""}html?(html=("Ended"==item.Status?"Aired ":"Airs ")+html,seriesAirTime.innerHTML=html,seriesAirTime.classList.remove("hide")):seriesAirTime.classList.add("hide")}function renderTags(page,item){var itemTags=page.querySelector(".itemTags");if(item.Tags&&item.Tags.length){for(var html="",i=0,length=item.Tags.length;i'+item.Tags[i]+"
";itemTags.innerHTML=html,itemTags.classList.remove("hide")}else itemTags.classList.add("hide")}function getEpisodesFunction(seriesId,query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getEpisodes(seriesId,query)}}function getAlbumSongsFunction(query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getItems(Dashboard.getCurrentUserId(),query)}}function renderChildren(page,item){_childrenItemsFunction=null;var fields="ItemCounts,PrimaryImageAspectRatio,BasicSyncInfo,CanDelete",query={ParentId:item.Id,Fields:fields};"BoxSet"!==item.Type&&(query.SortBy="SortName");var promise,userId=Dashboard.getCurrentUserId();"Series"==item.Type?promise=ApiClient.getSeasons(item.Id,{userId:userId,Fields:fields}):"Season"==item.Type?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields})):"Episode"==item.Type&&item.SeriesId&&item.SeasonId?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields})):"MusicAlbum"==item.Type&&(_childrenItemsFunction=getAlbumSongsFunction(query)),promise=promise||ApiClient.getItems(Dashboard.getCurrentUserId(),query),promise.then(function(result){var html="",scrollX=!1,isList=!1,scrollClass="hiddenScrollX",childrenItemsContainer=page.querySelector(".childrenItemsContainer");if("MusicAlbum"==item.Type)html=listView.getListViewHtml({items:result.Items,smallIcon:!0,showIndex:!0,index:"disc",showIndexNumber:!0,playFromHere:!0,action:"playallfromhere",image:!1,artist:"auto",containerAlbumArtist:item.AlbumArtist,addToListButton:!0}),isList=!0;else if("Series"==item.Type)scrollX=enableScrollX(),html=cardBuilder.getCardsHtml({items:result.Items,shape:getPortraitShape(),showTitle:!0,centerText:!0,lazy:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX});else if("Season"==item.Type||"Episode"==item.Type){if("Episode"===item.Type&&childrenItemsContainer.classList.add("darkScroller"),scrollX="Episode"==item.Type,browser.touch||(scrollClass="smoothScrollX"),result.Items.length<2&&"Episode"===item.Type)return;html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(scrollX),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,playFromHere:!0,overlayText:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX,includeParentInfoInTitle:!1})}else"GameSystem"==item.Type&&(html=cardBuilder.getCardsHtml({items:result.Items,shape:"auto",showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0}));if("BoxSet"!==item.Type&&page.querySelector("#childrenCollapsible").classList.remove("hide"),scrollX?(childrenItemsContainer.classList.add(scrollClass),childrenItemsContainer.classList.remove("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list")):(childrenItemsContainer.classList.remove("hiddenScrollX"),childrenItemsContainer.classList.remove("smoothScrollX"),isList?(childrenItemsContainer.classList.add("vertical-list"),childrenItemsContainer.classList.remove("vertical-wrap")):(childrenItemsContainer.classList.add("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list"))),childrenItemsContainer.innerHTML=html,imageLoader.lazyChildren(childrenItemsContainer),"BoxSet"==item.Type){var collectionItemTypes=[{name:globalize.translate("HeaderVideos"),mediaType:"Video"},{name:globalize.translate("HeaderSeries"),type:"Series"},{name:globalize.translate("HeaderAlbums"),type:"MusicAlbum"},{name:globalize.translate("HeaderGames"),type:"Game"},{name:globalize.translate("HeaderBooks"),type:"Book"}];renderCollectionItems(page,item,collectionItemTypes,result.Items)}else if("Episode"===item.Type){var card=childrenItemsContainer.querySelector('.card[data-id="'+item.Id+'"]');card&&scrollHelper.toStart(childrenItemsContainer,card.previousSibling||card,!0)}}),"Season"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderEpisodes"):"Episode"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("MoreFromValue",item.SeasonName):"Series"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderSeasons"):"MusicAlbum"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderTracks"):"GameSystem"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderGames"):page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderItems"),"MusicAlbum"==item.Type?page.querySelector(".childrenSectionHeader",page).classList.add("hide"):page.querySelector(".childrenSectionHeader",page).classList.remove("hide")}function renderItemsByName(page,item,user){require("scripts/itembynamedetailpage".split(","),function(){window.ItemsByName.renderItems(page,item)})}function renderPlaylistItems(page,item,user){require("scripts/playlistedit".split(","),function(){PlaylistViewer.render(page,item)})}function renderChannelGuide(page,item,user){require("scripts/livetvchannel,scripts/livetvcomponents,livetvcss".split(","),function(liveTvChannelPage){liveTvChannelPage.renderPrograms(page,item.Id)})}function renderSeriesSchedule(page,item,user){}function inferContext(item){return"Movie"==item.Type||"BoxSet"==item.Type?"movies":"Series"==item.Type||"Season"==item.Type||"Episode"==item.Type?"tvshows":"Game"==item.Type||"GameSystem"==item.Type?"games":"Game"==item.Type||"GameSystem"==item.Type?"games":"MusicArtist"==item.Type||"MusicAlbum"==item.Type?"music":null}function renderStudios(elem,item,isStatic){var context=inferContext(item);if(item.Studios&&item.Studios.length&&"Series"!=item.Type,1)elem.classList.add("hide");else{for(var html="",i=0,length=item.Studios.length;i0&&(html+="  /  "),isStatic)html+=item.Studios[i].Name;else{item.Studios[i].Type="Studio";var href=embyRouter.getRouteUrl(item.Studios[0],{context:context});html+=''+item.Studios[i].Name+""}var translationKey=item.Studios.length>1?"ValueStudios":"ValueStudio";html=globalize.translate(translationKey,html),elem.innerHTML=html,elem.classList.remove("hide")}}function renderGenres(elem,item,limit,isStatic){for(var context=inferContext(item),html="",genres=item.Genres||[],i=0,length=genres.length;i=limit);i++){i>0&&(html+='');var param="Audio"==item.Type||"MusicArtist"==item.Type||"MusicAlbum"==item.Type||"MusicVideo"==item.Type?"musicgenre":"genre";if("Game"==item.MediaType&&(param="gamegenre"),isStatic)html+=genres[i];else{var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;case"music":type="MusicAlbum";break;default:type="Movie"}var url="secondaryitems.html?type="+type+"&"+param+"="+ApiClient.encodeName(genres[i]);html+=''+genres[i]+""}}elem.innerHTML=html}function filterItemsByCollectionItemType(items,typeInfo){return items.filter(function(item){return typeInfo.mediaType?item.MediaType==typeInfo.mediaType:item.Type==typeInfo.type})}function renderCollectionItems(page,parentItem,types,items){page.querySelector(".collectionItems").innerHTML="";var i,length;for(i=0,length=types.length;i0}).length});otherTypeItems.length&&renderCollectionItemType(page,parentItem,otherType,otherTypeItems),items.length||renderCollectionItemType(page,parentItem,{name:globalize.translate("HeaderItems")},items)}function renderCollectionItemType(page,parentItem,type,items){var html="";html+='
',html+='
',html+="

",html+=""+type.name+"",html+="

",html+='',html+="
",html+='
';var shape="MusicAlbum"==type.type?getSquareShape(!1):getPortraitShape(!1);html+=cardBuilder.getCardsHtml({items:items,shape:shape,showTitle:!0,centerText:!0, +lazy:!0,showDetailsMenu:!0,overlayMoreButton:!0,showAddToCollection:!1,showRemoveFromCollection:!0,collectionId:parentItem.Id}),html+="
",html+="
";var collectionItems=page.querySelector(".collectionItems");collectionItems.insertAdjacentHTML("beforeend",html),imageLoader.lazyChildren(collectionItems),collectionItems.querySelector(".btnAddToCollection").addEventListener("click",function(){require(["alert"],function(alert){alert({text:globalize.translate("AddItemToCollectionHelp"),html:globalize.translate("AddItemToCollectionHelp")+'

'+globalize.translate("ButtonLearnMore")+""})})})}function renderUserDataIcons(page,item){for(var userDataIcons=page.querySelectorAll(".userDataIcons"),i=0,length=userDataIcons.length;i',html+='
',null!=review.Score||null!=review.Likes&&(html+=review.Likes?"
":"
"),html+='
',html+='

'+review.Caption+"

";var vals=[];if(review.ReviewerName&&vals.push(review.ReviewerName),review.Publisher&&vals.push(review.Publisher),html+='
'+vals.join(", ")+".",review.Date)try{var date=datetime.toLocaleDateString(datetime.parseISO8601Date(review.Date,!0));html+=''+date+""}catch(error){}html+="
",review.Url&&(html+='"),html+="
",html+="
",html+="
"}limit&&result.TotalRecordCount>limit&&(html+='

");var criticReviewsContent=page.querySelector("#criticReviewsContent");criticReviewsContent.innerHTML=html,enableScrollX()?criticReviewsContent.classList.add("hiddenScrollX"):criticReviewsContent.classList.remove("hiddenScrollX")}function renderThemeMedia(page,item){"SeriesTimer"!==item.Type&&"Timer"!==item.Type&&"Genre"!==item.Type&&"MusicGenre"!==item.Type&&"GameGenre"!==item.Type&&"Studio"!==item.Type&&"Person"!==item.Type&&ApiClient.getThemeMedia(Dashboard.getCurrentUserId(),item.Id,!0).then(function(result){var themeSongs=result.ThemeSongsResult.OwnerId==item.Id?result.ThemeSongsResult.Items:[],themeVideos=result.ThemeVideosResult.OwnerId==item.Id?result.ThemeVideosResult.Items:[];renderThemeSongs(page,themeSongs),renderThemeVideos(page,themeVideos)})}function renderThemeSongs(page,items){if(items.length){page.querySelector("#themeSongsCollapsible").classList.remove("hide");var html=listView.getListViewHtml({items:items});page.querySelector("#themeSongsContent").innerHTML=html}else page.querySelector("#themeSongsCollapsible").classList.add("hide")}function renderThemeVideos(page,items,user){if(items.length){page.querySelector("#themeVideosCollapsible").classList.remove("hide");var themeVideosContent=page.querySelector("#themeVideosContent");themeVideosContent.innerHTML=getVideosHtml(items,user),imageLoader.lazyChildren(themeVideosContent)}else page.querySelector("#themeVideosCollapsible").classList.add("hide")}function renderMusicVideos(page,item,user){ApiClient.getItems(user.Id,{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"MusicVideo",Recursive:!0,Fields:"DateCreated,CanDelete",AlbumIds:item.Id}).then(function(result){if(result.Items.length){page.querySelector("#musicVideosCollapsible").classList.remove("hide");var musicVideosContent=page.querySelector(".musicVideosContent");musicVideosContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(musicVideosContent)}else page.querySelector("#musicVideosCollapsible").classList.add("hide")})}function renderAdditionalParts(page,item,user){ApiClient.getAdditionalVideoParts(user.Id,item.Id).then(function(result){if(result.Items.length){page.querySelector("#additionalPartsCollapsible").classList.remove("hide");var additionalPartsContent=page.querySelector("#additionalPartsContent");additionalPartsContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(additionalPartsContent)}else page.querySelector("#additionalPartsCollapsible").classList.add("hide")})}function renderScenes(page,item){var chapters=item.Chapters||[];if(chapters.length&&!chapters[0].ImageTag&&(chapters=[]),chapters.length){page.querySelector("#scenesCollapsible").classList.remove("hide");var scenesContent=page.querySelector("#scenesContent");enableScrollX()?scenesContent.classList.add("smoothScrollX"):scenesContent.classList.add("vertical-wrap"),require(["chaptercardbuilder"],function(chaptercardbuilder){chaptercardbuilder.buildChapterCards(item,chapters,{itemsContainer:scenesContent,width:400,backdropShape:getThumbShape(),squareShape:getSquareShape()})})}else page.querySelector("#scenesCollapsible").classList.add("hide")}function renderMediaSources(page,user,item){var html=item.MediaSources.map(function(v){return getMediaSourceHtml(user,item,v)}).join('
');item.MediaSources.length>1&&(html="
"+html);var mediaInfoContent=page.querySelector("#mediaInfoContent");mediaInfoContent.innerHTML=html}function getMediaSourceHtml(user,item,version){var html="";version.Name&&item.MediaSources.length>1&&(html+='
'+version.Name+"

");for(var i=0,length=version.MediaStreams.length;i';var displayType=globalize.translate("MediaInfoStreamType"+stream.Type);html+='

'+displayType+"

";var attributes=[];stream.Language&&"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoLanguage"),stream.Language)),stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoCodec"),stream.Codec.toUpperCase())),stream.CodecTag&&attributes.push(createAttribute(globalize.translate("MediaInfoCodecTag"),stream.CodecTag)),null!=stream.IsAVC&&attributes.push(createAttribute("AVC",stream.IsAVC?"Yes":"No")),stream.Profile&&attributes.push(createAttribute(globalize.translate("MediaInfoProfile"),stream.Profile)),stream.Level&&attributes.push(createAttribute(globalize.translate("MediaInfoLevel"),stream.Level)),(stream.Width||stream.Height)&&attributes.push(createAttribute(globalize.translate("MediaInfoResolution"),stream.Width+"x"+stream.Height)),stream.AspectRatio&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoAspectRatio"),stream.AspectRatio)),"Video"==stream.Type&&(null!=stream.IsAnamorphic&&attributes.push(createAttribute(globalize.translate("MediaInfoAnamorphic"),stream.IsAnamorphic?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoInterlaced"),stream.IsInterlaced?"Yes":"No"))),(stream.AverageFrameRate||stream.RealFrameRate)&&attributes.push(createAttribute(globalize.translate("MediaInfoFramerate"),stream.AverageFrameRate||stream.RealFrameRate)),stream.ChannelLayout&&attributes.push(createAttribute(globalize.translate("MediaInfoLayout"),stream.ChannelLayout)),stream.Channels&&attributes.push(createAttribute(globalize.translate("MediaInfoChannels"),stream.Channels+" ch")),stream.BitRate&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoBitrate"),parseInt(stream.BitRate/1e3)+" kbps")),stream.SampleRate&&attributes.push(createAttribute(globalize.translate("MediaInfoSampleRate"),stream.SampleRate+" Hz")),stream.BitDepth&&attributes.push(createAttribute(globalize.translate("MediaInfoBitDepth"),stream.BitDepth+" bit")),stream.PixelFormat&&attributes.push(createAttribute(globalize.translate("MediaInfoPixelFormat"),stream.PixelFormat)),stream.RefFrames&&attributes.push(createAttribute(globalize.translate("MediaInfoRefFrames"),stream.RefFrames)),stream.NalLengthSize&&attributes.push(createAttribute("NAL",stream.NalLengthSize)),"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoDefault"),stream.IsDefault?"Yes":"No")),"Subtitle"==stream.Type&&(attributes.push(createAttribute(globalize.translate("MediaInfoForced"),stream.IsForced?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoExternal"),stream.IsExternal?"Yes":"No"))),"Video"==stream.Type&&version.Timestamp&&attributes.push(createAttribute(globalize.translate("MediaInfoTimestamp"),version.Timestamp)),stream.DisplayTitle&&attributes.push(createAttribute("Title",stream.DisplayTitle)),html+=attributes.join("
"),html+=""}}if(version.Container&&(html+='
'+globalize.translate("MediaInfoContainer")+''+version.Container+"
"),version.Formats&&version.Formats.length,version.Path&&"Http"!=version.Protocol&&user&&user.Policy.IsAdministrator&&(html+='
'+globalize.translate("MediaInfoPath")+''+version.Path+"
"),version.Size){var size=(version.Size/1048576).toFixed(0);html+='
'+globalize.translate("MediaInfoSize")+''+size+" MB
"}return html}function createAttribute(label,value){return''+label+''+value+""}function getVideosHtml(items,user,limit,moreButtonClass){var html=cardBuilder.getCardsHtml({items:items,shape:"auto",showTitle:!0,action:"play",overlayText:!0,showRuntime:!0});return limit&&items.length>limit&&(html+='

"),html}function renderSpecials(page,item,user,limit){ApiClient.getSpecialFeatures(user.Id,item.Id).then(function(specials){var specialsContent=page.querySelector("#specialsContent");specialsContent.innerHTML=getVideosHtml(specials,user,limit,"moreSpecials"),imageLoader.lazyChildren(specialsContent)})}function renderCast(page,item,context,limit,isStatic){var people=item.People||[],castContent=page.querySelector("#castContent");enableScrollX()?(castContent.classList.add("smoothScrollX"),limit=32):castContent.classList.add("vertical-wrap");var limitExceeded=limit&&people.length>limit;limitExceeded&&(people=people.slice(0),people.length=Math.min(limit,people.length)),require(["peoplecardbuilder"],function(peoplecardbuilder){peoplecardbuilder.buildPeopleCards(people,{itemsContainer:castContent,coverImage:!0,serverId:item.ServerId,width:160,shape:getPortraitShape()})});var morePeopleButton=page.querySelector(".morePeople");morePeopleButton&&(limitExceeded&&!enableScrollX()?morePeopleButton.classList.remove("hide"):morePeopleButton.classList.add("hide"))}function play(startPosition){playbackManager.play({items:[currentItem],startPositionTicks:startPosition})}function splitVersions(page,params){require(["confirm"],function(confirm){confirm("Are you sure you wish to split the media sources into separate items?","Split Media Apart").then(function(){loading.show(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Videos/"+params.id+"/AlternateSources")}).then(function(){loading.hide(),reload(page,params)})})})}function playTrailer(page){playbackManager.playTrailers(currentItem)}function showPlayMenu(item,target){require(["playMenu"],function(playMenu){playMenu.show({item:item,positionTo:target})})}function playCurrentItem(button,mode){var item=currentItem;return"Program"===item.Type?void ApiClient.getLiveTvChannel(item.ChannelId,Dashboard.getCurrentUserId()).then(function(channel){playbackManager.play({items:[channel]})}):void("playmenu"===mode?showPlayMenu(item,button):playbackManager.play({items:[item],startPositionTicks:item.UserData&&"resume"===mode?item.UserData.PlaybackPositionTicks:0}))}function itemDetailPage(){var self=this;self.play=play,self.setInitialCollapsibleState=setInitialCollapsibleState,self.renderDetails=renderDetails,self.renderCriticReviews=renderCriticReviews,self.renderCast=renderCast,self.renderScenes=renderScenes,self.renderMediaSources=renderMediaSources}function onPlayClick(){var mode=this.getAttribute("data-mode");playCurrentItem(this,mode)}function onInstantMixClick(){playbackManager.instantMix(currentItem)}function onShuffleClick(){playbackManager.shuffle(currentItem)}function onDeleteClick(){require(["deleteHelper"],function(deleteHelper){deleteHelper.deleteItem({item:currentItem,navigate:!0})})}function onCancelSeriesTimerClick(){require(["recordingHelper"],function(recordingHelper){recordingHelper.cancelSeriesTimerWithConfirmation(currentItem.Id,currentItem.ServerId).then(function(){Dashboard.navigate("livetv.html")})})}var currentItem,currentRecordingFields,_childrenItemsFunction=null;return window.ItemDetailPage=new itemDetailPage,function(view,params){function onPlayTrailerClick(){playTrailer(view)}function onMoreCommandsClick(){var button=this;connectionManager.getApiClient(currentItem.ServerId).getCurrentUser().then(function(user){itemContextMenu.show(getContextMenuOptions(currentItem,user,button)).then(function(result){result.deleted?embyRouter.goHome():result.updated&&reload(view,params)})})}function editImages(){return new Promise(function(resolve,reject){require(["imageEditor"],function(imageEditor){imageEditor.show({itemId:currentItem.Id,serverId:currentItem.ServerId}).then(resolve,reject)})})}function onWebSocketMessage(e,data){var msg=data;if("UserDataChanged"===msg.MessageType&¤tItem&&msg.Data.UserId==Dashboard.getCurrentUserId()){var key=currentItem.UserData.Key,userData=msg.Data.UserDataList.filter(function(u){return u.Key==key})[0];userData&&(currentItem.UserData=userData,reloadPlayButtons(view,currentItem),Dashboard.getCurrentUser().then(function(user){refreshImage(view,currentItem,user)}))}}var i,length,elems=view.querySelectorAll(".btnPlay");for(i=0,length=elems.length;i':''),headerHtml+="",headerHtml+="",page.insertAdjacentHTML("afterbegin",headerHtml)}},getToolsLinkHtml:function(item){var menuHtml="",pageIds=item.pageIds?item.pageIds.join(","):"";return pageIds=pageIds?' data-pageids="'+pageIds+'"':"",menuHtml+='",item.icon&&(menuHtml+=''+item.icon+""),menuHtml+='',menuHtml+=item.name,menuHtml+="",menuHtml+=""},getToolsMenuHtml:function(page){var i,length,item,items=Dashboard.getToolsMenuLinks(page),menuHtml="";for(menuHtml+='
',i=0,length=items.length;i
"),item.href?menuHtml+=Dashboard.getToolsLinkHtml(item):(menuHtml+='
',menuHtml+=item.name,menuHtml+="
");return menuHtml+=""},getToolsMenuLinks:function(){return[{name:Globalize.translate("TabServer")},{name:Globalize.translate("TabDashboard"),href:"dashboard.html",pageIds:["dashboardPage"],icon:"dashboard"},{name:Globalize.translate("TabSettings"),href:"dashboardgeneral.html",pageIds:["dashboardGeneralPage"],icon:"settings"},{name:Globalize.translate("TabDevices"),href:"devices.html",pageIds:["devicesPage","devicePage","devicesUploadPage"],icon:"tablet"},{name:Globalize.translate("TabUsers"),href:"userprofiles.html",pageIds:["userProfilesPage","newUserPage","editUserPage","userLibraryAccessPage","userParentalControlPage","userPasswordPage"],icon:"people"},{name:"Emby Premiere",href:"supporterkey.html",pageIds:["supporterKeyPage"],icon:"star"},{divider:!0,name:Globalize.translate("TabLibrary"),href:"library.html",pageIds:["mediaLibraryPage","librarySettingsPage","libraryDisplayPage","metadataImagesConfigurationPage","metadataNfoPage"],icon:"folder",color:"#38c"},{name:Globalize.translate("TabSubtitles"),href:"metadatasubtitles.html",pageIds:["metadataSubtitlesPage"],icon:"closed_caption"},{name:Globalize.translate("TabPlayback"),icon:"play_circle_filled",color:"#E5342E",href:"cinemamodeconfiguration.html",pageIds:["cinemaModeConfigurationPage","playbackConfigurationPage","streamingSettingsPage"]},{name:Globalize.translate("TabSync"),icon:"sync",href:"syncactivity.html",pageIds:["syncActivityPage","syncJobPage","syncSettingsPage"],color:"#009688"},{name:Globalize.translate("TabTranscoding"),icon:"transform",href:"encodingsettings.html",pageIds:["encodingSettingsPage"]},{divider:!0,name:Globalize.translate("TabExtras")},{name:Globalize.translate("TabAutoOrganize"),color:"#01C0DD",href:"autoorganizelog.html",pageIds:["libraryFileOrganizerPage","libraryFileOrganizerSmartMatchPage","libraryFileOrganizerLogPage"],icon:"folder"},{name:Globalize.translate("DLNA"),href:"dlnasettings.html",pageIds:["dlnaSettingsPage","dlnaProfilesPage","dlnaProfilePage"],icon:"settings"},{name:Globalize.translate("TabLiveTV"),href:"livetvstatus.html",pageIds:["liveTvStatusPage","liveTvSettingsPage","liveTvTunerPage"],icon:"dvr"},{name:Globalize.translate("TabNotifications"),icon:"notifications",color:"brown",href:"notificationsettings.html",pageIds:["notificationSettingsPage","notificationSettingPage"]},{name:Globalize.translate("TabPlugins"),icon:"add_shopping_cart",color:"#9D22B1",href:"plugins.html",pageIds:["pluginsPage","pluginCatalogPage"]},{divider:!0,name:Globalize.translate("TabExpert")},{name:Globalize.translate("TabAdvanced"),icon:"settings",href:"dashboardhosting.html",color:"#F16834",pageIds:["dashboardHostingPage","serverSecurityPage"]},{name:Globalize.translate("TabLogs"),href:"log.html",pageIds:["logPage"],icon:"folder_open"},{name:Globalize.translate("TabScheduledTasks"),href:"scheduledtasks.html",pageIds:["scheduledTasksPage","scheduledTaskPage"],icon:"schedule"},{name:Globalize.translate("MetadataManager"),href:"edititemmetadata.html",pageIds:[],icon:"mode_edit"},{name:Globalize.translate("ButtonReports"),href:"reports.html",pageIds:[],icon:"insert_chart"}]},getSupportedRemoteCommands:function(){return["GoHome","GoToSettings","VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","DisplayContent","GoToSearch","DisplayMessage","SetRepeatMode"]},capabilities:function(){var caps={PlayableMediaTypes:["Audio","Video"],SupportedCommands:Dashboard.getSupportedRemoteCommands(),SupportsPersistentIdentifier:Dashboard.isRunningInCordova(),SupportsMediaControl:!0,SupportedLiveMediaTypes:["Audio","Video"]};return Dashboard.isRunningInCordova()&&!browserInfo.safari&&(caps.SupportsSync=!0,caps.SupportsContentUploading=!0),caps},normalizeImageOptions:function(options){var setQuality;if(options.maxWidth&&(setQuality=!0),options.width&&(setQuality=!0),options.maxHeight&&(setQuality=!0),options.height&&(setQuality=!0),setQuality){var quality=90,isBackdrop="backdrop"==(options.type||"").toLowerCase();isBackdrop&&(quality-=10),browserInfo.slow&&(quality-=40),AppInfo.hasLowImageBandwidth&&!isBackdrop&&(quality-=10),options.quality=quality}}},AppInfo={};!function(){"use strict";function setAppInfo(){var isCordova=Dashboard.isRunningInCordova();AppInfo.enableAutoSave=browserInfo.touch,AppInfo.enableAppStorePolicy=isCordova,browserInfo.iOS&&(AppInfo.hasLowImageBandwidth=!0),isCordova?(AppInfo.isNativeApp=!0,browserInfo.android&&(AppInfo.supportsExternalPlayers=!0)):AppInfo.enableSupporterMembership=!0,AppInfo.supportsFileInput=!(AppInfo.isNativeApp&&browserInfo.android),AppInfo.supportsUserDisplayLanguageSetting=Dashboard.isConnectMode()}function initializeApiClient(apiClient){AppInfo.enableAppStorePolicy&&(apiClient.getAvailablePlugins=function(){return Promise.resolve([])},apiClient.getInstalledPlugins=function(){return Promise.resolve([])}),apiClient.normalizeImageOptions=Dashboard.normalizeImageOptions,Events.off(apiClient,"requestfail",Dashboard.onRequestFail),Events.on(apiClient,"requestfail",Dashboard.onRequestFail)}function onApiClientCreated(e,newApiClient){initializeApiClient(newApiClient),window.$&&($.ajax=newApiClient.ajax),require(["globalize"],function(globalize){newApiClient.downloadsTitleText=globalize.translate("sharedcomponents#Downloads")})}function defineConnectionManager(connectionManager){window.ConnectionManager=connectionManager,define("connectionManager",[],function(){return connectionManager})}function bindConnectionManagerEvents(connectionManager,events,userSettings){window.Events=events,events.on(ConnectionManager,"apiclientcreated",onApiClientCreated),connectionManager.currentApiClient=function(){if(!localApiClient){var server=connectionManager.getLastUsedServer();server&&(localApiClient=connectionManager.getApiClient(server.Id))}return localApiClient},connectionManager.onLocalUserSignedIn=function(user){return localApiClient=connectionManager.getApiClient(user.ServerId),window.ApiClient=localApiClient,userSettings.setUserInfo(user.Id,localApiClient)},events.on(connectionManager,"localusersignedout",function(){userSettings.setUserInfo(null,null)})}function createConnectionManager(){return new Promise(function(resolve,reject){require(["connectionManagerFactory","apphost","credentialprovider","events","userSettings"],function(connectionManagerExports,apphost,credentialProvider,events,userSettings){window.MediaBrowser=Object.assign(window.MediaBrowser||{},connectionManagerExports);var credentialProviderInstance=new credentialProvider,promises=[apphost.getSyncProfile(),apphost.appInfo()];Promise.all(promises).then(function(responses){var deviceProfile=responses[0],appInfo=responses[1],capabilities=Dashboard.capabilities();capabilities.DeviceProfile=deviceProfile;var connectionManager=new MediaBrowser.ConnectionManager(credentialProviderInstance,appInfo.appName,appInfo.appVersion,appInfo.deviceName,appInfo.deviceId,capabilities,window.devicePixelRatio);return defineConnectionManager(connectionManager),bindConnectionManagerEvents(connectionManager,events,userSettings),Dashboard.isConnectMode()?void resolve():(console.log("loading ApiClient singleton"),getRequirePromise(["apiclient"]).then(function(apiClientFactory){console.log("creating ApiClient singleton");var apiClient=new apiClientFactory(Dashboard.serverAddress(),appInfo.appName,appInfo.appVersion,appInfo.deviceName,appInfo.deviceId,window.devicePixelRatio);apiClient.enableAutomaticNetworking=!1,connectionManager.addApiClient(apiClient),require(["css!"+apiClient.getUrl("Branding/Css")]),window.ApiClient=apiClient,localApiClient=apiClient,console.log("loaded ApiClient singleton"),resolve()}))})})})}function setDocumentClasses(browser){var elem=document.documentElement;AppInfo.enableSupporterMembership||elem.classList.add("supporterMembershipDisabled")}function loadTheme(){var name=getParameterByName("theme");if(name)return void require(["themes/"+name+"/theme"]);if(!AppInfo.isNativeApp){var date=new Date,month=date.getMonth(),day=date.getDate();return 9==month&&day>=30?void require(["themes/halloween/theme"]):void 0}}function returnFirstDependency(obj){return obj}function getBowerPath(){return"bower_components"}function getLayoutManager(layoutManager,appHost){return appHost.getDefaultLayout&&(layoutManager.defaultLayout=appHost.getDefaultLayout()),layoutManager.init(),layoutManager}function getAppStorage(basePath){try{return localStorage.setItem("_test","0"),localStorage.removeItem("_test"),basePath+"/appstorage-localstorage"}catch(e){return basePath+"/appstorage-memory"}}function createWindowHeadroom(Headroom){var headroom=new Headroom([],{});return headroom.init(),headroom}function getCastSenderApiLoader(){var ccLoaded=!1;return{load:function(){return ccLoaded?Promise.resolve():new Promise(function(resolve,reject){var fileref=document.createElement("script");fileref.setAttribute("type","text/javascript"),fileref.onload=function(){ccLoaded=!0,resolve()},fileref.setAttribute("src","https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"),document.querySelector("head").appendChild(fileref)})}}}function getDummyCastSenderApiLoader(){return{load:function(){return window.chrome=window.chrome||{},Promise.resolve()}}}function createSharedAppFooter(appFooter){var footer=new appFooter({});return footer}function onRequireJsError(requireType,requireModules){console.log("RequireJS error: "+(requireType||"unknown")+". Failed modules: "+(requireModules||[]).join(","))}function initRequire(){var urlArgs="v="+(window.dashboardVersion||(new Date).getDate()),bowerPath=getBowerPath(),apiClientBowerPath=bowerPath+"/emby-apiclient",embyWebComponentsBowerPath=bowerPath+"/emby-webcomponents",paths={velocity:bowerPath+"/velocity/velocity.min",vibrant:bowerPath+"/vibrant/dist/vibrant",staticBackdrops:embyWebComponentsBowerPath+"/staticbackdrops",ironCardList:"components/ironcardlist/ironcardlist",scrollThreshold:"components/scrollthreshold",playlisteditor:"components/playlisteditor/playlisteditor",medialibrarycreator:"components/medialibrarycreator/medialibrarycreator",medialibraryeditor:"components/medialibraryeditor/medialibraryeditor",howler:bowerPath+"/howlerjs/howler.min",sortable:bowerPath+"/Sortable/Sortable.min",isMobile:bowerPath+"/isMobile/isMobile.min",masonry:bowerPath+"/masonry/dist/masonry.pkgd.min",humanedate:"components/humanedate",libraryBrowser:"scripts/librarybrowser",chromecasthelpers:"components/chromecasthelpers",events:apiClientBowerPath+"/events",credentialprovider:apiClientBowerPath+"/credentials",connectionManagerFactory:bowerPath+"/emby-apiclient/connectionmanager",visibleinviewport:embyWebComponentsBowerPath+"/visibleinviewport",browserdeviceprofile:embyWebComponentsBowerPath+"/browserdeviceprofile",browser:embyWebComponentsBowerPath+"/browser",inputManager:embyWebComponentsBowerPath+"/inputmanager",qualityoptions:embyWebComponentsBowerPath+"/qualityoptions",hammer:bowerPath+"/hammerjs/hammer.min",pageJs:embyWebComponentsBowerPath+"/pagejs/page",focusManager:embyWebComponentsBowerPath+"/focusmanager",datetime:embyWebComponentsBowerPath+"/datetime",globalize:embyWebComponentsBowerPath+"/globalize",itemHelper:embyWebComponentsBowerPath+"/itemhelper",itemShortcuts:embyWebComponentsBowerPath+"/shortcuts",serverNotifications:embyWebComponentsBowerPath+"/servernotifications",playbackManager:embyWebComponentsBowerPath+"/playback/playbackmanager",autoPlayDetect:embyWebComponentsBowerPath+"/playback/autoplaydetect",nowPlayingHelper:embyWebComponentsBowerPath+"/playback/nowplayinghelper",pluginManager:embyWebComponentsBowerPath+"/pluginmanager",packageManager:embyWebComponentsBowerPath+"/packagemanager"};paths.hlsjs=bowerPath+"/hlsjs/dist/hls.min",define("mediaSession",[embyWebComponentsBowerPath+"/playback/mediasession"],returnFirstDependency),define("webActionSheet",[embyWebComponentsBowerPath+"/actionsheet/actionsheet"],returnFirstDependency),Dashboard.isRunningInCordova()?paths.sharingMenu="cordova/sharingwidget":define("sharingMenu",[embyWebComponentsBowerPath+"/sharing/sharingmenu"],returnFirstDependency),paths.wakeonlan=apiClientBowerPath+"/wakeonlan",define("libjass",[bowerPath+"/libjass/libjass.min","css!"+bowerPath+"/libjass/libjass"],returnFirstDependency),window.IntersectionObserver?define("lazyLoader",[embyWebComponentsBowerPath+"/lazyloader/lazyloader-intersectionobserver"],returnFirstDependency):define("lazyLoader",[embyWebComponentsBowerPath+"/lazyloader/lazyloader-scroll"],returnFirstDependency),define("tunerPicker",["components/tunerpicker"],returnFirstDependency),define("mainTabsManager",["components/maintabsmanager"],returnFirstDependency),define("imageLoader",[embyWebComponentsBowerPath+"/images/imagehelper"],returnFirstDependency),define("appfooter",["components/appfooter/appfooter"],returnFirstDependency),define("dockedtabs",["components/dockedtabs/dockedtabs"],returnFirstDependency),define("directorybrowser",["components/directorybrowser/directorybrowser"],returnFirstDependency),define("metadataEditor",[embyWebComponentsBowerPath+"/metadataeditor/metadataeditor"],returnFirstDependency),define("personEditor",[embyWebComponentsBowerPath+"/metadataeditor/personeditor"],returnFirstDependency),define("playerSelectionMenu",[embyWebComponentsBowerPath+"/playback/playerselection"],returnFirstDependency),define("playerSettingsMenu",[embyWebComponentsBowerPath+"/playback/playersettingsmenu"],returnFirstDependency),define("brightnessOsd",[embyWebComponentsBowerPath+"/playback/brightnessosd"],returnFirstDependency),define("libraryMenu",["scripts/librarymenu"],returnFirstDependency),define("emby-collapse",[embyWebComponentsBowerPath+"/emby-collapse/emby-collapse"],returnFirstDependency),define("emby-button",[embyWebComponentsBowerPath+"/emby-button/emby-button"],returnFirstDependency),define("emby-linkbutton",["emby-button"],returnFirstDependency),define("emby-itemscontainer",[embyWebComponentsBowerPath+"/emby-itemscontainer/emby-itemscontainer"],returnFirstDependency),define("emby-scroller",[embyWebComponentsBowerPath+"/emby-scroller/emby-scroller"],returnFirstDependency),define("emby-tabs",[embyWebComponentsBowerPath+"/emby-tabs/emby-tabs"],returnFirstDependency),define("itemHoverMenu",[embyWebComponentsBowerPath+"/itemhovermenu/itemhovermenu"],returnFirstDependency),define("multiSelect",[embyWebComponentsBowerPath+"/multiselect/multiselect"],returnFirstDependency),define("alphaPicker",[embyWebComponentsBowerPath+"/alphapicker/alphapicker"],returnFirstDependency),define("paper-icon-button-light",[embyWebComponentsBowerPath+"/emby-button/paper-icon-button-light"],returnFirstDependency),define("connectHelper",[embyWebComponentsBowerPath+"/emby-connect/connecthelper"],returnFirstDependency),define("emby-input",[embyWebComponentsBowerPath+"/emby-input/emby-input"],returnFirstDependency),define("emby-select",[embyWebComponentsBowerPath+"/emby-select/emby-select"],returnFirstDependency),define("emby-slider",[embyWebComponentsBowerPath+"/emby-slider/emby-slider"],returnFirstDependency),define("emby-checkbox",[embyWebComponentsBowerPath+"/emby-checkbox/emby-checkbox"],returnFirstDependency),define("emby-radio",[embyWebComponentsBowerPath+"/emby-radio/emby-radio"],returnFirstDependency),define("emby-textarea",[embyWebComponentsBowerPath+"/emby-textarea/emby-textarea"],returnFirstDependency),define("collectionEditor",[embyWebComponentsBowerPath+"/collectioneditor/collectioneditor"],returnFirstDependency),define("playlistEditor",[embyWebComponentsBowerPath+"/playlisteditor/playlisteditor"],returnFirstDependency),define("recordingCreator",[embyWebComponentsBowerPath+"/recordingcreator/recordingcreator"],returnFirstDependency),define("recordingEditor",[embyWebComponentsBowerPath+"/recordingcreator/recordingeditor"],returnFirstDependency),define("seriesRecordingEditor",[embyWebComponentsBowerPath+"/recordingcreator/seriesrecordingeditor"],returnFirstDependency),define("recordingFields",[embyWebComponentsBowerPath+"/recordingcreator/recordingfields"],returnFirstDependency),define("recordingButton",[embyWebComponentsBowerPath+"/recordingcreator/recordingbutton"],returnFirstDependency),define("recordingHelper",[embyWebComponentsBowerPath+"/recordingcreator/recordinghelper"],returnFirstDependency),define("subtitleEditor",[embyWebComponentsBowerPath+"/subtitleeditor/subtitleeditor"],returnFirstDependency),define("itemIdentifier",[embyWebComponentsBowerPath+"/itemidentifier/itemidentifier"],returnFirstDependency),define("mediaInfo",[embyWebComponentsBowerPath+"/mediainfo/mediainfo"],returnFirstDependency),define("itemContextMenu",[embyWebComponentsBowerPath+"/itemcontextmenu"],returnFirstDependency),define("imageEditor",[embyWebComponentsBowerPath+"/imageeditor/imageeditor"],returnFirstDependency),define("dom",[embyWebComponentsBowerPath+"/dom"],returnFirstDependency),define("searchFields",[embyWebComponentsBowerPath+"/search/searchfields"],returnFirstDependency),define("searchResults",[embyWebComponentsBowerPath+"/search/searchresults"],returnFirstDependency),define("fullscreen-doubleclick",[embyWebComponentsBowerPath+"/fullscreen/fullscreen-doubleclick"],returnFirstDependency),define("fullscreenManager",[embyWebComponentsBowerPath+"/fullscreen/fullscreenmanager","events"],returnFirstDependency),define("headroom",[embyWebComponentsBowerPath+"/headroom/headroom"],returnFirstDependency),define("homescreenSettings",[embyWebComponentsBowerPath+"/homescreensettings/homescreensettings"],returnFirstDependency),define("homescreenSettingsDialog",[embyWebComponentsBowerPath+"/homescreensettings/homescreensettingsdialog"],returnFirstDependency),define("layoutManager",[embyWebComponentsBowerPath+"/layoutmanager","apphost"],getLayoutManager),define("homeSections",[embyWebComponentsBowerPath+"/homesections"],returnFirstDependency),define("playMenu",[embyWebComponentsBowerPath+"/playmenu"],returnFirstDependency),define("refreshDialog",[embyWebComponentsBowerPath+"/refreshdialog/refreshdialog"],returnFirstDependency),define("backdrop",[embyWebComponentsBowerPath+"/backdrop/backdrop"],returnFirstDependency),define("fetchHelper",[embyWebComponentsBowerPath+"/fetchhelper"],returnFirstDependency),define("roundCardStyle",["cardStyle","css!"+embyWebComponentsBowerPath+"/cardbuilder/roundcard"],returnFirstDependency),define("cardStyle",["css!"+embyWebComponentsBowerPath+"/cardbuilder/card"],returnFirstDependency),define("cardBuilder",[embyWebComponentsBowerPath+"/cardbuilder/cardbuilder"],returnFirstDependency),define("peoplecardbuilder",[embyWebComponentsBowerPath+"/cardbuilder/peoplecardbuilder"],returnFirstDependency),define("chaptercardbuilder",[embyWebComponentsBowerPath+"/cardbuilder/chaptercardbuilder"],returnFirstDependency),define("mouseManager",[embyWebComponentsBowerPath+"/input/mouse"],returnFirstDependency),define("flexStyles",["css!"+embyWebComponentsBowerPath+"/flexstyles"],returnFirstDependency),define("deleteHelper",[embyWebComponentsBowerPath+"/deletehelper"],returnFirstDependency),define("tvguide",[embyWebComponentsBowerPath+"/guide/guide"],returnFirstDependency),define("programStyles",["css!"+embyWebComponentsBowerPath+"/guide/programs"],returnFirstDependency),define("guide-settings-dialog",[embyWebComponentsBowerPath+"/guide/guide-settings"],returnFirstDependency),define("syncDialog",[embyWebComponentsBowerPath+"/sync/sync"],returnFirstDependency),define("syncToggle",[embyWebComponentsBowerPath+"/sync/synctoggle"],returnFirstDependency),define("syncJobEditor",[embyWebComponentsBowerPath+"/sync/syncjobeditor"],returnFirstDependency),define("syncJobList",[embyWebComponentsBowerPath+"/sync/syncjoblist"],returnFirstDependency),define("voiceDialog",[embyWebComponentsBowerPath+"/voice/voicedialog"],returnFirstDependency),define("voiceReceiver",[embyWebComponentsBowerPath+"/voice/voicereceiver"],returnFirstDependency),define("voiceProcessor",[embyWebComponentsBowerPath+"/voice/voiceprocessor"],returnFirstDependency),define("viewManager",[embyWebComponentsBowerPath+"/viewmanager/viewmanager"],function(viewManager){return window.ViewManager=viewManager,viewManager.dispatchPageEvents(!0),viewManager}),Dashboard.isRunningInCordova()&&window.MainActivity?define("shell",["cordova/shell"],returnFirstDependency):define("shell",[embyWebComponentsBowerPath+"/shell"],returnFirstDependency),define("sharingmanager",[embyWebComponentsBowerPath+"/sharing/sharingmanager"],returnFirstDependency),Dashboard.isRunningInCordova()?paths.apphost="cordova/apphost":paths.apphost="components/apphost",Dashboard.isRunningInCordova()&&window.MainActivity?(paths.appStorage="cordova/appstorage",paths.filesystem="cordova/filesystem"):(paths.appStorage=getAppStorage(apiClientBowerPath),paths.filesystem=embyWebComponentsBowerPath+"/filesystem");var sha1Path=bowerPath+"/cryptojslib/components/sha1-min",md5Path=bowerPath+"/cryptojslib/components/md5-min",shim={};shim[sha1Path]={deps:[bowerPath+"/cryptojslib/components/core-min"]},shim[md5Path]={deps:[bowerPath+"/cryptojslib/components/core-min"]},requirejs.config({waitSeconds:0,map:{"*":{css:bowerPath+"/emby-webcomponents/require/requirecss",html:bowerPath+"/emby-webcomponents/require/requirehtml",text:bowerPath+"/emby-webcomponents/require/requiretext"}},urlArgs:urlArgs,paths:paths,shim:shim,onError:onRequireJsError}),requirejs.onError=onRequireJsError,define("cryptojs-sha1",[sha1Path],returnFirstDependency),define("cryptojs-md5",[md5Path],returnFirstDependency),define("jstree",[bowerPath+"/jstree/dist/jstree","css!thirdparty/jstree/themes/default/style.min.css"],returnFirstDependency),define("dashboardcss",["css!css/dashboard"],returnFirstDependency),define("jqmtable",["thirdparty/jquerymobile-1.4.5/jqm.table","css!thirdparty/jquerymobile-1.4.5/jqm.table.css"],returnFirstDependency),define("jqmwidget",["thirdparty/jquerymobile-1.4.5/jqm.widget"],returnFirstDependency),define("jqmslider",["thirdparty/jquerymobile-1.4.5/jqm.slider","css!thirdparty/jquerymobile-1.4.5/jqm.slider.css"],returnFirstDependency),define("jqmpopup",["thirdparty/jquerymobile-1.4.5/jqm.popup","css!thirdparty/jquerymobile-1.4.5/jqm.popup.css"],returnFirstDependency),define("jqmlistview",["css!thirdparty/jquerymobile-1.4.5/jqm.listview.css"],returnFirstDependency),define("jqmpanel",["thirdparty/jquerymobile-1.4.5/jqm.panel","css!thirdparty/jquerymobile-1.4.5/jqm.panel.css"],returnFirstDependency),define("slideshow",[embyWebComponentsBowerPath+"/slideshow/slideshow"],returnFirstDependency),define("fetch",[bowerPath+"/fetch/fetch"],returnFirstDependency),define("raf",[embyWebComponentsBowerPath+"/polyfills/raf"],returnFirstDependency),define("functionbind",[embyWebComponentsBowerPath+"/polyfills/bind"],returnFirstDependency),define("arraypolyfills",[embyWebComponentsBowerPath+"/polyfills/array"],returnFirstDependency),define("objectassign",[embyWebComponentsBowerPath+"/polyfills/objectassign"],returnFirstDependency),define("clearButtonStyle",["css!"+embyWebComponentsBowerPath+"/clearbutton"],returnFirstDependency),define("userdataButtons",[embyWebComponentsBowerPath+"/userdatabuttons/userdatabuttons"],returnFirstDependency),define("listView",[embyWebComponentsBowerPath+"/listview/listview"],returnFirstDependency),define("listViewStyle",["css!"+embyWebComponentsBowerPath+"/listview/listview"],returnFirstDependency),define("formDialogStyle",["css!"+embyWebComponentsBowerPath+"/formdialog"],returnFirstDependency),define("indicators",[embyWebComponentsBowerPath+"/indicators/indicators"],returnFirstDependency),define("registrationServices",[embyWebComponentsBowerPath+"/registrationservices/registrationservices"],returnFirstDependency),Dashboard.isRunningInCordova()?(define("iapManager",["cordova/iap"],returnFirstDependency),define("fileupload",["cordova/fileupload"],returnFirstDependency)):(define("iapManager",["components/iap"],returnFirstDependency),define("fileupload",[apiClientBowerPath+"/fileupload"],returnFirstDependency)),define("connectionmanager",[apiClientBowerPath+"/connectionmanager"]),define("cameraRoll",[apiClientBowerPath+"/cameraroll"],returnFirstDependency),define("contentuploader",[apiClientBowerPath+"/sync/contentuploader"],returnFirstDependency),define("serversync",[apiClientBowerPath+"/sync/serversync"],returnFirstDependency),define("multiserversync",[apiClientBowerPath+"/sync/multiserversync"],returnFirstDependency),define("mediasync",[apiClientBowerPath+"/sync/mediasync"],returnFirstDependency),define("idb",[embyWebComponentsBowerPath+"/idb"],returnFirstDependency),define("itemrepository",[apiClientBowerPath+"/sync/itemrepository"],returnFirstDependency),define("useractionrepository",[apiClientBowerPath+"/sync/useractionrepository"],returnFirstDependency),self.Windows?(define("bgtaskregister",["environments/windows-uwp/bgtaskregister"],returnFirstDependency),define("transfermanager",["environments/windows-uwp/transfermanager"],returnFirstDependency),define("filerepository",["environments/windows-uwp/filerepository"],returnFirstDependency)):(define("transfermanager",[apiClientBowerPath+"/sync/transfermanager"],returnFirstDependency),define("filerepository",[apiClientBowerPath+"/sync/filerepository"],returnFirstDependency)),define("swiper",[bowerPath+"/Swiper/dist/js/swiper.min","css!"+bowerPath+"/Swiper/dist/css/swiper.min"],returnFirstDependency),define("scroller",[embyWebComponentsBowerPath+"/scroller/smoothscroller"],returnFirstDependency),define("toast",[embyWebComponentsBowerPath+"/toast/toast"],returnFirstDependency),define("scrollHelper",[embyWebComponentsBowerPath+"/scrollhelper"],returnFirstDependency), -define("touchHelper",[embyWebComponentsBowerPath+"/touchhelper"],returnFirstDependency),define("appSettings",[embyWebComponentsBowerPath+"/appsettings"],updateAppSettings),define("userSettings",[embyWebComponentsBowerPath+"/usersettings/usersettings"],returnFirstDependency),define("userSettingsBuilder",[embyWebComponentsBowerPath+"/usersettings/usersettingsbuilder"],returnFirstDependency),define("material-icons",["css!"+embyWebComponentsBowerPath+"/fonts/material-icons/style"],returnFirstDependency),define("robotoFont",["css!fonts/roboto/style"],returnFirstDependency),define("scrollStyles",["css!"+embyWebComponentsBowerPath+"/scrollstyles"],returnFirstDependency),define("navdrawer",["components/navdrawer/navdrawer"],returnFirstDependency),define("viewcontainer",["components/viewcontainer-lite","css!"+embyWebComponentsBowerPath+"/viewmanager/viewcontainer-lite"],returnFirstDependency),define("queryString",[bowerPath+"/query-string/index"],function(){return queryString}),define("jQuery",[bowerPath+"/jquery/dist/jquery.slim.min"],function(){return window.ApiClient&&(jQuery.ajax=ApiClient.ajax),jQuery}),define("fnchecked",["legacy/fnchecked"],returnFirstDependency),define("dialogHelper",[embyWebComponentsBowerPath+"/dialoghelper/dialoghelper"],function(dialoghelper){return dialoghelper.setOnOpen(onDialogOpen),dialoghelper}),define("inputmanager",["inputManager"],returnFirstDependency),define("historyManager",["embyRouter"],returnFirstDependency),define("headroom-window",["headroom"],createWindowHeadroom),define("appfooter-shared",["appfooter"],createSharedAppFooter),define("skinManager",[],function(){return{loadUserSkin:function(){require(["embyRouter"],function(embyRouter){embyRouter.goHome()})}}}),define("connectionManager",[],function(){return ConnectionManager}),define("apiClientResolver",[],function(){return function(){return window.ApiClient}}),define("embyRouter",[embyWebComponentsBowerPath+"/router"],function(embyRouter){function showItem(item,serverId,options){"string"==typeof item?require(["connectionManager"],function(connectionManager){var apiClient=connectionManager.currentApiClient();apiClient.getItem(apiClient.getCurrentUserId(),item).then(function(item){embyRouter.showItem(item,options)})}):(2==arguments.length&&(options=arguments[1]),embyRouter.show("/"+embyRouter.getRouteUrl(item,options),{item:item}))}return embyRouter.showLocalLogin=function(apiClient,serverId,manualLogin){Dashboard.navigate("login.html?serverid="+serverId)},embyRouter.showVideoOsd=function(){return Dashboard.navigate("videoosd.html")},embyRouter.showSelectServer=function(){Dashboard.isConnectMode()?Dashboard.navigate("selectserver.html"):Dashboard.navigate("login.html")},embyRouter.showWelcome=function(){Dashboard.isConnectMode()?Dashboard.navigate("connectlogin.html?mode=welcome"):Dashboard.navigate("login.html")},embyRouter.showSettings=function(){Dashboard.navigate("mypreferencesmenu.html")},embyRouter.showGuide=function(){Dashboard.navigate("livetv.html?tab=1")},embyRouter.goHome=function(){Dashboard.navigate("home.html")},embyRouter.showSearch=function(){Dashboard.navigate("search.html")},embyRouter.showLiveTV=function(){Dashboard.navigate("livetv.html")},embyRouter.showRecordedTV=function(){Dashboard.navigate("livetv.html?tab=3")},embyRouter.showFavorites=function(){Dashboard.navigate("home.html?tab=1")},embyRouter.showSettings=function(){Dashboard.navigate("mypreferencesmenu.html")},embyRouter.setTitle=function(){},embyRouter.getRouteUrl=function(item,options){if(!item)throw new Error("item cannot be null");if(item.url)return item.url;var context=options?options.context:null,topParentId=options?options.topParentId||options.parentId:null;if("string"==typeof item){if("nextup"===item)return"secondaryitems.html?type=nextup&serverId="+options.serverId;if("livetv"===item)return"guide"===options.section?"livetv.html?tab=1&serverId="+options.serverId:"livetv.html?serverId="+options.serverId}var url,id=item.Id||item.ItemId,itemType=item.Type||(options?options.itemType:null);if("SeriesTimer"==itemType)return"itemdetails.html?seriesTimerId="+id;if("livetv"==item.CollectionType)return"livetv.html";if("channels"==item.CollectionType)return"channels.html";if("folders"!=context){if("movies"==item.CollectionType)return url="movies.html?topParentId="+item.Id,options&&"latest"===options.section&&(url+="&tab=1"),url;if("boxsets"==item.CollectionType)return"itemlist.html?topParentId="+item.Id+"&parentId="+item.Id;if("tvshows"==item.CollectionType)return url="tv.html?topParentId="+item.Id,options&&"latest"===options.section&&(url+="&tab=1"),url;if("music"==item.CollectionType)return"music.html?topParentId="+item.Id;if("games"==item.CollectionType)return id?"itemlist.html?parentId="+id:"#";if("playlists"==item.CollectionType)return"playlists.html?topParentId="+item.Id;if("photos"==item.CollectionType)return"photos.html?topParentId="+item.Id}else if(item.IsFolder&&"BoxSet"!=itemType&&"Series"!=itemType)return id?"itemlist.html?parentId="+id:"#";if("CollectionFolder"==itemType)return"itemlist.html?topParentId="+item.Id+"&parentId="+item.Id;if("PhotoAlbum"==itemType)return"itemlist.html?context=photos&parentId="+id;if("Playlist"==itemType)return"itemdetails.html?id="+id;if("TvChannel"==itemType)return"itemdetails.html?id="+id;if("Channel"==itemType)return"channelitems.html?id="+id;if(item.IsFolder&&"Channel"==item.SourceType||"ChannelFolderItem"==itemType)return"channelitems.html?id="+item.ChannelId+"&folderId="+item.Id;if("Program"==itemType)return"itemdetails.html?id="+id;if("BoxSet"==itemType)return"itemdetails.html?id="+id;if("MusicAlbum"==itemType)return"itemdetails.html?id="+id;if("GameSystem"==itemType)return"itemdetails.html?id="+id;if("Genre"==itemType){var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;default:type="Movie"}return url="secondaryitems.html?type="+type+"&genreId="+id,topParentId&&(url+="&parentId="+topParentId),url}if("MusicGenre"==itemType)return"itemdetails.html?id="+id;if("GameGenre"==itemType)return url="secondaryitems.html?type=Game&genreId="+id,topParentId&&(url+="&parentId="+topParentId),url;if("Studio"==itemType){var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;default:type="Movie"}return url="secondaryitems.html?type="+type+"&studioId="+id,topParentId&&(url+="&parentId="+topParentId),url}if("Person"==itemType)return"itemdetails.html?id="+id;if("Recording"==itemType)return"itemdetails.html?id="+id;if("MusicArtist"==itemType)return"itemdetails.html?id="+id;var contextSuffix=context?"&context="+context:"";return"Series"==itemType||"Season"==itemType||"Episode"==itemType?"itemdetails.html?id="+id+contextSuffix:item.IsFolder?id?"itemlist.html?parentId="+id:"#":"itemdetails.html?id="+id},embyRouter.showItem=showItem,embyRouter})}function updateAppSettings(appSettings){return appSettings.enableExternalPlayers=function(val){return null!=val&&appSettings.set("externalplayers",val.toString()),"true"===appSettings.get("externalplayers")},appSettings}function onDialogOpen(dlg){dlg.classList.contains("background-theme-a")||dlg.classList.contains("actionSheet")||(dlg.classList.add("background-theme-b"),dlg.classList.add("ui-body-b"))}function initRequireWithBrowser(browser){var bowerPath=getBowerPath(),apiClientBowerPath=bowerPath+"/emby-apiclient",embyWebComponentsBowerPath=bowerPath+"/emby-webcomponents";Dashboard.isRunningInCordova()&&browser.android?define("apiclient",["bower_components/emby-apiclient/apiclient"],returnFirstDependency):define("apiclient",["bower_components/emby-apiclient/apiclient"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.safari?define("actionsheet",["cordova/actionsheet"],returnFirstDependency):define("actionsheet",["webActionSheet"],returnFirstDependency),"registerElement"in document?define("registerElement",[]):browser.msie?define("registerElement",[bowerPath+"/webcomponentsjs/webcomponents-lite.min.js"],returnFirstDependency):define("registerElement",[bowerPath+"/document-register-element/build/document-register-element"],returnFirstDependency),window.chrome&&window.chrome.sockets?define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery-chrome"],returnFirstDependency):Dashboard.isRunningInCordova()&&browser.android?define("serverdiscovery",["cordova/serverdiscovery"],returnFirstDependency):Dashboard.isRunningInCordova()&&browser.safari?define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery-chrome"],returnFirstDependency):define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.safari?define("imageFetcher",["cordova/imagestore"],returnFirstDependency):define("imageFetcher",[embyWebComponentsBowerPath+"/images/basicimagefetcher"],returnFirstDependency);var preferNativeAlerts=browser.tv;preferNativeAlerts&&window.alert?define("alert",[embyWebComponentsBowerPath+"/alert/nativealert"],returnFirstDependency):define("alert",[embyWebComponentsBowerPath+"/alert/alert"],returnFirstDependency),define("dialog",[embyWebComponentsBowerPath+"/dialog/dialog"],returnFirstDependency),preferNativeAlerts&&window.confirm?define("confirm",[embyWebComponentsBowerPath+"/confirm/nativeconfirm"],returnFirstDependency):define("confirm",[embyWebComponentsBowerPath+"/confirm/confirm"],returnFirstDependency);var preferNativePrompt=preferNativeAlerts||browser.xboxOne;preferNativePrompt&&window.confirm?define("prompt",[embyWebComponentsBowerPath+"/prompt/nativeprompt"],returnFirstDependency):define("prompt",[embyWebComponentsBowerPath+"/prompt/prompt"],returnFirstDependency),browser.tizen||browser.operaTv?define("loading",[embyWebComponentsBowerPath+"/loading/loading-legacy"],returnFirstDependency):define("loading",[embyWebComponentsBowerPath+"/loading/loading-lite"],returnFirstDependency),define("multi-download",[embyWebComponentsBowerPath+"/multidownload"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.android?(define("fileDownloader",["cordova/filedownloader"],returnFirstDependency),define("localassetmanager",["cordova/localassetmanager"],returnFirstDependency)):(define("fileDownloader",[embyWebComponentsBowerPath+"/filedownloader"],returnFirstDependency),define("localassetmanager",[apiClientBowerPath+"/localassetmanager"],returnFirstDependency)),define("screenLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.android?(define("resourceLockManager",[embyWebComponentsBowerPath+"/resourcelocks/resourcelockmanager"],returnFirstDependency),define("wakeLock",["cordova/wakelock"],returnFirstDependency),define("networkLock",["cordova/networklock"],returnFirstDependency)):(define("resourceLockManager",[embyWebComponentsBowerPath+"/resourcelocks/resourcelockmanager"],returnFirstDependency),define("wakeLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency),define("networkLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency)),Dashboard.isRunningInCordova()?define("castSenderApiLoader",[],getDummyCastSenderApiLoader):define("castSenderApiLoader",[],getCastSenderApiLoader)}function init(){Dashboard.isRunningInCordova()&&browserInfo.android&&define("nativedirectorychooser",["cordova/nativedirectorychooser"],returnFirstDependency),Dashboard.isRunningInCordova()&&browserInfo.android?define("localsync",["cordova/localsync"],returnFirstDependency):define("localsync",["scripts/localsync"],returnFirstDependency),define("livetvcss",["css!css/livetv.css"],returnFirstDependency),define("detailtablecss",["css!css/detailtable.css"],returnFirstDependency),define("autoorganizetablecss",["css!css/autoorganizetable.css"],returnFirstDependency),define("buttonenabled",["legacy/buttonenabled"],returnFirstDependency),initAfterDependencies()}function getRequirePromise(deps){return new Promise(function(resolve,reject){require(deps,resolve)})}function initAfterDependencies(){var list=[];window.fetch||list.push("fetch"),"function"!=typeof Object.assign&&list.push("objectassign"),Array.prototype.filter||list.push("arraypolyfills"),Function.prototype.bind||list.push("functionbind"),window.requestAnimationFrame||list.push("raf"),require(list,function(){createConnectionManager().then(function(){console.log("initAfterDependencies promises resolved"),require(["globalize"],function(globalize){window.Globalize=globalize,Promise.all([loadCoreDictionary(globalize),loadSharedComponentsDictionary(globalize)]).then(onGlobalizeInit)})})})}function loadSharedComponentsDictionary(globalize){var baseUrl="bower_components/emby-webcomponents/strings/",languages=["ar","bg-bg","ca","cs","da","de","el","en-gb","en-us","es-ar","es-mx","es","fi","fr","gsw","he","hr","hu","id","it","kk","ko","lt-lt","ms","nb","nl","pl","pt-br","pt-pt","ro","ru","sk","sl-si","sv","tr","uk","vi","zh-cn","zh-hk","zh-tw"],translations=languages.map(function(i){return{lang:i,path:baseUrl+i+".json"}});globalize.loadStrings({name:"sharedcomponents",translations:translations})}function loadCoreDictionary(globalize){var baseUrl="strings/",languages=["ar","bg-bg","ca","cs","da","de","el","en-gb","en-us","es-ar","es-mx","es","fa","fi","fr","gsw","he","hr","hu","id","it","kk","ko","ms","nb","nl","pl","pt-br","pt-pt","ro","ru","sl-si","sv","tr","uk","vi","zh-cn","zh-hk","zh-tw"],translations=languages.map(function(i){return{lang:i,path:baseUrl+i+".json"}});return globalize.defaultModule("core"),globalize.loadStrings({name:"core",translations:translations})}function onGlobalizeInit(){document.title=Globalize.translateDocument(document.title,"core"),require(["apphost"],function(appHost){loadPlugins([],appHost,browserInfo).then(onAppReady)})}function defineRoute(newRoute,dictionary){var baseRoute=Emby.Page.baseUrl(),path=newRoute.path;path=path.replace(baseRoute,""),console.log("Defining route: "+path),newRoute.dictionary=newRoute.dictionary||dictionary||"core",Emby.Page.addRoute(path,newRoute)}function defineCoreRoutes(appHost){console.log("Defining core routes"),defineRoute({path:"/addplugin.html",dependencies:[],autoFocus:!1,roles:"admin",controller:"scripts/addpluginpage"}),defineRoute({path:"/appservices.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/autoorganizelog.html",dependencies:["scripts/taskbutton","autoorganizetablecss"],controller:"dashboard/autoorganizelog",roles:"admin"}),defineRoute({path:"/autoorganizesmart.html",dependencies:["emby-button"],controller:"dashboard/autoorganizesmart",autoFocus:!1,roles:"admin"}),defineRoute({path:"/autoorganizetv.html",dependencies:["emby-checkbox","emby-input","emby-button","emby-select","emby-collapse"],controller:"dashboard/autoorganizetv",autoFocus:!1,roles:"admin"}),defineRoute({path:"/channelitems.html",dependencies:[],autoFocus:!1,transition:"fade"}),defineRoute({path:"/channels.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/channels"}),defineRoute({path:"/channelsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/cinemamodeconfiguration.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/connectlogin.html",dependencies:["emby-button","emby-input"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/connectlogin"}),defineRoute({path:"/dashboard.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dashboardgeneral.html",controller:"dashboard/dashboardgeneral",autoFocus:!1,roles:"admin"}),defineRoute({path:"/dashboardhosting.html",dependencies:["emby-input","emby-button"],autoFocus:!1,roles:"admin",controller:"dashboard/dashboardhosting"}),defineRoute({path:"/device.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/devices.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/devicesupload.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaprofile.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaprofiles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaserversettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnasettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/edititemmetadata.html",dependencies:[],controller:"scripts/edititemmetadata",autoFocus:!1}),defineRoute({path:"/encodingsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/forgotpassword.html",dependencies:["emby-input","emby-button"],anonymous:!0,startup:!0,controller:"scripts/forgotpassword"}),defineRoute({path:"/forgotpasswordpin.html",dependencies:["emby-input","emby-button"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/forgotpasswordpin"}),defineRoute({path:"/gamegenres.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/games.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamesrecommended.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamestudios.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamesystems.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/home.html",dependencies:[],autoFocus:!1,controller:"scripts/indexpage",transition:"fade",type:"home"}),defineRoute({path:"/index.html",dependencies:[],autoFocus:!1,isDefaultRoute:!0}),defineRoute({path:"/itemdetails.html",dependencies:["emby-button","scripts/livetvcomponents","paper-icon-button-light","emby-itemscontainer"],controller:"scripts/itemdetailpage",autoFocus:!1,transition:"fade"}),defineRoute({path:"/itemlist.html",dependencies:[],autoFocus:!1,controller:"scripts/itemlistpage",transition:"fade"}),defineRoute({path:"/kids.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/library.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/librarydisplay.html",dependencies:[],autoFocus:!1,roles:"admin",controller:"dashboard/librarydisplay"}),defineRoute({path:"/librarysettings.html",dependencies:["emby-collapse","emby-input","emby-button","emby-select"],autoFocus:!1,roles:"admin",controller:"dashboard/librarysettings"}),defineRoute({path:"/livetv.html",dependencies:["emby-button","livetvcss"],controller:"scripts/livetvsuggested",autoFocus:!1,transition:"fade"}),defineRoute({path:"/livetvguideprovider.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvitems.html",dependencies:[],autoFocus:!1,controller:"scripts/livetvitems"}),defineRoute({path:"/livetvseriestimer.html",dependencies:["emby-checkbox","emby-input","emby-button","emby-collapse","scripts/livetvcomponents","scripts/livetvseriestimer","livetvcss"],autoFocus:!1,controller:"scripts/livetvseriestimer"}),defineRoute({path:"/livetvsettings.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/livetvstatus.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvtuner.html",dependencies:[],autoFocus:!1,roles:"admin",controller:"dashboard/livetvtuner"}),defineRoute({path:"/log.html",dependencies:["emby-checkbox"],roles:"admin",controller:"dashboard/logpage"}),defineRoute({path:"/login.html",dependencies:["emby-button","emby-input"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/loginpage"}),defineRoute({path:"/metadataadvanced.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadataimages.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadatanfo.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadatasubtitles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/movies.html",dependencies:["emby-button"],autoFocus:!1,controller:"scripts/moviesrecommended",transition:"fade"}),defineRoute({path:"/music.html",dependencies:[],controller:"scripts/musicrecommended",autoFocus:!1,transition:"fade"}),defineRoute({path:"/mypreferencesdisplay.html",dependencies:["emby-checkbox","emby-button","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferencesdisplay"}),defineRoute({path:"/mypreferenceshome.html",dependencies:["emby-checkbox","emby-button","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferenceshome"}),defineRoute({path:"/mypreferenceslanguages.html",dependencies:["emby-button","emby-checkbox","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferenceslanguages"}),defineRoute({path:"/mypreferencesmenu.html",dependencies:["emby-button"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferencescommon"}),defineRoute({path:"/myprofile.html",dependencies:["emby-button","emby-collapse","emby-checkbox","emby-input"],autoFocus:!1,transition:"fade",controller:"scripts/myprofile"}),defineRoute({path:"/offline/offline.html",transition:"false",controller:"offline/offline",dependencies:[],anonymous:!0,startup:!1}),defineRoute({path:"/mysync.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/mysync"}),defineRoute({path:"/camerauploadsettings.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/camerauploadsettings"}),defineRoute({path:"/mysyncjob.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/syncjob"}),defineRoute({path:"/mysyncsettings.html",dependencies:["emby-checkbox","emby-input","emby-button","paper-icon-button-light"],autoFocus:!1,transition:"fade",controller:"scripts/mysyncsettings"}),defineRoute({path:"/notificationlist.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/notificationsetting.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/notificationsettings.html",controller:"scripts/notificationsettings",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/nowplaying.html",dependencies:["paper-icon-button-light","emby-slider","emby-button","emby-input","emby-itemscontainer"],controller:"scripts/nowplayingpage",autoFocus:!1,transition:"fade",fullscreen:!0,supportsThemeMedia:!0}),defineRoute({path:"/photos.html",dependencies:[],autoFocus:!1,transition:"fade"}),defineRoute({path:"/playbackconfiguration.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/playlists.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/playlists"}),defineRoute({path:"/plugincatalog.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/plugins.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/reports.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/scheduledtask.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/scheduledtasks.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/search.html",dependencies:[],controller:"scripts/searchpage"}),defineRoute({path:"/secondaryitems.html",dependencies:[],autoFocus:!1,controller:"scripts/secondaryitems"}),defineRoute({path:"/selectserver.html",dependencies:["listViewStyle","emby-button"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/selectserver"}),defineRoute({path:"/serversecurity.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/shared.html",dependencies:[],autoFocus:!1,anonymous:!0}),defineRoute({path:"/streamingsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/support.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/supporterkey.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/syncactivity.html",dependencies:[],autoFocus:!1,controller:"scripts/syncactivity"}),defineRoute({path:"/syncsettings.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/tv.html",dependencies:["paper-icon-button-light","emby-button"],autoFocus:!1,controller:"scripts/tvrecommended",transition:"fade"}),defineRoute({path:"/useredit.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userlibraryaccess.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/usernew.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userparentalcontrol.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userpassword.html",dependencies:["emby-input","emby-button","emby-checkbox"],autoFocus:!1,controller:"scripts/userpasswordpage"}),defineRoute({path:"/userprofiles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/wizardagreement.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardcomponents.html",dependencies:["dashboardcss","emby-button","emby-input","emby-select"],autoFocus:!1,anonymous:!0,controller:"dashboard/wizardcomponents"}),defineRoute({path:"/wizardfinish.html",dependencies:["emby-button","dashboardcss"],autoFocus:!1,anonymous:!0,controller:"dashboard/wizardfinishpage"}),defineRoute({path:"/wizardlibrary.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardsettings.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardstart.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizarduser.html",dependencies:["dashboardcss","emby-input"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/videoosd.html",dependencies:[],transition:"fade",controller:"scripts/videoosd",autoFocus:!1,type:"video-osd",supportsThemeMedia:!0,fullscreen:!0}),defineRoute({path:"/configurationpage",dependencies:["jQuery"],autoFocus:!1,enableCache:!1,enableContentQueryString:!0,roles:"admin"}),defineRoute({path:"/",isDefaultRoute:!0,autoFocus:!1,dependencies:[]})}function loadPlugins(externalPlugins,appHost,browser,shell){console.log("Loading installed plugins");var list=["bower_components/emby-webcomponents/playback/playbackvalidation","bower_components/emby-webcomponents/playback/playaccessvalidation"];Dashboard.isRunningInCordova()&&browser.android?(document.createElement("audio").canPlayType("audio/flac").replace(/no/,"")&&document.createElement("audio").canPlayType('audio/ogg; codecs="opus"').replace(/no/,"")?window.VlcAudio=!0:window.VlcAudio=!0,list.push("cordova/vlcplayer")):Dashboard.isRunningInCordova()&&browser.safari&&list.push("cordova/audioplayer"),list.push("bower_components/emby-webcomponents/htmlaudioplayer/plugin"),Dashboard.isRunningInCordova()&&browser.safari&&list.push("cordova/chromecast"),Dashboard.isRunningInCordova()&&browser.android&&list.push("cordova/externalplayer"),list.push("bower_components/emby-webcomponents/htmlvideoplayer/plugin"),appHost.supports("remotecontrol")&&(list.push("bower_components/emby-webcomponents/sessionplayer"),browser.chrome&&list.push("bower_components/emby-webcomponents/chromecastplayer")),list.push("bower_components/emby-webcomponents/youtubeplayer/plugin");for(var i=0,length=externalPlugins.length;i=1600?5:6,options={SortBy:"DatePlayed",SortOrder:"Descending",IncludeItemTypes:"Episode",Filters:"IsResumable",Limit:limit,Recursive:!0,Fields:"PrimaryImageAspectRatio,SeriesInfo,UserData,BasicSyncInfo",ExcludeLocationTypes:"Virtual",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){result.Items.length?view.querySelector("#resumableSection").classList.remove("hide"):view.querySelector("#resumableSection").classList.add("hide");var allowBottomPadding=!enableScrollX(),container=view.querySelector("#resumableItems"),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=!1;cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:getThumbShape(),scalable:!0,showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!cardLayout,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis})})}function onBeforeTabChange(e){preLoadTab(view,parseInt(e.detail.selectedTabIndex))}function onTabChange(e){var newIndex=parseInt(e.detail.selectedTabIndex);loadTab(view,newIndex)}function initTabs(){var tabsReplaced=mainTabsManager.setTabs(view,currentTabIndex,getTabs);if(tabsReplaced){var viewTabs=document.querySelector(".tabs-viewmenubar");viewTabs.addEventListener("beforetabchange",onBeforeTabChange),viewTabs.addEventListener("tabchange",onTabChange),libraryBrowser.configurePaperLibraryTabs(view,viewTabs,view.querySelectorAll(".pageTabContent"),[0,1,2,4,5,6]),viewTabs.triggerBeforeTabChange||viewTabs.addEventListener("ready",function(){viewTabs.triggerBeforeTabChange()})}}function getTabController(page,index,callback){var depends=[];switch(index){case 0:break;case 1:depends.push("scripts/tvlatest");break;case 2:depends.push("scripts/tvshows");break;case 3:depends.push("scripts/tvupcoming");break;case 4:depends.push("scripts/tvgenres");break;case 5:depends.push("scripts/tvstudios");break;case 6:depends.push("scripts/searchtab")}require(depends,function(controllerFactory){var tabContent;0==index&&(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),self.tabContent=tabContent);var controller=tabControllers[index];controller||(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),controller=0===index?self:6===index?new controllerFactory(view,tabContent,{collectionType:"tvshows",parentId:params.topParentId}):new controllerFactory(view,params,tabContent),tabControllers[index]=controller,controller.initTab&&controller.initTab()),callback(controller)})}function preLoadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&controller.preRender&&controller.preRender()})}function loadTab(page,index){currentTabIndex=index,getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&(renderedTabs.push(index),controller.renderTab())})}function onPlaybackStop(e,state){state.NowPlayingItem&&"Video"==state.NowPlayingItem.MediaType&&(renderedTabs=[],mainTabsManager.getTabsElement().triggerTabChange())}function onWebSocketMessage(e,data){var msg=data;"UserDataChanged"===msg.MessageType&&msg.Data.UserId==Dashboard.getCurrentUserId()&&(renderedTabs=[])}var self=this,currentTabIndex=parseInt(params.tab||getDefaultTabIndex(params.topParentId));self.initTab=function(){var tabContent=self.tabContent,resumableItemsContainer=tabContent.querySelector("#resumableItems");enableScrollX()?(resumableItemsContainer.classList.add("hiddenScrollX"),resumableItemsContainer.classList.remove("vertical-wrap")):(resumableItemsContainer.classList.remove("hiddenScrollX"),resumableItemsContainer.classList.add("vertical-wrap")),categorysyncbuttons.init(tabContent)},self.renderTab=function(){reload()};var tabControllers=[],renderedTabs=[];enableScrollX()?view.querySelector("#resumableItems").classList.add("hiddenScrollX"):view.querySelector("#resumableItems").classList.remove("hiddenScrollX"),view.addEventListener("viewbeforeshow",function(e){if(initTabs(),!view.getAttribute("data-title")){var parentId=params.topParentId;parentId?ApiClient.getItem(Dashboard.getCurrentUserId(),parentId).then(function(item){view.setAttribute("data-title",item.Name),LibraryMenu.setTitle(item.Name)}):(view.setAttribute("data-title",Globalize.translate("TabShows")),LibraryMenu.setTitle(Globalize.translate("TabShows")))}var tabs=mainTabsManager.getTabsElement();tabs.triggerBeforeTabChange&&tabs.triggerBeforeTabChange(),Events.on(playbackManager,"playbackstop",onPlaybackStop),Events.on(ApiClient,"websocketmessage",onWebSocketMessage)}),view.addEventListener("viewshow",function(e){mainTabsManager.getTabsElement().triggerTabChange()}),view.addEventListener("viewbeforehide",function(e){Events.off(playbackManager,"playbackstop",onPlaybackStop),Events.off(ApiClient,"websocketmessage",onWebSocketMessage)}),view.addEventListener("viewdestroy",function(e){tabControllers.forEach(function(t){t.destroy&&t.destroy()})})}}); \ No newline at end of file +define(["layoutManager","loading","libraryBrowser","dom","components/categorysyncbuttons","userSettings","cardBuilder","apphost","playbackManager","mainTabsManager","scrollStyles","emby-itemscontainer","emby-button"],function(layoutManager,loading,libraryBrowser,dom,categorysyncbuttons,userSettings,cardBuilder,appHost,playbackManager,mainTabsManager){"use strict";function getTabs(){return[{name:Globalize.translate("TabSuggestions")},{name:Globalize.translate("TabLatest")},{name:Globalize.translate("TabShows")},{name:Globalize.translate("TabUpcoming")},{name:Globalize.translate("TabGenres")},{name:Globalize.translate("TabNetworks")},{name:Globalize.translate("TabEpisodes")},{name:Globalize.translate("ButtonSearch")}]}function getDefaultTabIndex(folderId){switch(userSettings.get("landing-"+folderId)){case"latest":return 1;case"shows":return 2;case"favorites":return 0;case"genres":return 4;default:return 0}}return function(view,params){function reload(){loading.show(),loadResume(),loadNextUp()}function loadNextUp(){var query={Limit:24,Fields:"PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo",UserId:Dashboard.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",EnableTotalRecordCount:!1};query.ParentId=LibraryMenu.getTopParentId(),ApiClient.getNextUpEpisodes(query).then(function(result){result.Items.length?view.querySelector(".noNextUpItems").classList.add("hide"):view.querySelector(".noNextUpItems").classList.remove("hide");var container=view.querySelector("#nextUpItems"),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=!1;cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:"backdrop",scalable:!0,showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!cardLayout,overlayPlayButton:!0,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis}),loading.hide()})}function enableScrollX(){return!layoutManager.desktop}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function loadResume(){var parentId=LibraryMenu.getTopParentId(),screenWidth=dom.getWindowSize().innerWidth,limit=screenWidth>=1600?5:6,options={SortBy:"DatePlayed",SortOrder:"Descending",IncludeItemTypes:"Episode",Filters:"IsResumable",Limit:limit,Recursive:!0,Fields:"PrimaryImageAspectRatio,SeriesInfo,UserData,BasicSyncInfo",ExcludeLocationTypes:"Virtual",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){result.Items.length?view.querySelector("#resumableSection").classList.remove("hide"):view.querySelector("#resumableSection").classList.add("hide");var allowBottomPadding=!enableScrollX(),container=view.querySelector("#resumableItems"),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=!1;cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:getThumbShape(),scalable:!0,showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!cardLayout,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis})})}function onBeforeTabChange(e){preLoadTab(view,parseInt(e.detail.selectedTabIndex))}function onTabChange(e){var newIndex=parseInt(e.detail.selectedTabIndex);loadTab(view,newIndex)}function initTabs(){var tabsReplaced=mainTabsManager.setTabs(view,currentTabIndex,getTabs);if(tabsReplaced){var viewTabs=document.querySelector(".tabs-viewmenubar");viewTabs.addEventListener("beforetabchange",onBeforeTabChange),viewTabs.addEventListener("tabchange",onTabChange),libraryBrowser.configurePaperLibraryTabs(view,viewTabs,view.querySelectorAll(".pageTabContent"),[0,1,2,4,5,6]),viewTabs.triggerBeforeTabChange||viewTabs.addEventListener("ready",function(){viewTabs.triggerBeforeTabChange()})}}function getTabController(page,index,callback){var depends=[];switch(index){case 0:break;case 1:depends.push("scripts/tvlatest");break;case 2:depends.push("scripts/tvshows");break;case 3:depends.push("scripts/tvupcoming");break;case 4:depends.push("scripts/tvgenres");break;case 5:depends.push("scripts/tvstudios");break;case 6:depends.push("scripts/episodes");break;case 7:depends.push("scripts/searchtab")}require(depends,function(controllerFactory){var tabContent;0==index&&(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),self.tabContent=tabContent);var controller=tabControllers[index];controller||(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),controller=0===index?self:7===index?new controllerFactory(view,tabContent,{collectionType:"tvshows",parentId:params.topParentId}):new controllerFactory(view,params,tabContent),tabControllers[index]=controller,controller.initTab&&controller.initTab()),callback(controller)})}function preLoadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&controller.preRender&&controller.preRender()})}function loadTab(page,index){currentTabIndex=index,getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&(renderedTabs.push(index),controller.renderTab())})}function onPlaybackStop(e,state){state.NowPlayingItem&&"Video"==state.NowPlayingItem.MediaType&&(renderedTabs=[],mainTabsManager.getTabsElement().triggerTabChange())}function onWebSocketMessage(e,data){var msg=data;"UserDataChanged"===msg.MessageType&&msg.Data.UserId==Dashboard.getCurrentUserId()&&(renderedTabs=[])}var self=this,currentTabIndex=parseInt(params.tab||getDefaultTabIndex(params.topParentId));self.initTab=function(){var tabContent=self.tabContent,resumableItemsContainer=tabContent.querySelector("#resumableItems");enableScrollX()?(resumableItemsContainer.classList.add("hiddenScrollX"),resumableItemsContainer.classList.remove("vertical-wrap")):(resumableItemsContainer.classList.remove("hiddenScrollX"),resumableItemsContainer.classList.add("vertical-wrap")),categorysyncbuttons.init(tabContent)},self.renderTab=function(){reload()};var tabControllers=[],renderedTabs=[];enableScrollX()?view.querySelector("#resumableItems").classList.add("hiddenScrollX"):view.querySelector("#resumableItems").classList.remove("hiddenScrollX"),view.addEventListener("viewbeforeshow",function(e){if(initTabs(),!view.getAttribute("data-title")){var parentId=params.topParentId;parentId?ApiClient.getItem(Dashboard.getCurrentUserId(),parentId).then(function(item){view.setAttribute("data-title",item.Name),LibraryMenu.setTitle(item.Name)}):(view.setAttribute("data-title",Globalize.translate("TabShows")),LibraryMenu.setTitle(Globalize.translate("TabShows")))}var tabs=mainTabsManager.getTabsElement();tabs.triggerBeforeTabChange&&tabs.triggerBeforeTabChange(),Events.on(playbackManager,"playbackstop",onPlaybackStop),Events.on(ApiClient,"websocketmessage",onWebSocketMessage)}),view.addEventListener("viewshow",function(e){mainTabsManager.getTabsElement().triggerTabChange()}),view.addEventListener("viewbeforehide",function(e){Events.off(playbackManager,"playbackstop",onPlaybackStop),Events.off(ApiClient,"websocketmessage",onWebSocketMessage)}),view.addEventListener("viewdestroy",function(e){tabControllers.forEach(function(t){t.destroy&&t.destroy()})})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userparentalcontrol.js b/dashboard-ui/scripts/userparentalcontrol.js index bead04174f..4fb2c3aaaa 100644 --- a/dashboard-ui/scripts/userparentalcontrol.js +++ b/dashboard-ui/scripts/userparentalcontrol.js @@ -1 +1 @@ -define(["jQuery","datetime","loading","listViewStyle","paper-icon-button-light"],function($,datetime,loading){"use strict";function populateRatings(allParentalRatings,page){var html="";html+="";var i,length,rating,ratings=[];for(i=0,length=allParentalRatings.length;i"+rating.Name+"";$("#selectMaxParentalRating",page).html(html)}function loadUnratedItems(page,user){var items=[{name:Globalize.translate("OptionBlockBooks"),value:"Book"},{name:Globalize.translate("OptionBlockGames"),value:"Game"},{name:Globalize.translate("OptionBlockChannelContent"),value:"ChannelContent"},{name:Globalize.translate("OptionBlockLiveTvChannels"),value:"LiveTvChannel"},{name:Globalize.translate("OptionBlockMovies"),value:"Movie"},{name:Globalize.translate("OptionBlockMusic"),value:"Music"},{name:Globalize.translate("OptionBlockTrailers"),value:"Trailer"},{name:Globalize.translate("OptionBlockTvShows"),value:"Series"},{name:Globalize.translate("OptionBlockOthers"),value:"Other"}],html="";html+='

'+Globalize.translate("HeaderBlockItemsWithNoRating")+"

",html+='
';for(var i=0,length=items.length;i"+item.name+""}html+="
",$(".blockUnratedItems",page).html(html).trigger("create")}function loadUser(page,user,allParentalRatings){LibraryMenu.setTitle(user.Name),loadUnratedItems(page,user),loadBlockedTags(page,user.Policy.BlockedTags),populateRatings(allParentalRatings,page);var ratingValue="";if(user.Policy.MaxParentalRating)for(var i=0,length=allParentalRatings.length;i=rating.Value&&(ratingValue=rating.Value)}$("#selectMaxParentalRating",page).val(ratingValue),user.Policy.IsAdministrator?$(".accessScheduleSection",page).hide():$(".accessScheduleSection",page).show(),renderAccessSchedule(page,user.Policy.AccessSchedules||[]),loading.hide()}function loadBlockedTags(page,tags){var html=tags.map(function(h){var li='
';return li+='
',li+='

',li+=h,li+="

",li+="
",li+='',li+="
"}).join("");html&&(html='
'+html+"
");var elem=$(".blockedTags",page).html(html).trigger("create");$(".btnDeleteTag",elem).on("click",function(){var tag=this.getAttribute("data-tag"),newTags=tags.filter(function(t){return t!=tag});loadBlockedTags(page,newTags)})}function deleteAccessSchedule(page,schedules,index){schedules.splice(index,1),renderAccessSchedule(page,schedules)}function renderAccessSchedule(page,schedules){var html="",index=0;html+=schedules.map(function(a){var itemHtml="";return itemHtml+='
',itemHtml+='
',itemHtml+='

',itemHtml+=Globalize.translate("Option"+a.DayOfWeek),itemHtml+="

",itemHtml+='
'+getDisplayTime(a.StartHour)+" - "+getDisplayTime(a.EndHour)+"
",itemHtml+="
",itemHtml+='',itemHtml+="
",index++,itemHtml}).join("");var accessScheduleList=page.querySelector(".accessScheduleList");accessScheduleList.innerHTML=html,$(".btnDelete",accessScheduleList).on("click",function(){deleteAccessSchedule(page,schedules,parseInt(this.getAttribute("data-index")))})}function onSaveComplete(page){loading.hide(),require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))})}function saveUser(user,page){user.Policy.MaxParentalRating=$("#selectMaxParentalRating",page).val()||null,user.Policy.BlockUnratedItems=$(".chkUnratedItem",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-itemtype")}),user.Policy.AccessSchedules=getSchedulesFromPage(page),user.Policy.BlockedTags=getBlockedTagsFromPage(page),ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){onSaveComplete(page)})}function getDisplayTime(hours){var minutes=0,pct=hours%1;return pct&&(minutes=parseInt(60*pct)),datetime.getDisplayTime(new Date(2e3,1,1,hours,minutes,0,0))}function showSchedulePopup(page,schedule,index){schedule=schedule||{},require(["components/accessschedule/accessschedule"],function(accessschedule){accessschedule.show({schedule:schedule}).then(function(updatedSchedule){var schedules=getSchedulesFromPage(page);index==-1&&(index=schedules.length),schedules[index]=updatedSchedule,renderAccessSchedule(page,schedules)})})}function getSchedulesFromPage(page){return $(".liSchedule",page).map(function(){return{DayOfWeek:this.getAttribute("data-day"),StartHour:this.getAttribute("data-start"),EndHour:this.getAttribute("data-end")}}).get()}function getBlockedTagsFromPage(page){return $(".blockedTag",page).map(function(){return this.getAttribute("data-tag")}).get()}function showBlockedTagPopup(page){require(["prompt"],function(prompt){prompt({label:Globalize.translate("LabelTag")}).then(function(value){var tags=getBlockedTagsFromPage(page);tags.indexOf(value)==-1&&(tags.push(value),loadBlockedTags(page,tags))})})}window.UserParentalControlPage={onSubmit:function(){var page=$(this).parents(".page");loading.show();var userId=getParameterByName("userId");return ApiClient.getUser(userId).then(function(result){saveUser(result,page)}),!1}},$(document).on("pageinit","#userParentalControlPage",function(){var page=this;$(".btnAddSchedule",page).on("click",function(){showSchedulePopup(page,{},-1)}),$(".btnAddBlockedTag",page).on("click",function(){showBlockedTagPopup(page)}),$(".userParentalControlForm").off("submit",UserParentalControlPage.onSubmit).on("submit",UserParentalControlPage.onSubmit)}).on("pageshow","#userParentalControlPage",function(){var page=this;loading.show();var userId=getParameterByName("userId"),promise1=ApiClient.getUser(userId),promise2=ApiClient.getParentalRatings();Promise.all([promise1,promise2]).then(function(responses){loadUser(page,responses[0],responses[1])})})}); \ No newline at end of file +define(["jQuery","datetime","loading","listViewStyle","paper-icon-button-light"],function($,datetime,loading){"use strict";function populateRatings(allParentalRatings,page){var html="";html+="";var i,length,rating,ratings=[];for(i=0,length=allParentalRatings.length;i"+rating.Name+"";$("#selectMaxParentalRating",page).html(html)}function loadUnratedItems(page,user){var items=[{name:Globalize.translate("OptionBlockBooks"),value:"Book"},{name:Globalize.translate("OptionBlockGames"),value:"Game"},{name:Globalize.translate("OptionBlockChannelContent"),value:"ChannelContent"},{name:Globalize.translate("OptionBlockLiveTvChannels"),value:"LiveTvChannel"},{name:Globalize.translate("OptionBlockMovies"),value:"Movie"},{name:Globalize.translate("OptionBlockMusic"),value:"Music"},{name:Globalize.translate("OptionBlockTrailers"),value:"Trailer"},{name:Globalize.translate("OptionBlockTvShows"),value:"Series"}],html="";html+='

'+Globalize.translate("HeaderBlockItemsWithNoRating")+"

",html+='
';for(var i=0,length=items.length;i"+item.name+""}html+="
",$(".blockUnratedItems",page).html(html).trigger("create")}function loadUser(page,user,allParentalRatings){LibraryMenu.setTitle(user.Name),loadUnratedItems(page,user),loadBlockedTags(page,user.Policy.BlockedTags),populateRatings(allParentalRatings,page);var ratingValue="";if(user.Policy.MaxParentalRating)for(var i=0,length=allParentalRatings.length;i=rating.Value&&(ratingValue=rating.Value)}$("#selectMaxParentalRating",page).val(ratingValue),user.Policy.IsAdministrator?$(".accessScheduleSection",page).hide():$(".accessScheduleSection",page).show(),renderAccessSchedule(page,user.Policy.AccessSchedules||[]),loading.hide()}function loadBlockedTags(page,tags){var html=tags.map(function(h){var li='
';return li+='
',li+='

',li+=h,li+="

",li+="
",li+='',li+="
"}).join("");html&&(html='
'+html+"
");var elem=$(".blockedTags",page).html(html).trigger("create");$(".btnDeleteTag",elem).on("click",function(){var tag=this.getAttribute("data-tag"),newTags=tags.filter(function(t){return t!=tag});loadBlockedTags(page,newTags)})}function deleteAccessSchedule(page,schedules,index){schedules.splice(index,1),renderAccessSchedule(page,schedules)}function renderAccessSchedule(page,schedules){var html="",index=0;html+=schedules.map(function(a){var itemHtml="";return itemHtml+='
',itemHtml+='
',itemHtml+='

',itemHtml+=Globalize.translate("Option"+a.DayOfWeek),itemHtml+="

",itemHtml+='
'+getDisplayTime(a.StartHour)+" - "+getDisplayTime(a.EndHour)+"
",itemHtml+="
",itemHtml+='',itemHtml+="
",index++,itemHtml}).join("");var accessScheduleList=page.querySelector(".accessScheduleList");accessScheduleList.innerHTML=html,$(".btnDelete",accessScheduleList).on("click",function(){deleteAccessSchedule(page,schedules,parseInt(this.getAttribute("data-index")))})}function onSaveComplete(page){loading.hide(),require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))})}function saveUser(user,page){user.Policy.MaxParentalRating=$("#selectMaxParentalRating",page).val()||null,user.Policy.BlockUnratedItems=$(".chkUnratedItem",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-itemtype")}),user.Policy.AccessSchedules=getSchedulesFromPage(page),user.Policy.BlockedTags=getBlockedTagsFromPage(page),ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){onSaveComplete(page)})}function getDisplayTime(hours){var minutes=0,pct=hours%1;return pct&&(minutes=parseInt(60*pct)),datetime.getDisplayTime(new Date(2e3,1,1,hours,minutes,0,0))}function showSchedulePopup(page,schedule,index){schedule=schedule||{},require(["components/accessschedule/accessschedule"],function(accessschedule){accessschedule.show({schedule:schedule}).then(function(updatedSchedule){var schedules=getSchedulesFromPage(page);index==-1&&(index=schedules.length),schedules[index]=updatedSchedule,renderAccessSchedule(page,schedules)})})}function getSchedulesFromPage(page){return $(".liSchedule",page).map(function(){return{DayOfWeek:this.getAttribute("data-day"),StartHour:this.getAttribute("data-start"),EndHour:this.getAttribute("data-end")}}).get()}function getBlockedTagsFromPage(page){return $(".blockedTag",page).map(function(){return this.getAttribute("data-tag")}).get()}function showBlockedTagPopup(page){require(["prompt"],function(prompt){prompt({label:Globalize.translate("LabelTag")}).then(function(value){var tags=getBlockedTagsFromPage(page);tags.indexOf(value)==-1&&(tags.push(value),loadBlockedTags(page,tags))})})}window.UserParentalControlPage={onSubmit:function(){var page=$(this).parents(".page");loading.show();var userId=getParameterByName("userId");return ApiClient.getUser(userId).then(function(result){saveUser(result,page)}),!1}},$(document).on("pageinit","#userParentalControlPage",function(){var page=this;$(".btnAddSchedule",page).on("click",function(){showSchedulePopup(page,{},-1)}),$(".btnAddBlockedTag",page).on("click",function(){showBlockedTagPopup(page)}),$(".userParentalControlForm").off("submit",UserParentalControlPage.onSubmit).on("submit",UserParentalControlPage.onSubmit)}).on("pageshow","#userParentalControlPage",function(){var page=this;loading.show();var userId=getParameterByName("userId"),promise1=ApiClient.getUser(userId),promise2=ApiClient.getParentalRatings();Promise.all([promise1,promise2]).then(function(responses){loadUser(page,responses[0],responses[1])})})}); \ No newline at end of file diff --git a/dashboard-ui/shared.html b/dashboard-ui/shared.html index 62ecb24e87..00bab911e6 100644 --- a/dashboard-ui/shared.html +++ b/dashboard-ui/shared.html @@ -79,7 +79,6 @@ ${HeaderAwardsAndReviews}
-