1 line
No EOL
21 KiB
JavaScript
1 line
No EOL
21 KiB
JavaScript
import globalize from"./../common/globalize.js";import connectionManager from"./../emby-apiclient/connectionmanager.js";import events from"./../emby-apiclient/events.js";import playbackManager from"./../common/playback/playbackmanager.js";import appSettings from"./../common/appsettings.js";import userSettings from"./../common/usersettings/usersettings.js";function showAlert(options){return Emby.importModule("./modules/common/dialogs/alert.js").then(function(alert){return alert(options)})}function getCastSenderApiLoader(){return new Promise(function(resolve,reject){var fileref=document.createElement("script");fileref.setAttribute("type","text/javascript"),fileref.onload=resolve,fileref.setAttribute("src","https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"),document.querySelector("head").appendChild(fileref)})}let currentResolve,currentReject,PlayerName="Chromecast";function sendConnectionResult(isOk){var resolve=currentResolve,reject=currentReject;currentResolve=null,currentReject=null,isOk?resolve&&resolve():reject?reject():playbackManager.removeActivePlayer(PlayerName)}let 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.currentVolume=1,this.initializeCastPlayer()};function mapItemForLoadMedia(i){return{Id:i.Id,ServerId:i.ServerId,Name:i.Name,Type:i.Type,MediaType:i.MediaType,IsFolder:i.IsFolder,ChannelId:i.ChannelId}}function normalizeImages(state){state&&state.NowPlayingItem&&((state=state.NowPlayingItem).ImageTags&&state.ImageTags.Primary||state.PrimaryImageTag&&(state.ImageTags=state.ImageTags||{},state.ImageTags.Primary=state.PrimaryImageTag),state.BackdropImageTag&&state.BackdropItemId===state.Id&&(state.BackdropImageTags=[state.BackdropImageTag]),state.BackdropImageTag)&&state.BackdropItemId!==state.Id&&(state.ParentBackdropImageTags=[state.BackdropImageTag],state.ParentBackdropItemId=state.BackdropItemId)}function getItemsForPlayback(apiClient,query){var 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))}function bindEventForRelay(instance,eventName){events.on(instance._castPlayer,eventName,function(e,data){"playlistitemremove"!==eventName&&(data=instance.getPlayerStateInternal(data)),events.trigger(instance,eventName,[data])})}function initializeChromecast(){let instance=this;instance._castPlayer=new CastPlayer,document.dispatchEvent(new CustomEvent("chromecastloaded",{detail:{player:instance}})),events.on(instance._castPlayer,"connect",function(e){currentResolve?sendConnectionResult(!0):playbackManager.setActivePlayer(PlayerName,instance.getCurrentTargetInfo()),console.log("cc: connect"),instance.lastPlayerData=null}),events.on(instance._castPlayer,"playbackstart",function(e,data){console.log("cc: playbackstart"),instance._castPlayer.initializeCastPlayer();data=instance.getPlayerStateInternal(data);events.trigger(instance,"playbackstart",[data])}),events.on(instance._castPlayer,"playbackstop",function(e,data){console.log("cc: playbackstop");data=instance.getPlayerStateInternal(data);events.trigger(instance,"playbackstop",[data]),instance.resetLastPlayerData()}),events.on(instance._castPlayer,"playbackprogress",function(e,data){data=instance.getPlayerStateInternal(data);events.trigger(instance,"timeupdate",[data])}),bindEventForRelay(instance,"timeupdate"),bindEventForRelay(instance,"pause"),bindEventForRelay(instance,"unpause"),bindEventForRelay(instance,"volumechange"),bindEventForRelay(instance,"repeatmodechange"),bindEventForRelay(instance,"shufflechange"),bindEventForRelay(instance,"subtitleoffsetchange"),bindEventForRelay(instance,"playbackratechange"),bindEventForRelay(instance,"audiotrackchange"),bindEventForRelay(instance,"subtitletrackchange"),bindEventForRelay(instance,"qualitychange"),bindEventForRelay(instance,"playlistitemmove"),bindEventForRelay(instance,"playlistitemremove"),bindEventForRelay(instance,"playlistitemadd")}function ChromecastPlayer(){this.name=PlayerName,this.type="mediaplayer",this.id="chromecast",this.isLocalPlayer=!1,this.resetLastPlayerData(),getCastSenderApiLoader().then(initializeChromecast.bind(this))}CastPlayer.prototype.initializeCastPlayer=function(){var sessionRequest,chrome=window.chrome;chrome&&(chrome.cast&&chrome.cast.isAvailable?(sessionRequest=new chrome.cast.SessionRequest(applicationID),sessionRequest=new chrome.cast.ApiConfig(sessionRequest,this.sessionListener.bind(this),this.receiverListener.bind(this),"origin_scoped"),console.log("chromecast.initialize"),chrome.cast.initialize(sessionRequest,this.onInitSuccess.bind(this),this.errorHandler)):setTimeout(this.initializeCastPlayer.bind(this),1e3))},CastPlayer.prototype.onInitSuccess=function(){this.isInitialized=!0,console.log("chromecast init success")},CastPlayer.prototype.onError=function(e){console.log("chromecast error. code: "+(e.code||"")+", details: "+(e.details||""))},CastPlayer.prototype.sessionListener=function(e){this.session=e,this.session&&(this.session.media[0]&&this.onMediaDiscovered("activeSession",this.session.media[0]),this.onSessionConnected(e))},CastPlayer.prototype.messageListener=function(namespace,message){if("playbackerror"===(message="string"==typeof message?JSON.parse(message):message).type){let errorCode=message.data;setTimeout(function(){showAlert(globalize.translate("MessagePlaybackError"+errorCode),globalize.translate("HeaderPlaybackError"))},300)}else"connectionerror"===message.type?setTimeout(function(){showAlert(globalize.translate("MessageChromecastConnectionError"),globalize.translate("Error"))},300):message.type&&events.trigger(this,message.type,[message.data])},CastPlayer.prototype.receiverListener=function(e){this.hasReceivers="available"===e},CastPlayer.prototype.sessionUpdateListener=function(isAlive){isAlive||(this.session=null,this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,this.currentMediaSession=null,sendConnectionResult(!1))},CastPlayer.prototype.launchApp=function(){chrome.cast.requestSession(this.onRequestSessionSuccess.bind(this),this.onLaunchError.bind(this))},CastPlayer.prototype.onRequestSessionSuccess=function(e){this.onSessionConnected(e)},CastPlayer.prototype.onSessionConnected=function(session){this.session=session,this.currentVolume=this.session.receiver.volume.level,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){this.currentMediaSession=e,this.currentMediaSession.addUpdateListener(this.mediaStatusUpdateHandler)},CastPlayer.prototype.onLaunchError=function(){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){this.deviceState=DEVICE_STATE.IDLE,this.castPlayerState=PLAYER_STATE.IDLE,this.currentMediaSession=null},CastPlayer.prototype.loadMedia=function(options,command){return this.session?(options.items=options.items.map(mapItemForLoadMedia),this.sendMessage({options:options,command:command})):Promise.reject()},CastPlayer.prototype.sendMessage=function(message){let player=this,receiverName=null;var session=player.session;session&&session.receiver&&session.receiver.friendlyName&&(receiverName=session.receiver.friendlyName);let apiClient;apiClient=message.options&&message.options.ServerId?connectionManager.getApiClient(message.options.ServerId):message.options&&message.options.items&&message.options.items.length?connectionManager.getApiClient(message.options.items[0]):connectionManager.currentApiClient(),message=Object.assign(message,{userId:apiClient.getCurrentUserId(),deviceId:apiClient.deviceId(),accessToken:apiClient.accessToken(),serverAddress:apiClient.serverAddress(),serverId:apiClient.serverId(),serverVersion:apiClient.serverVersion(),receiverName:receiverName});session=appSettings.maxChromecastBitrate();return session&&(message.maxBitrate=session),message.options&&message.options.items&&(message.subtitleAppearance=userSettings.getSubtitleAppearanceSettings()),Emby.importModule("./modules/chromecast/chromecasthelpers.js").then(function(chromecastHelper){return chromecastHelper.getServerAddress(apiClient).then(function(serverAddress){return message.serverAddress=serverAddress,player.sendMessageInternal(message)})})},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(){},CastPlayer.prototype.onMediaDiscovered=function(how,mediaSession){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){!1===e&&(this.castPlayerState=PLAYER_STATE.IDLE)},CastPlayer.prototype.setReceiverVolume=function(mute,vol){this.currentMediaSession,mute?this.session.setReceiverMuted(!0,this.mediaCommandSuccessCallback.bind(this),this.errorHandler):(this.currentVolume=mute=vol,this.session.setReceiverVolumeLevel(mute,this.mediaCommandSuccessCallback.bind(this),this.errorHandler))},CastPlayer.prototype.mute=function(){this.setReceiverVolume(!0)},CastPlayer.prototype.unMute=function(){var newVolume=this.currentVolume||1;this.setReceiverVolume(!1,newVolume)},CastPlayer.prototype.mediaCommandSuccessCallback=function(info,e){},ChromecastPlayer.prototype.tryPair=function(target){let castPlayer=this._castPlayer;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())},ChromecastPlayer.prototype.resetLastPlayerData=function(){var newData={},lastPlayerData=this.lastPlayerData;lastPlayerData&&lastPlayerData.NowPlayingQueue&&(newData.NowPlayingQueue=lastPlayerData.NowPlayingQueue),this.lastPlayerData=newData},ChromecastPlayer.prototype.getTargets=function(){var targets=[];return this._castPlayer&&this._castPlayer.hasReceivers&&targets.push(this.getCurrentTargetInfo()),Promise.resolve(targets)},ChromecastPlayer.prototype.getCurrentTargetInfo=function(){let appName=null;var castPlayer=this._castPlayer;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","RefreshMediaSource","DisplayContent","SetRepeatMode","SetShuffle","SetSubtitleOffset","SetPlaybackRate","EndSession","PlayMediaSource","PlayTrailers"]}},ChromecastPlayer.prototype.getPlayerStateInternal=function(data){var lastPlayerData=this.lastPlayerData;let triggerStateChange=!1;return data&&(!data.NowPlayingQueue&&lastPlayerData&&(data.NowPlayingQueue=lastPlayerData.NowPlayingQueue),lastPlayerData||(triggerStateChange=!0)),(data=data||lastPlayerData)&&(data.VolumeLevel=100*this._castPlayer.currentVolume),normalizeImages(this.lastPlayerData=data),triggerStateChange&&events.trigger(this,"statechange",[data]),data},ChromecastPlayer.prototype.playWithCommand=function(options,command){if(options.items)return this._castPlayer.loadMedia(options,command);{var apiClient=connectionManager.getApiClient(options.serverId);let instance=this;return apiClient.getItem(apiClient.getCurrentUserId(),options.ids[0]).then(function(item){return options.items=[item],instance.playWithCommand(options,command)})}},ChromecastPlayer.prototype.seek=function(position){return position=parseInt(position),this._castPlayer.sendMessage({options:{position:position/=1e7},command:"Seek"})},ChromecastPlayer.prototype.seekRelative=function(offsetTicks){return offsetTicks=parseInt(offsetTicks),this._castPlayer.sendMessage({options:{offset:offsetTicks},command:"SeekRelative"})},ChromecastPlayer.prototype.setAudioStreamIndex=function(index){return this._castPlayer.sendMessage({options:{index:index},command:"SetAudioStreamIndex"})},ChromecastPlayer.prototype.setSubtitleStreamIndex=function(index,refreshMediaSource){return this._castPlayer.sendMessage({options:{index:index,RefreshMediaSource:refreshMediaSource},command:"SetSubtitleStreamIndex"})},ChromecastPlayer.prototype.setMaxStreamingBitrate=function(options){return this._castPlayer.sendMessage({options:options,command:"SetMaxStreamingBitrate"})},ChromecastPlayer.prototype.isFullscreen=function(){return((this.lastPlayerData||{}).PlayState||{}).IsFullscreen},ChromecastPlayer.prototype.nextTrack=function(){return this._castPlayer.sendMessage({options:{},command:"NextTrack"})},ChromecastPlayer.prototype.previousTrack=function(){return this._castPlayer.sendMessage({options:{},command:"PreviousTrack"})},ChromecastPlayer.prototype.volumeDown=function(){var volume=this._castPlayer.currentVolume-.02;this.setVolume(100*volume)},ChromecastPlayer.prototype.endSession=function(){let instance=this;this.stop().then(function(){setTimeout(function(){instance._castPlayer.stopApp()},1e3)})},ChromecastPlayer.prototype.volumeUp=function(){var volume=this._castPlayer.currentVolume+.02;this.setVolume(100*volume)},ChromecastPlayer.prototype.setVolume=function(vol){vol=Math.min(vol,100),vol=Math.max(vol,0),this._castPlayer.setReceiverVolume(!1,vol/100)},ChromecastPlayer.prototype.unpause=function(){return this._castPlayer.sendMessage({options:{},command:"Unpause"})},ChromecastPlayer.prototype.playPause=function(){return this._castPlayer.sendMessage({options:{},command:"PlayPause"})},ChromecastPlayer.prototype.pause=function(){return this._castPlayer.sendMessage({options:{},command:"Pause"})},ChromecastPlayer.prototype.stop=function(){return this._castPlayer.sendMessage({options:{},command:"Stop"})},ChromecastPlayer.prototype.displayContent=function(options){return this._castPlayer.sendMessage({options:options,command:"DisplayContent"})},ChromecastPlayer.prototype.setMute=function(isMuted){isMuted?this._castPlayer.mute():this._castPlayer.unMute()},ChromecastPlayer.prototype.getRepeatMode=function(){return((this.lastPlayerData||{}).PlayState||{}).RepeatMode},ChromecastPlayer.prototype.getShuffle=function(){return((this.lastPlayerData||{}).PlayState||{}).Shuffle},ChromecastPlayer.prototype.getSubtitleOffset=function(){return((this.lastPlayerData||{}).PlayState||{}).SubtitleOffset},ChromecastPlayer.prototype.playTrailers=function(item){return this._castPlayer.sendMessage({options:{ItemId:item.Id,ServerId:item.ServerId},command:"PlayTrailers"})},ChromecastPlayer.prototype.setRepeatMode=function(mode){return this._castPlayer.sendMessage({options:{RepeatMode:mode},command:"SetRepeatMode"})},ChromecastPlayer.prototype.setShuffle=function(mode){return this._castPlayer.sendMessage({options:{Shuffle:mode},command:"SetShuffle"})},ChromecastPlayer.prototype.setSubtitleOffset=function(value){return this._castPlayer.sendMessage({options:{SubtitleOffset:value},command:"SetSubtitleOffset"})},ChromecastPlayer.prototype.incrementSubtitleOffset=function(value){return this._castPlayer.sendMessage({options:{Increment:value},command:"IncrementSubtitleOffset"})},ChromecastPlayer.prototype.getPlaybackRate=function(){return((this.lastPlayerData||{}).PlayState||{}).PlaybackRate},ChromecastPlayer.prototype.setPlaybackRate=function(value){return this._castPlayer.sendMessage({options:{PlaybackRate:value},command:"SetPlaybackRate"})},ChromecastPlayer.prototype.toggleMute=function(){return this._castPlayer.sendMessage({options:{},command:"ToggleMute"})},ChromecastPlayer.prototype.getAudioStreamIndex=function(){return((this.lastPlayerData||{}).PlayState||{}).AudioStreamIndex},ChromecastPlayer.prototype.getSubtitleStreamIndex=function(){return((this.lastPlayerData||{}).PlayState||{}).SubtitleStreamIndex},ChromecastPlayer.prototype.getMaxStreamingBitrate=function(){return((this.lastPlayerData||{}).PlayState||{}).MaxStreamingBitrate},ChromecastPlayer.prototype.getVolume=function(){var state;return null==(state=(this.lastPlayerData||{}).PlayState||{}).VolumeLevel?100:state.VolumeLevel},ChromecastPlayer.prototype.isPlaying=function(mediaType){var nowPlayingItem=this.lastPlayerData?.NowPlayingItem;return nowPlayingItem&&(!mediaType||nowPlayingItem.MediaType===mediaType)},ChromecastPlayer.prototype.currentMediaSource=function(){return(this.lastPlayerData||{}).MediaSource},ChromecastPlayer.prototype.currentTime=function(val){return null!=val?this.seek(val):((this.lastPlayerData||{}).PlayState||{}).PositionTicks},ChromecastPlayer.prototype.playbackStartTime=function(){return((this.lastPlayerData||{}).PlayState||{}).PlaybackStartTimeTicks},ChromecastPlayer.prototype.duration=function(){return((this.lastPlayerData||{}).MediaSource||{}).RunTimeTicks},ChromecastPlayer.prototype.getBufferedRanges=function(){return((this.lastPlayerData||{}).PlayState||{}).BufferedRanges||[]},ChromecastPlayer.prototype.getSeekableRanges=function(){return((this.lastPlayerData||{}).PlayState||{}).SeekableRanges||[]},ChromecastPlayer.prototype.paused=function(){return((this.lastPlayerData||{}).PlayState||{}).IsPaused},ChromecastPlayer.prototype.isMuted=function(){return((this.lastPlayerData||{}).PlayState||{}).IsMuted},ChromecastPlayer.prototype.shuffle=function(item){var apiClient=connectionManager.getApiClient(item),userId=apiClient.getCurrentUserId();let instance=this;return apiClient.getItem(userId,item.Id).then(function(item){return instance.playWithCommand({items:[item]},"Shuffle")})},ChromecastPlayer.prototype.instantMix=function(item){var apiClient=connectionManager.getApiClient(item),userId=apiClient.getCurrentUserId();let instance=this;return apiClient.getItem(userId,item.Id).then(function(item){return instance.playWithCommand({items:[item]},"InstantMix")})},ChromecastPlayer.prototype.canPlayMediaType=function(mediaType){switch(mediaType){case"Audio":case"Video":return!0;default:return!1}},ChromecastPlayer.prototype.queue=function(options){return this.playWithCommand(options,"PlayLast")},ChromecastPlayer.prototype.queueNext=function(options){return this.playWithCommand(options,"PlayNext")},ChromecastPlayer.prototype.play=function(options){if(options.shuffle){if(options.items?.length)return this.shuffle(options.items[0]);if(options.ids?.length)return this.shuffle({Id:options.ids[0]})}if(options.items)return this.playWithCommand(options,"PlayNow");{if(!options.serverId)throw new Error("serverId required!");let instance=this;return getItemsForPlayback(connectionManager.getApiClient(options.serverId),{Ids:options.ids.join(",")}).then(function(result){return options.items=result.Items,instance.playWithCommand(options,"PlayNow")})}},ChromecastPlayer.prototype.toggleFullscreen=function(){},ChromecastPlayer.prototype.beginPlayerUpdates=function(){},ChromecastPlayer.prototype.endPlayerUpdates=function(){},ChromecastPlayer.prototype.getPlaylist=function(){var items=(this.lastPlayerData||{}).NowPlayingQueue||[];return Promise.resolve({Items:items,TotalRecordCount:items.length})},ChromecastPlayer.prototype.getCurrentPlaylistItemId=function(){return(this.lastPlayerData||{}).PlaylistItemId},ChromecastPlayer.prototype.getCurrentPlaylistIndex=function(){return(this.lastPlayerData||{}).PlaylistIndex},ChromecastPlayer.prototype.getCurrentPlaylistLength=function(){return(this.lastPlayerData||{}).PlaylistLength},ChromecastPlayer.prototype.setCurrentPlaylistItem=function(playlistItemId){return this._castPlayer.sendMessage({options:{PlaylistItemId:playlistItemId},command:"SetCurrentPlaylistItem"})},ChromecastPlayer.prototype.movePlaylistItem=function(playlistItemId,newIndex){return this._castPlayer.sendMessage({options:{PlaylistItemId:playlistItemId,NewIndex:newIndex},command:"MovePlaylistItem"})},ChromecastPlayer.prototype.removeFromPlaylist=function(playlistItemIds){return this._castPlayer.sendMessage({options:{PlaylistItemIds:playlistItemIds.join(",")},command:"RemoveFromPlaylist"})},ChromecastPlayer.prototype.getPlayerState=function(){return this.getPlayerStateInternal()||{}};export default ChromecastPlayer; |