Redesign playbackutils

This commit is contained in:
tomkat83 2016-02-03 13:01:13 +01:00
parent ef904fcd6c
commit c63e4c1bc4
8 changed files with 236 additions and 238 deletions

View file

@ -75,6 +75,7 @@ class Main:
# Simple functions
if mode == "play":
dbid = params.get('dbid')
# modes[mode](itemid, dbid)
modes[mode](itemid, dbid)
elif mode in ("nextup", "inprogressepisodes", "recentepisodes"):

View file

@ -1395,6 +1395,8 @@ class API():
"""
converts a Unix time stamp (seconds passed sinceJanuary 1 1970) to a
propper, human-readable time stamp used by Kodi
Output: Y-m-d h:m:s = 2009-04-05 23:16:04
"""
# DATEFORMAT = xbmc.getRegion('dateshort')
# TIMEFORMAT = xbmc.getRegion('meridiem')
@ -1414,7 +1416,7 @@ class API():
DATEFORMAT = xbmc.getRegion('dateshort')
TIMEFORMAT = xbmc.getRegion('meridiem')
date_time = time.localtime(float(stamp))
localdate = time.strftime('%Y-%m-%dT%H:%M:%SZ', date_time)
localdate = time.strftime('%Y-%m-%d %H:%M:%S', date_time)
except:
localdate = None
return localdate
@ -1591,9 +1593,9 @@ class API():
def getProvider(self, providername=None):
"""
providername: depricated
providername: e.g. 'imdb'
Return IMDB, e.g. "imdb://tt0903624?lang=en". Returns None if not found
Return IMDB, e.g. "tt0903624". Returns None if not found
"""
item = self.item.attrib
try:
@ -1601,7 +1603,11 @@ class API():
except KeyError:
return None
regex = re.compile(r'''com\.plexapp\.agents\.(.+)$''')
if providername == 'imdb':
regex = re.compile(r'''/(tt\d+)''')
else:
return None
provider = regex.findall(item)
try:
provider = provider[0]
@ -1729,6 +1735,9 @@ class API():
string = " / ".join(listobject)
return string
def getParentRatingKey(self):
return self.item.attrib.get('parentRatingKey', '')
def getEpisodeDetails(self):
"""
Call on a single episode.
@ -1746,7 +1755,7 @@ class API():
title = item['grandparentTitle']
season = item['parentIndex']
episode = item['index']
return str(key), title, str(season), str(episode)
return key, title, season, episode
def addPlexCredentialsToUrl(self, url, arguments={}):
"""
@ -1755,8 +1764,7 @@ class API():
arguments overrule everything
"""
token = {'X-Plex-Token': self.token}
xargs = PlexAPI().getXArgsDeviceInfo(options=token)
xargs = PlexAPI().getXArgsDeviceInfo()
xargs.update(arguments)
if '?' not in url:
url = "%s?%s" % (url, urlencode(xargs))
@ -1770,7 +1778,7 @@ class API():
If not found, empty str is returned
"""
return self.item.atrrib.get('playQueueItemID', '')
return self.item.attrib.get('playQueueItemID', '')
def getDataFromPartOrMedia(self, key):
"""
@ -1779,8 +1787,8 @@ class API():
If all fails, None is returned.
"""
media = self.item.attrib
part = self.item[self.part].attrib
media = self.item[0].attrib
part = self.item[0][self.part].attrib
try:
try:
@ -2048,6 +2056,9 @@ class API():
def getTranscodeVideoPath(self, action, quality={}, subtitle={},
audioboost=None, options={}):
"""
To be called on a VIDEO level of PMS xml response!
Transcode Video support; returns the URL to get a media started
Input:
@ -2107,18 +2118,15 @@ class API():
"wmavoice,"
"wmalossless;"
}
xargs = PlexAPI().getXArgsDeviceInfo(options=options)
# For Direct Playing
path = self.getDataFromPartOrMedia('key')
path = self.item[0][self.part].attrib['key']
xargs = PlexAPI().getXArgsDeviceInfo()
if action == "DirectPlay":
transcodePath = self.server + path
# Be sure to have exactly ONE '?' in the path (might already have
# been returned, e.g. trailers!)
if '?' not in path:
transcodePath = transcodePath + '?'
url = transcodePath + \
urlencode(clientArgs) + '&' + \
urlencode(xargs)
url = self.server + path
if '?' in url:
url += '&' + urlencode(xargs)
else:
url += '?' + urlencode(xargs)
return url
# For Direct Streaming or Transcoding
@ -2187,12 +2195,11 @@ class API():
itemid = self.getRatingKey()
kodiindex = 0
for stream in mediastreams:
# index = stream['Index']
index = stream.attrib['id']
# Since Emby returns all possible tracks together, have to pull only external subtitles.
# IsTextSubtitleStream if true, is available to download from emby.
if (stream.attrib['streamType'] == "3" and
stream.attrib['format']):
if (stream.attrib.get('streamType', '') == "3" and
stream.attrib.get('format', '')):
# Direct stream
# PLEX: TODO!!
@ -2208,39 +2215,3 @@ class API():
utils.window('emby_%s.indexMapping' % playurl, value=mapping)
return externalsubs
def GetPlexPlaylist(self):
"""
Returns raw API metadata XML dump for a playlist with e.g. trailers.
"""
item = self.item
key = self.getRatingKey()
try:
uuid = item.attrib['librarySectionUUID']
# if not found: probably trying to start a trailer directly
# Hence no playlist needed
except KeyError:
return None
mediatype = item[0].tag.lower()
trailerNumber = utils.settings('trailerNumber')
if not trailerNumber:
trailerNumber = '3'
url = "{server}/playQueues"
args = {
'type': mediatype,
'uri': 'library://' + uuid +
'/item/%2Flibrary%2Fmetadata%2F' + key,
'includeChapters': '1',
'extrasPrefixCount': trailerNumber,
'shuffle': '0',
'repeat': '0'
}
url = url + '?' + urlencode(args)
xml = downloadutils.DownloadUtils().downloadUrl(
url,
type="POST",
headerOptions={'Accept': 'application/xml'}
)
if not xml:
self.logMsg("Error retrieving metadata for %s" % url, 1)
return xml

View file

@ -7,7 +7,7 @@ import re
from xbmcaddon import Addon
import downloadutils
from utils import logMsg
from utils import logMsg, settings
addonName = Addon().getAddonInfo('name')
@ -273,3 +273,30 @@ def GetPlexCollections(mediatype):
'uuid': uuid
})
return collections
def GetPlexPlaylist(itemid, librarySectionUUID, mediatype='movie'):
"""
Returns raw API metadata XML dump for a playlist with e.g. trailers.
"""
trailerNumber = settings('trailerNumber')
if not trailerNumber:
trailerNumber = '3'
url = "{server}/playQueues"
args = {
'type': mediatype,
'uri': 'library://' + librarySectionUUID +
'/item/%2Flibrary%2Fmetadata%2F' + itemid,
'includeChapters': '1',
'extrasPrefixCount': trailerNumber,
'shuffle': '0',
'repeat': '0'
}
xml = downloadutils.DownloadUtils().downloadUrl(
url + '?' + urlencode(args), type="POST")
try:
xml[0].tag
except (IndexError, TypeError, AttributeError):
logMsg("Error retrieving metadata for %s" % url, -1)
return None
return xml

View file

@ -32,38 +32,29 @@ import embydb_functions
#################################################################################################
# For logging only
title = " %s %s" % (clientinfo.ClientInfo().getAddonName(), __name__)
addonName = clientinfo.ClientInfo().getAddonName()
title = "%s %s" % (addonName, __name__)
def plexCompanion(fullurl, params=None):
def plexCompanion(fullurl, params):
params = PlexFunctions.LiteralEval(params[26:])
utils.logMsg("entrypoint - plexCompanion",
"params is: %s" % params, -1)
# {'protocol': 'http',
# 'containerKey': '/playQueues/3045?own=1&repeat=0&window=200',
# 'offset': '0',
# 'commandID': '20',
# 'token': 'transient-0243a39f-4c7d-495f-a5c8-6991b622b5a6',
# 'key': '/library/metadata/470',
# 'address': '192.168.0.2',
# 'machineIdentifier': '3eb2fc28af89500e000db2e07f8e8234d159f2c4',
# 'type': 'video',
# 'port': '32400'}
"params is: %s" % params, -1)
if (params.get('machineIdentifier') !=
if (params['machineIdentifier'] !=
utils.window('plex_machineIdentifier')):
utils.logMsg(
title,
"Command was not for us, machineIdentifier controller: %s, "
"our machineIdentifier : %s"
% (params.get('machineIdentifier'),
% (params['machineIdentifier'],
utils.window('plex_machineIdentifier')), -1)
return
utils.window('plex_key', params.get('key'))
library, key, query = PlexFunctions.ParseContainerKey(
params.get('containerKey'))
params['containerKey'])
# Construct a container key that works always (get rid of playlist args)
utils.window('plex_containerKey', '/'+library+'/'+key)
utils.window('containerKey', '/'+library+'/'+key)
# Assume it's video when something goes wrong
playbackType = params.get('type', 'video')
@ -75,51 +66,67 @@ def plexCompanion(fullurl, params=None):
utils.logMsg(
title, "Error getting PMS playlist for key %s" % key, -1)
else:
PassPlaylist(xml, resume=int(params.get('offset', '0')))
PassPlaylist(xml, resume=int(params.get('offset', 0)))
else:
utils.logMsg(
title, "Not knowing what to do for now - no playQueue sent", -1)
def PassPlaylist(xml, resume=0):
# Set window properties to make them available later for other threads
windowArgs = [
'playQueueID',
'playQueueVersion',
'playQueueShuffled']
for arg in windowArgs:
utils.window(arg, utils.XMLAtt(xml, arg))
def PassPlaylist(xml, resume=None):
"""
resume in KodiTime - seconds.
"""
# Set window properties to make them available later for other threads
windowArgs = [
'playQueueID',
'playQueueVersion',
'playQueueShuffled']
for arg in windowArgs:
utils.window(arg, xml.attrib.get(arg, ''))
# Get resume point
resume1 = utils.IntFromStr(
utils.XMLAtt(xml, 'playQueueSelectedItemOffset'))
resume2 = resume
# Convert Plextime to Koditime
resume = PlexFunctions.ConvertPlexToKodiTime(max(resume1, resume2))
# Get resume point
resume1 = PlexFunctions.ConvertPlexToKodiTime(utils.IntFromStr(
xml.attrib.get('playQueueSelectedItemOffset')))
resume2 = resume
resume = max(resume1, resume2)
pbutils.PlaybackUtils(xml).StartPlay(
resume=resume,
resumeItem=utils.XMLAtt(xml, 'playQueueSelectedItemID'))
pbutils.PlaybackUtils(xml).StartPlay(
resume=resume,
resumeId=xml.attrib.get('playQueueSelectedItemID', None))
def doPlayback(itemid, dbid):
utils.logMsg(title, "doPlayback called with %s %s"
"""
Called only for a SINGLE element, not playQueues
"""
utils.logMsg(title, "doPlayback called with itemid=%s, dbid=%s"
% (itemid, dbid), 1)
item = PlexFunctions.GetPlexMetadata(itemid)
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
# If current playlist is NOT empty, we only need to update the item url
if playlist.size() != 0:
utils.logMsg(title, "Playlist is not empty, hence update url only", 1)
pbutils.PlaybackUtils(item).StartPlay()
else:
# Get a first XML to get the librarySectionUUID
# Use librarySectionUUID to call the playlist
xmlPlaylist = PlexAPI.API(item).GetPlexPlaylist()
if xmlPlaylist:
PassPlaylist(xmlPlaylist)
API = PlexAPI.API(item[0])
# If resume != 0, then we don't need to build a playlist for trailers etc.
# No idea how we could otherwise get resume timing out of Kodi
resume, runtime = API.getRuntime()
if resume == 0:
uuid = item.attrib.get('librarySectionUUID', None)
if uuid:
if utils.settings('askCinema') == "true":
trailers = xbmcgui.Dialog().yesno(addonName, "Play trailers?")
else:
trailers = True
if trailers:
playQueue = PlexFunctions.GetPlexPlaylist(
API.getRatingKey(), uuid, mediatype=API.getType())
if playQueue is not None:
return PassPlaylist(playQueue)
else:
utils.logMsg(title, "Error: no valid playQueue", -1)
else:
# No playlist received e.g. when directly playing trailers
pbutils.PlaybackUtils(item).StartPlay()
# E.g trailers being directly played
utils.logMsg(title, "No librarySectionUUID found.", 1)
# Play only 1 item, not playQueue
pbutils.PlaybackUtils(item).StartPlay(resume=resume,
resumeId=None)
##### DO RESET AUTH #####

View file

@ -334,7 +334,7 @@ class Movies(Items):
rating = API.getAudienceRating()
year = API.getYear()
imdb = API.getProvider()
imdb = API.getProvider('imdb')
mpaa = API.getMpaa()
countries = API.getCountry()
country = API.joinList(countries)

View file

@ -25,9 +25,9 @@ import PlexAPI
@utils.logging
class PlaybackUtils():
def __init__(self, item):
def __init__(self, xml):
self.item = item
self.item = xml
self.doUtils = downloadutils.DownloadUtils()
@ -39,131 +39,94 @@ class PlaybackUtils():
self.emby = embyserver.Read_EmbyServer()
self.pl = playlist.Playlist()
def StartPlay(self, resume=0, resumeItem=""):
self.logMsg("StartPlay called with resume=%s, resumeItem=%s"
% (resume, resumeItem), 1)
# Why should we have different behaviour if user is on home screen?!?
# self.homeScreen = xbmc.getCondVisibility('Window.IsActive(home)')
def StartPlay(self, resume=None, resumeId=None):
"""
Feed with a PMS playQueue or a single PMS item metadata XML
Every item will get put in playlist
"""
self.logMsg("StartPlay called with resume=%s, resumeId=%s"
% (resume, resumeId), 1)
self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
self.startPos = max(self.playlist.getposition(), 0) # Can return -1
sizePlaylist = self.playlist.size()
self.sizePlaylist = self.playlist.size()
self.currentPosition = self.startPos
self.logMsg("Playlist size to start: %s" % self.sizePlaylist, 1)
self.logMsg("Playlist start position: %s" % self.startPos, 1)
self.logMsg("Playlist position we're starting with: %s"
% self.currentPosition, 1)
self.logMsg("Playlist size: %s" % sizePlaylist, 1)
# Might have been called AFTER a playlist has been setup to only
# update the playitem's url
self.updateUrlOnly = True if sizePlaylist != 0 else False
# When do we need to kick off Kodi playback from start?
# if the startPos is equal than playlist size (otherwise we're asked)
# to only update an url
startPlayer = True if self.startPos == self.sizePlaylist else False
self.plexResumeItemId = resumeItem
# Where should we ultimately start playback?
self.resumePos = self.startPos
# Run through the passed PMS playlist and construct playlist
startitem = None
# Run through the passed PMS playlist and construct self.playlist
listitems = []
for mediaItem in self.item:
listitem = self.AddMediaItemToPlaylist(mediaItem)
if listitem:
startitem = listitem
listitems += self.AddMediaItemToPlaylist(mediaItem)
# Return the updated play Url if we've already setup the playlist
if self.updateUrlOnly:
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, startitem)
return
# Kick off initial playback
self.logMsg("Starting playback", 1)
Player = xbmc.Player()
Player.play(self.playlist, startpos=self.resumePos)
if resume != 0:
try:
Player.seekTime(resume)
except:
self.logMsg("Could not use resume: %s. Start from beginning."
% resume, 0)
# Kick off playback
if startPlayer:
Player = xbmc.Player()
Player.play(self.playlist, startpos=self.startPos)
if resume:
try:
Player.seekTime(resume)
except:
self.logMsg("Error, could not resume", -1)
else:
# Delete the last playlist item because we have added it already
filename = self.playlist[-1].getfilename()
self.playlist.remove(filename)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitems[0])
def AddMediaItemToPlaylist(self, item):
"""
Feed with ONE media item from PMS json response
Feed with ONE media item from PMS xml response
(on level with e.g. key=/library/metadata/220493 present)
An item may consist of several parts (e.g. movie in 2 pieces/files)
Returns a list of tuples: (playlistPosition, listitem)
"""
API = PlexAPI.API(item)
self.API = PlexAPI.API(item)
playutils = putils.PlayUtils(item)
# If we're only updating an url, we've been handed metadata for only
# one part - no need to run over all parts
if self.updateUrlOnly:
return playutils.getPlayUrl()[0]
# e.g. itemid='219155'
itemid = API.getRatingKey()
# Get DB id from Kodi by using plex id, if that works
embyconn = utils.kodiSQL('emby')
embycursor = embyconn.cursor()
emby = embydb_functions.Embydb_Functions(embycursor)
try:
dbid = emby.getItem_byId(itemid)[0]
except TypeError:
# Trailers and the like that are not in the kodi DB
dbid = None
embyconn.close()
# Get playurls per part and process them
returnListItem = None
for counter, playurl in enumerate(playutils.getPlayUrl()):
listitems = []
for playurl in playutils.getPlayUrl():
# One new listitem per part
listitem = xbmcgui.ListItem()
# For items that are not (yet) synced to Kodi lib, e.g. trailers
if not dbid:
self.logMsg("Add item to playlist without Kodi DB id", 1)
# Add Plex credentials to url because Kodi will have no headers
playurl = API.addPlexCredentialsToUrl(playurl)
listitem.setPath(playurl)
self.setProperties(playurl, listitem)
# Set artwork already done in setProperties
self.playlist.add(
playurl, listitem, index=self.currentPosition)
self.currentPosition += 1
else:
self.logMsg("Add item to playlist with existing Kodi DB id", 1)
self.pl.addtoPlaylist(dbid, API.getType())
self.currentPosition += 1
# For transcoding only, ask for audio/subs pref
if utils.window('emby_%s.playmethod' % playurl) == "Transcode":
playurl = playutils.audioSubsPref(playurl, listitem)
utils.window('emby_%s.playmethod' % playurl, value="Transcode")
playQueueItemID = API.GetPlayQueueItemID()
# Is this the position where we should start playback?
if counter == 0:
if playQueueItemID == self.plexResumeItemId:
self.logMsg(
"Figure we should start playback at position %s "
"with playQueueItemID %s"
% (self.currentPosition, playQueueItemID), 2)
self.resumePost = self.currentPosition
returnListItem = listitem
listitem.setPath(playurl)
# Set artwork
self.setProperties(playurl, listitem)
# Set metadata
self.setListItem(listitem)
self.playlist.add(
playurl, listitem, index=self.currentPosition)
listitems.append(listitem)
self.currentPosition += 1
# We need to keep track of playQueueItemIDs for Plex Companion
playQueueItemID = self.API.GetPlayQueueItemID()
utils.window(
'plex_%s.playQueueItemID' % playurl, playQueueItemID)
utils.window(
'plex_%s.playlistPosition'
% playurl, str(self.currentPosition))
# Log the playlist that we end up with
self.pl.verifyPlaylist()
return returnListItem
return listitems
def play(self, itemid, dbid=None):
"""
Original one
"""
self.logMsg("Play called.", 1)
@ -331,10 +294,7 @@ class PlaybackUtils():
def setProperties(self, playurl, listitem):
# Set all properties necessary for plugin path playback
item = self.item
# itemid = item['Id']
itemid = self.API.getRatingKey()
# itemtype = item['Type']
itemtype = self.API.getType()
resume, runtime = self.API.getRuntime()
@ -345,7 +305,7 @@ class PlaybackUtils():
if itemtype == "episode":
utils.window('%s.refreshid' % embyitem,
value=item.get('parentRatingKey'))
value=self.API.getParentRatingKey())
else:
utils.window('%s.refreshid' % embyitem, value=itemid)
@ -398,6 +358,7 @@ class PlaybackUtils():
def setArtwork(self, listItem):
# allartwork = artwork.getAllArtwork(item, parentInfo=True)
allartwork = self.API.getAllArtwork(parentInfo=True)
self.logMsg('allartwork: %s' % allartwork, 2)
# Set artwork for listitem
arttypes = {
@ -434,37 +395,77 @@ class PlaybackUtils():
def setListItem(self, listItem):
item = self.item
API = self.API
type = API.getType()
mediaType = API.getType()
people = API.getPeople()
userdata = API.getUserData()
title, sorttitle = API.getTitle()
metadata = {
'title': API.getTitle()[0],
'year': API.getYear(),
'plot': API.getPlot(),
'director': API.joinList(people.get('Director')),
'writer': API.joinList(people.get('Writer')),
'mpaa': API.getMpaa(),
'genre': API.joinList(API.getGenres()),
'studio': API.joinList(API.getStudios()),
'aired': API.getPremiereDate(),
'year': API.getYear(),
'rating': API.getAudienceRating(),
'playcount': userdata['PlayCount'],
'cast': people['Cast'],
'director': API.joinList(people.get('Director')),
'plot': API.getPlot(),
'title': title,
'sorttitle': sorttitle,
'duration': userdata['Runtime'],
'studio': API.joinList(API.getStudios()),
'tagline': API.getTagline(),
'writer': API.joinList(people.get('Writer')),
'premiered': API.getPremiereDate(),
'dateadded': API.getDateCreated(),
'lastplayed': userdata['LastPlayedDate'],
'mpaa': API.getMpaa(),
'aired': API.getPremiereDate(),
'votes': None
}
if "Episode" in type:
if "Episode" in mediaType:
# Only for tv shows
thumbId = item.get('SeriesId')
season = item.get('ParentIndexNumber', -1)
episode = item.get('IndexNumber', -1)
show = item.get('SeriesName', "")
metadata['TVShowTitle'] = show
metadata['season'] = season
key, show, season, episode = API.getEpisodeDetails()
metadata['episode'] = episode
metadata['season'] = season
metadata['tvshowtitle'] = show
# Additional values:
# - Video Values:
# 'tracknumber': None,
# - overlay : integer (2) - range is 0..8. See GUIListItem.h for
# values
# - castandrole : list of tuples ([("Michael C. Hall","Dexter"),
# ("Jennifer Carpenter","Debra")])
# # - originaltitle : string (Big Fan)
# - code : string (tt0110293) - IMDb code
# - aired : string (2008-12-07)
# - trailer : string (/home/user/trailer.avi)
# - album : string (The Joshua Tree)
# - artist : list (['U2'])
listItem.setProperty('IsPlayable', 'true')
listItem.setProperty('IsFolder', 'false')
listItem.setLabel(metadata['title'])
listItem.setInfo('video', infoLabels=metadata)
listItem.setInfo('video', infoLabels=metadata)
"""
- Music Values:
- tracknumber : integer (8)
- discnumber : integer (2)
- duration : integer (245) - duration in seconds
- year : integer (1998)
- genre : string (Rock)
- album : string (Pulse)
- artist : string (Muse)
- title : string (American Pie)
- rating : string (3) - single character between 0 and 5
- lyrics : string (On a dark desert highway...)
- playcount : integer (2) - number of times this item has been
played
- lastplayed : string (Y-m-d h:m:s = 2009-04-05 23:16:04)
- Picture Values:
- title : string (In the last summer-1)
- picturepath : string (/home/username/pictures/img001.jpg)
- exif : string (See CPictureInfoTag::TranslateString in
PictureInfoTag.cpp for valid strings)
"""

View file

@ -93,8 +93,8 @@ class PlayUtils():
return False
# Found with e.g. trailers
if self.API.getDataFromPartOrMedia('optimizedForStreaming') == '1':
return False
# if self.API.getDataFromPartOrMedia('optimizedForStreaming') == '1':
# return False
return True
@ -208,7 +208,7 @@ class PlayUtils():
settings = self.getBitrate()
sourceBitrate = int(self.API.getDataFromPartOrMedia())
sourceBitrate = int(self.API.getDataFromPartOrMedia('bitrate'))
self.logMsg("The add-on settings bitrate is: %s, the video bitrate required is: %s" % (settings, sourceBitrate), 1)
if settings < sourceBitrate:
return False
@ -277,7 +277,6 @@ class PlayUtils():
return bitrate.get(videoQuality, 2147483)
def audioSubsPref(self, url, listitem, child=0):
self.API.setChildNumber(child)
# For transcoding only
# Present the list of audio to select from
audioStreamsList = {}

View file

@ -140,14 +140,6 @@ def logging(cls):
return cls
def XMLAtt(xml, key):
try:
result = xml.attrib['key']
except KeyError:
result = ''
return result
def IntFromStr(string):
"""
Returns an int from string or the int 0 if something happened