PlexKodiConnect/resources/lib/player.py

579 lines
22 KiB
Python
Raw Normal View History

2015-12-25 07:07:00 +11:00
# -*- coding: utf-8 -*-
#################################################################################################
import json
import xbmc
import xbmcgui
import utils
import clientinfo
import downloadutils
2016-01-12 23:57:26 +11:00
from urllib import urlencode
2015-12-25 07:07:00 +11:00
#################################################################################################
2016-01-27 03:20:13 +11:00
@utils.logging
2015-12-25 07:07:00 +11:00
class Player(xbmc.Player):
# Borg - multiple instances, shared state
_shared_state = {}
played_info = {}
playStats = {}
currentFile = None
def __init__(self):
self.__dict__ = self._shared_state
self.clientInfo = clientinfo.ClientInfo()
2016-02-17 19:13:37 +11:00
self.doUtils = downloadutils.DownloadUtils().downloadUrl
2015-12-25 07:07:00 +11:00
self.xbmcplayer = xbmc.Player()
self.logMsg("Starting playback monitor.", 2)
2016-02-07 22:38:50 +11:00
# Should we start notification or is this done by Plex Companion?
self.doNotify = False if (utils.settings('plexCompanion') == 'true') \
else True
if self.doNotify:
self.logMsg("PMS notifications not done by Plex Companion", 2)
else:
self.logMsg("PMS notifications done by Plex Companion", 2)
2015-12-25 07:07:00 +11:00
def GetPlayStats(self):
return self.playStats
2016-02-17 19:13:37 +11:00
def onPlayBackStarted(self):
log = self.logMsg
window = utils.window
2015-12-25 07:07:00 +11:00
# Will be called when xbmc starts playing a file
xbmcplayer = self.xbmcplayer
self.stopAll()
# Get current file
try:
currentFile = xbmcplayer.getPlayingFile()
xbmc.sleep(300)
except:
currentFile = ""
count = 0
while not currentFile:
xbmc.sleep(100)
try:
currentFile = xbmcplayer.getPlayingFile()
except: pass
if count == 5: # try 5 times
2016-02-17 19:13:37 +11:00
log("Cancelling playback report...", 1)
2015-12-25 07:07:00 +11:00
break
else: count += 1
if currentFile:
self.currentFile = currentFile
2016-02-07 22:38:50 +11:00
# Save currentFile for cleanup later
2016-02-20 06:03:06 +11:00
window('plex_lastPlayedFiled', value=currentFile)
2015-12-25 07:07:00 +11:00
# We may need to wait for info to be set in kodi monitor
2016-02-17 19:13:37 +11:00
itemId = window("emby_%s.itemid" % currentFile)
2015-12-25 07:07:00 +11:00
tryCount = 0
while not itemId:
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
xbmc.sleep(200)
2016-02-17 19:13:37 +11:00
itemId = window("emby_%s.itemid" % currentFile)
2015-12-25 07:07:00 +11:00
if tryCount == 20: # try 20 times or about 10 seconds
2016-02-17 19:13:37 +11:00
log("Could not find itemId, cancelling playback report...", 1)
2015-12-25 07:07:00 +11:00
break
else: tryCount += 1
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
else:
window('Plex_currently_playing_itemid', value=itemId)
2016-02-17 19:13:37 +11:00
log("ONPLAYBACK_STARTED: %s itemid: %s" % (currentFile, itemId), 0)
2015-12-25 07:07:00 +11:00
# Only proceed if an itemId was found.
embyitem = "emby_%s" % currentFile
2016-02-20 06:03:06 +11:00
runtime = window("%s.runtime" % embyitem)
refresh_id = window("%s.refreshid" % embyitem)
playMethod = window("%s.playmethod" % embyitem)
itemType = window("%s.type" % embyitem)
window('emby_skipWatched%s' % itemId, value="true")
2016-02-17 19:13:37 +11:00
log("Playing itemtype is: %s" % itemType, 1)
2016-02-20 06:03:06 +11:00
# Suspend library sync thread while movie is playing
if itemType in ('movie', 'episode'):
log("Suspending library sync while playing", 1)
window('suspend_LibraryThread', value='true')
2016-02-04 12:06:12 +11:00
2016-02-20 06:03:06 +11:00
customseek = window('emby_customPlaylist.seektime')
if (window('emby_customPlaylist') == "true" and customseek):
2016-02-04 12:06:12 +11:00
# Start at, when using custom playlist (play to Kodi from webclient)
2016-02-17 19:13:37 +11:00
log("Seeking to: %s" % customseek, 1)
xbmcplayer.seekTime(int(customseek))
2016-02-17 19:13:37 +11:00
window('emby_customPlaylist.seektime', clear=True)
2016-02-04 12:06:12 +11:00
2015-12-25 07:07:00 +11:00
seekTime = xbmcplayer.getTime()
# Get playback volume
volume_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Application.GetProperties",
"params": {
"properties": ["volume", "muted"]
}
}
result = xbmc.executeJSONRPC(json.dumps(volume_query))
result = json.loads(result)
result = result.get('result')
volume = result.get('volume')
muted = result.get('muted')
# Postdata structure to send to Emby server
2016-01-27 22:18:54 +11:00
url = "{server}/:/timeline?"
2015-12-25 07:07:00 +11:00
postdata = {
'QueueableMediaTypes': "Video",
'CanSeek': True,
'ItemId': itemId,
'MediaSourceId': itemId,
'PlayMethod': playMethod,
'VolumeLevel': volume,
'PositionTicks': int(seekTime * 10000000),
'IsMuted': muted
}
# Get the current audio track and subtitles
if playMethod == "Transcode":
# property set in PlayUtils.py
2016-02-17 19:13:37 +11:00
postdata['AudioStreamIndex'] = window("%sAudioStreamIndex" % currentFile)
postdata['SubtitleStreamIndex'] = window("%sSubtitleStreamIndex" % currentFile)
2015-12-25 07:07:00 +11:00
else:
# Get the current kodi audio and subtitles and convert to Emby equivalent
tracks_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Player.GetProperties",
"params": {
"playerid": 1,
"properties": ["currentsubtitle","currentaudiostream","subtitleenabled"]
}
}
result = xbmc.executeJSONRPC(json.dumps(tracks_query))
result = json.loads(result)
result = result.get('result')
try: # Audio tracks
indexAudio = result['currentaudiostream']['index']
except (KeyError, TypeError):
indexAudio = 0
try: # Subtitles tracks
indexSubs = result['currentsubtitle']['index']
except (KeyError, TypeError):
indexSubs = 0
try: # If subtitles are enabled
subsEnabled = result['subtitleenabled']
except (KeyError, TypeError):
subsEnabled = ""
# Postdata for the audio
postdata['AudioStreamIndex'] = indexAudio + 1
# Postdata for the subtitles
if subsEnabled and len(xbmc.Player().getAvailableSubtitleStreams()) > 0:
# Number of audiotracks to help get Emby Index
audioTracks = len(xbmc.Player().getAvailableAudioStreams())
2016-02-17 19:13:37 +11:00
mapping = window("%s.indexMapping" % embyitem)
2015-12-25 07:07:00 +11:00
if mapping: # Set in playbackutils.py
2016-02-17 19:13:37 +11:00
log("Mapping for external subtitles index: %s" % mapping, 2)
2015-12-25 07:07:00 +11:00
externalIndex = json.loads(mapping)
if externalIndex.get(str(indexSubs)):
# If the current subtitle is in the mapping
postdata['SubtitleStreamIndex'] = externalIndex[str(indexSubs)]
else:
# Internal subtitle currently selected
subindex = indexSubs - len(externalIndex) + audioTracks + 1
postdata['SubtitleStreamIndex'] = subindex
else: # Direct paths enabled scenario or no external subtitles set
postdata['SubtitleStreamIndex'] = indexSubs + audioTracks + 1
else:
postdata['SubtitleStreamIndex'] = ""
# Post playback to server
# log("Sending POST play started: %s." % postdata, 2)
# self.doUtils(url, postBody=postdata, type="POST")
2015-12-25 07:07:00 +11:00
# Ensure we do have a runtime
try:
runtime = int(runtime)
except ValueError:
runtime = xbmcplayer.getTotalTime()
2016-02-17 19:13:37 +11:00
log("Runtime is missing, Kodi runtime: %s" % runtime, 1)
2015-12-25 07:07:00 +11:00
2016-02-07 22:38:50 +11:00
playQueueVersion = utils.window(
'playQueueVersion')
playQueueID = utils.window(
'playQueueID')
playQueueItemID = utils.window(
'plex_%s.playQueueItemID' % currentFile)
2015-12-25 07:07:00 +11:00
# Save data map for updates and position calls
data = {
2016-02-07 22:38:50 +11:00
'playQueueVersion': playQueueVersion,
'playQueueID': playQueueID,
'playQueueItemID': playQueueItemID,
'runtime': runtime * 1000,
2015-12-25 07:07:00 +11:00
'item_id': itemId,
'refresh_id': refresh_id,
'currentfile': currentFile,
'AudioStreamIndex': postdata['AudioStreamIndex'],
'SubtitleStreamIndex': postdata['SubtitleStreamIndex'],
'playmethod': playMethod,
'Type': itemType,
'currentPosition': int(seekTime)
}
self.played_info[currentFile] = data
2016-02-17 19:13:37 +11:00
log("ADDING_FILE: %s" % self.played_info, 1)
2015-12-25 07:07:00 +11:00
# log some playback stats
'''if(itemType != None):
if(self.playStats.get(itemType) != None):
count = self.playStats.get(itemType) + 1
self.playStats[itemType] = count
else:
self.playStats[itemType] = 1
if(playMethod != None):
if(self.playStats.get(playMethod) != None):
count = self.playStats.get(playMethod) + 1
self.playStats[playMethod] = count
else:
self.playStats[playMethod] = 1'''
def reportPlayback(self):
2016-02-07 22:38:50 +11:00
# Don't use if Plex Companion is enabled
if not self.doNotify:
return
2016-02-20 06:03:06 +11:00
log = self.logMsg
2016-02-17 19:13:37 +11:00
log("reportPlayback Called", 2)
2015-12-25 07:07:00 +11:00
# Get current file
currentFile = self.currentFile
data = self.played_info.get(currentFile)
# only report playback if emby has initiated the playback (item_id has value)
if data:
# Get playback information
itemId = data['item_id']
audioindex = data['AudioStreamIndex']
subtitleindex = data['SubtitleStreamIndex']
playTime = data['currentPosition']
playMethod = data['playmethod']
paused = data.get('paused', False)
2016-01-12 23:57:26 +11:00
duration = data.get('runtime', '')
2015-12-25 07:07:00 +11:00
# Get playback volume
volume_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Application.GetProperties",
"params": {
"properties": ["volume", "muted"]
}
2016-02-17 19:13:37 +11:00
}
2015-12-25 07:07:00 +11:00
result = xbmc.executeJSONRPC(json.dumps(volume_query))
result = json.loads(result)
result = result.get('result')
volume = result.get('volume')
muted = result.get('muted')
# Postdata for the websocketclient report
2016-01-12 23:57:26 +11:00
# postdata = {
# 'QueueableMediaTypes': "Video",
# 'CanSeek': True,
# 'ItemId': itemId,
# 'MediaSourceId': itemId,
# 'PlayMethod': playMethod,
# 'PositionTicks': int(playTime * 10000000),
# 'IsPaused': paused,
# 'VolumeLevel': volume,
# 'IsMuted': muted
# }
if paused == 'stopped':
state = 'stopped'
2016-01-13 01:53:06 +11:00
elif paused is True:
2016-01-12 23:57:26 +11:00
state = 'paused'
else:
state = 'playing'
2015-12-25 07:07:00 +11:00
postdata = {
2016-01-12 23:57:26 +11:00
'ratingKey': itemId,
'state': state, # 'stopped', 'paused', 'buffering', 'playing'
'time': int(playTime) * 1000,
'duration': int(duration) * 1000
2015-12-25 07:07:00 +11:00
}
2016-02-07 22:38:50 +11:00
# For PMS playQueues/playlists only
if data.get('playQueueID'):
postdata['containerKey'] = '/playQueues/' + data.get('playQueueID')
postdata['playQueueVersion'] = data.get('playQueueVersion')
postdata['playQueueItemID'] = data.get('playQueueItemID')
2015-12-25 07:07:00 +11:00
if playMethod == "Transcode":
# Track can't be changed, keep reporting the same index
postdata['AudioStreamIndex'] = audioindex
postdata['AudioStreamIndex'] = subtitleindex
else:
# Get current audio and subtitles track
tracks_query = {
"jsonrpc": "2.0",
"id": 1,
"method": "Player.GetProperties",
"params": {
"playerid": 1,
"properties": ["currentsubtitle","currentaudiostream","subtitleenabled"]
}
}
result = xbmc.executeJSONRPC(json.dumps(tracks_query))
result = json.loads(result)
result = result.get('result')
try: # Audio tracks
indexAudio = result['currentaudiostream']['index']
except (KeyError, TypeError):
indexAudio = 0
try: # Subtitles tracks
indexSubs = result['currentsubtitle']['index']
except (KeyError, TypeError):
indexSubs = 0
try: # If subtitles are enabled
subsEnabled = result['subtitleenabled']
except (KeyError, TypeError):
subsEnabled = ""
# Postdata for the audio
data['AudioStreamIndex'], postdata['AudioStreamIndex'] = [indexAudio + 1] * 2
# Postdata for the subtitles
if subsEnabled and len(xbmc.Player().getAvailableSubtitleStreams()) > 0:
# Number of audiotracks to help get Emby Index
audioTracks = len(xbmc.Player().getAvailableAudioStreams())
mapping = utils.window("emby_%s.indexMapping" % currentFile)
if mapping: # Set in PlaybackUtils.py
2016-02-17 19:13:37 +11:00
log("Mapping for external subtitles index: %s" % mapping, 2)
2015-12-25 07:07:00 +11:00
externalIndex = json.loads(mapping)
if externalIndex.get(str(indexSubs)):
# If the current subtitle is in the mapping
subindex = [externalIndex[str(indexSubs)]] * 2
data['SubtitleStreamIndex'], postdata['SubtitleStreamIndex'] = subindex
else:
# Internal subtitle currently selected
subindex = [indexSubs - len(externalIndex) + audioTracks + 1] * 2
data['SubtitleStreamIndex'], postdata['SubtitleStreamIndex'] = subindex
else: # Direct paths enabled scenario or no external subtitles set
subindex = [indexSubs + audioTracks + 1] * 2
data['SubtitleStreamIndex'], postdata['SubtitleStreamIndex'] = subindex
else:
data['SubtitleStreamIndex'], postdata['SubtitleStreamIndex'] = [""] * 2
# Report progress via websocketclient
2016-01-12 23:57:26 +11:00
# postdata = json.dumps(postdata)
# self.ws.sendProgressUpdate(postdata)
self.doUtils(
2016-01-27 22:18:54 +11:00
"{server}/:/timeline?" + urlencode(postdata), type="GET")
2015-12-25 07:07:00 +11:00
2016-02-21 10:21:39 +11:00
def onPlayBackPaused(self):
2015-12-25 07:07:00 +11:00
currentFile = self.currentFile
self.logMsg("PLAYBACK_PAUSED: %s" % currentFile, 2)
if self.played_info.get(currentFile):
self.played_info[currentFile]['paused'] = True
self.reportPlayback()
2016-02-21 10:21:39 +11:00
def onPlayBackResumed(self):
2015-12-25 07:07:00 +11:00
currentFile = self.currentFile
self.logMsg("PLAYBACK_RESUMED: %s" % currentFile, 2)
if self.played_info.get(currentFile):
self.played_info[currentFile]['paused'] = False
self.reportPlayback()
2016-02-21 10:21:39 +11:00
def onPlayBackSeek(self, time, seekOffset):
2015-12-25 07:07:00 +11:00
# Make position when seeking a bit more accurate
currentFile = self.currentFile
self.logMsg("PLAYBACK_SEEK: %s" % currentFile, 2)
if self.played_info.get(currentFile):
position = self.xbmcplayer.getTime()
self.played_info[currentFile]['currentPosition'] = position
self.reportPlayback()
2016-02-21 10:21:39 +11:00
def onPlayBackStopped(self):
2016-02-17 19:13:37 +11:00
log = self.logMsg
window = utils.window
2015-12-25 07:07:00 +11:00
# Will be called when user stops xbmc playing a file
log("ONPLAYBACK_STOPPED", 2)
2016-02-17 19:13:37 +11:00
window('emby_customPlaylist', clear=True)
window('emby_customPlaylist.seektime', clear=True)
window('emby_playbackProps', clear=True)
window('suspend_LibraryThread', clear=True)
log("Clear playlist properties.", 1)
2015-12-25 07:07:00 +11:00
self.stopAll()
2016-02-21 10:21:39 +11:00
def onPlayBackEnded(self):
2015-12-25 07:07:00 +11:00
# Will be called when xbmc stops playing a file
self.logMsg("ONPLAYBACK_ENDED", 2)
2016-02-04 12:06:12 +11:00
utils.window('emby_customPlaylist.seektime', clear=True)
2016-02-07 22:38:50 +11:00
utils.window('suspend_LibraryThread', clear=True)
2015-12-25 07:07:00 +11:00
self.stopAll()
def stopAll(self):
2016-02-17 19:13:37 +11:00
log = self.logMsg
lang = utils.language
settings = utils.settings
2015-12-25 07:07:00 +11:00
doUtils = self.doUtils
if not self.played_info:
return
2016-02-17 19:13:37 +11:00
log("Played_information: %s" % self.played_info, 1)
2015-12-25 07:07:00 +11:00
# Process each items
for item in self.played_info:
data = self.played_info.get(item)
if data:
2016-02-17 19:13:37 +11:00
log("Item path: %s" % item, 2)
log("Item data: %s" % data, 2)
2015-12-25 07:07:00 +11:00
runtime = data['runtime']
currentPosition = data['currentPosition']
itemid = data['item_id']
refresh_id = data['refresh_id']
currentFile = data['currentfile']
type = data['Type']
playMethod = data['playmethod']
# Prevent manually mark as watched in Kodi monitor
utils.window('emby_skipWatched%s' % itemid, value="true")
2015-12-25 07:07:00 +11:00
if currentPosition and runtime:
try:
2016-02-07 22:38:50 +11:00
percentComplete = currentPosition / int(runtime)
2015-12-25 07:07:00 +11:00
except ZeroDivisionError:
# Runtime is 0.
percentComplete = 0
2016-02-17 19:13:37 +11:00
markPlayedAt = float(settings('markPlayed')) / 100
log("Percent complete: %s Mark played at: %s"
2015-12-25 07:07:00 +11:00
% (percentComplete, markPlayedAt), 1)
# Send the delete action to the server.
offerDelete = False
2016-02-17 19:13:37 +11:00
if type == "Episode" and settings('deleteTV') == "true":
2015-12-25 07:07:00 +11:00
offerDelete = True
2016-02-17 19:13:37 +11:00
elif type == "Movie" and settings('deleteMovies') == "true":
2015-12-25 07:07:00 +11:00
offerDelete = True
2016-02-17 19:13:37 +11:00
if settings('offerDelete') != "true":
2015-12-25 07:07:00 +11:00
# Delete could be disabled, even if the subsetting is enabled.
offerDelete = False
2016-02-07 22:38:50 +11:00
# Plex: never delete
offerDelete = False
2015-12-25 07:07:00 +11:00
if percentComplete >= markPlayedAt and offerDelete:
2016-03-07 23:38:45 +11:00
resp = xbmcgui.Dialog().yesno(
lang(30091),
lang(33015),
2016-03-07 23:38:45 +11:00
autoclose=120000)
if not resp:
2016-02-17 19:13:37 +11:00
log("User skipped deletion.", 1)
continue
2015-12-25 07:07:00 +11:00
url = "{server}/emby/Items/%s?format=json" % itemid
2016-02-17 19:13:37 +11:00
log("Deleting request: %s" % itemid, 1)
doUtils(url, type="DELETE")
2016-02-07 22:38:50 +11:00
# Clean the WINDOW properties
for filename in self.played_info:
cleanup = (
'emby_%s.itemid' % filename,
'emby_%s.runtime' % filename,
'emby_%s.refreshid' % filename,
'emby_%s.playmethod' % filename,
'emby_%s.type' % filename,
'plex_%s.playQueueItemID' % filename,
'plex_%s.playlistPosition' % filename,
'plex_%s.guid' % filename
)
for item in cleanup:
utils.window(item, clear=True)
self.stopPlayback(data)
2016-02-07 22:38:50 +11:00
# Stop transcoding
if playMethod == "Transcode":
log("Transcoding for %s terminated." % itemid, 1)
deviceId = self.clientInfo.getDeviceId()
url = "{server}/emby/Videos/ActiveEncodings?DeviceId=%s" % deviceId
doUtils(url, type="DELETE")
2015-12-25 07:07:00 +11:00
self.played_info.clear()
2016-01-13 01:53:06 +11:00
2015-12-25 07:07:00 +11:00
def stopPlayback(self, data):
self.logMsg("stopPlayback called", 2)
2016-01-13 01:53:06 +11:00
itemId = data['item_id']
playTime = data['currentPosition']
duration = data.get('runtime', '')
url = "{server}/:/timeline?"
args = {
'ratingKey': itemId,
'state': 'stopped', # 'stopped', 'paused', 'buffering', 'playing'
'time': int(playTime) * 1000,
2016-02-07 22:38:50 +11:00
'duration': int(duration)
2015-12-25 07:07:00 +11:00
}
2016-01-13 01:53:06 +11:00
url = url + urlencode(args)
self.doUtils(url, type="GET")