PlexKodiConnect/resources/lib/playbackutils.py

348 lines
14 KiB
Python
Raw Normal View History

2015-12-25 07:07:00 +11:00
# -*- coding: utf-8 -*-
2016-09-02 03:20:09 +10:00
###############################################################################
2015-12-25 07:07:00 +11:00
2016-09-02 03:20:09 +10:00
import logging
2015-12-25 07:07:00 +11:00
import json
import sys
2016-02-09 05:40:58 +11:00
from urllib import urlencode
2015-12-25 07:07:00 +11:00
import xbmc
import xbmcgui
import xbmcplugin
import artwork
2015-12-25 07:07:00 +11:00
import playutils as putils
import playlist
2016-09-02 03:20:09 +10:00
from utils import window, settings, tryEncode, tryDecode
2016-04-17 21:36:41 +10:00
import downloadutils
2016-01-02 00:40:40 +11:00
2016-02-09 05:40:58 +11:00
import PlexAPI
import PlexFunctions as PF
2016-09-02 03:20:09 +10:00
###############################################################################
log = logging.getLogger("PLEX."+__name__)
2016-09-02 03:44:15 +10:00
addonName = "PlexKodiConnect"
2016-09-02 03:20:09 +10:00
###############################################################################
2015-12-25 07:07:00 +11:00
class PlaybackUtils():
2016-02-20 06:03:06 +11:00
def __init__(self, item):
2016-01-30 06:07:21 +11:00
self.item = item
2016-02-09 05:40:58 +11:00
self.API = PlexAPI.API(item)
2015-12-25 07:07:00 +11:00
2016-09-02 03:20:09 +10:00
self.userid = window('currUserId')
self.server = window('pms_server')
2015-12-25 07:07:00 +11:00
self.artwork = artwork.Artwork()
2016-06-27 00:10:32 +10:00
if self.API.getType() == 'track':
self.pl = playlist.Playlist(typus='music')
else:
self.pl = playlist.Playlist(typus='video')
2015-12-25 07:07:00 +11:00
def play(self, itemid, dbid=None):
item = self.item
2016-02-09 05:40:58 +11:00
# Hack to get only existing entry in PMS response for THIS instance of
# playbackutils :-)
self.API = PlexAPI.API(item[0])
API = self.API
listitem = xbmcgui.ListItem()
2016-02-09 05:40:58 +11:00
playutils = putils.PlayUtils(item[0])
2016-01-30 06:07:21 +11:00
2016-09-02 03:20:09 +10:00
log.info("Play called.")
playurl = playutils.getPlayUrl()
if not playurl:
return xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)
2016-04-17 21:36:41 +10:00
if dbid in (None, '999999999', 'plexnode'):
# Item is not in Kodi database, is a trailer or plex redirect
# e.g. plex.tv watch later
API.CreateListItemFromPlexItem(listitem)
self.setArtwork(listitem)
if dbid == 'plexnode':
# Need to get yet another xml to get final url
window('emby_%s.playmethod' % playurl, clear=True)
xml = downloadutils.DownloadUtils().downloadUrl(
'{server}%s' % item[0][0][0].attrib.get('key'))
if xml in (None, 401):
2016-09-02 03:20:09 +10:00
log.error('Could not download %s'
% item[0][0][0].attrib.get('key'))
2016-04-17 21:36:41 +10:00
return xbmcplugin.setResolvedUrl(
int(sys.argv[1]), False, listitem)
2016-09-02 03:20:09 +10:00
playurl = tryEncode(xml[0].attrib.get('key'))
2016-04-17 21:36:41 +10:00
window('emby_%s.playmethod' % playurl, value='DirectStream')
2016-02-20 06:03:06 +11:00
playmethod = window('emby_%s.playmethod' % playurl)
2016-02-09 05:40:58 +11:00
if playmethod == "Transcode":
2016-02-20 06:03:06 +11:00
window('emby_%s.playmethod' % playurl, clear=True)
2016-09-02 03:20:09 +10:00
playurl = tryEncode(playutils.audioSubsPref(
listitem, tryDecode(playurl)))
2016-02-20 06:03:06 +11:00
window('emby_%s.playmethod' % playurl, "Transcode")
2016-02-03 23:01:13 +11:00
listitem.setPath(playurl)
self.setProperties(playurl, listitem)
return xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
############### ORGANIZE CURRENT PLAYLIST ################
homeScreen = xbmc.getCondVisibility('Window.IsActive(home)')
2016-09-05 02:30:06 +10:00
kodiPl = self.pl.playlist
2016-09-02 03:20:09 +10:00
# Can return -1
2016-09-05 02:30:06 +10:00
startPos = max(kodiPl.getposition(), 0)
sizePlaylist = kodiPl.size()
2016-02-09 05:40:58 +11:00
self.currentPosition = startPos
2016-05-31 16:06:42 +10:00
propertiesPlayback = window('plex_playbackProps') == "true"
introsPlaylist = False
dummyPlaylist = False
2016-09-02 03:20:09 +10:00
log.info("Playlist start position: %s" % startPos)
log.info("Playlist plugin position: %s" % self.currentPosition)
log.info("Playlist size: %s" % sizePlaylist)
############### RESUME POINT ################
2016-02-09 05:40:58 +11:00
seektime, runtime = API.getRuntime()
# We need to ensure we add the intro and additional parts only once.
# Otherwise we get a loop.
if not propertiesPlayback:
2016-05-31 16:06:42 +10:00
window('plex_playbackProps', value="true")
2016-09-02 03:20:09 +10:00
log.info("Setting up properties in playlist.")
2016-02-20 06:03:06 +11:00
if (not homeScreen and not seektime and
2016-05-31 16:06:42 +10:00
window('plex_customplaylist') != "true"):
2016-09-02 03:20:09 +10:00
log.debug("Adding dummy file to playlist.")
dummyPlaylist = True
2016-09-05 02:30:06 +10:00
kodiPl.add(playurl, listitem, index=startPos)
# Remove the original item from playlist
self.pl.removefromPlaylist(startPos+1)
# Readd the original item to playlist - via jsonrpc so we have full metadata
2016-02-09 05:40:58 +11:00
self.pl.insertintoPlaylist(
self.currentPosition+1,
dbid,
PF.GetKodiTypeFromPlex(API.getType()))
self.currentPosition += 1
2016-09-02 03:20:09 +10:00
############### -- CHECK FOR INTROS ################
2016-04-12 16:40:12 +10:00
if (settings('enableCinema') == "true" and not seektime):
# if we have any play them when the movie/show is not being resumed
2016-02-09 05:40:58 +11:00
xml = PF.GetPlexPlaylist(
itemid,
item.attrib.get('librarySectionUUID'),
mediatype=API.getType())
introsPlaylist = self.AddTrailers(xml)
2016-09-02 03:20:09 +10:00
############### -- ADD MAIN ITEM ONLY FOR HOMESCREEN ##############
if homeScreen and not seektime and not sizePlaylist:
# Extend our current playlist with the actual item to play
# only if there's no playlist first
2016-09-02 03:20:09 +10:00
log.info("Adding main item to playlist.")
2016-02-09 05:40:58 +11:00
self.pl.addtoPlaylist(
dbid,
2016-02-19 22:31:55 +11:00
PF.GetKodiTypeFromPlex(API.getType()))
# Ensure that additional parts are played after the main item
2016-02-09 05:40:58 +11:00
self.currentPosition += 1
############### -- CHECK FOR ADDITIONAL PARTS ################
2016-02-09 05:40:58 +11:00
if len(item[0][0]) > 1:
# Only add to the playlist after intros have played
2016-02-09 05:40:58 +11:00
for counter, part in enumerate(item[0][0]):
2016-04-12 01:50:56 +10:00
# Never add first part
if counter == 0:
continue
2016-02-09 05:40:58 +11:00
# Set listitem and properties for each additional parts
API.setPartNumber(counter)
additionalListItem = xbmcgui.ListItem()
2016-02-09 05:40:58 +11:00
additionalPlayurl = playutils.getPlayUrl(
partNumber=counter)
2016-09-02 03:20:09 +10:00
log.debug("Adding additional part: %s" % counter)
2016-02-09 05:40:58 +11:00
self.setProperties(additionalPlayurl, additionalListItem)
self.setArtwork(additionalListItem)
# NEW to Plex
2016-03-15 03:47:05 +11:00
API.CreateListItemFromPlexItem(additionalListItem)
2016-09-05 02:30:06 +10:00
kodiPl.add(additionalPlayurl, additionalListItem,
index=self.currentPosition)
self.pl.verifyPlaylist()
2016-02-09 05:40:58 +11:00
self.currentPosition += 1
API.setPartNumber = 0
if dummyPlaylist:
# Added a dummy file to the playlist,
# because the first item is going to fail automatically.
2016-09-02 03:20:09 +10:00
log.info("Processed as a playlist. First item is skipped.")
return xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)
# We just skipped adding properties. Reset flag for next time.
elif propertiesPlayback:
2016-09-02 03:20:09 +10:00
log.debug("Resetting properties playback flag.")
2016-05-31 16:06:42 +10:00
window('plex_playbackProps', clear=True)
#self.pl.verifyPlaylist()
########## SETUP MAIN ITEM ##########
# For transcoding only, ask for audio/subs pref
2016-02-17 19:13:37 +11:00
if window('emby_%s.playmethod' % playurl) == "Transcode":
window('emby_%s.playmethod' % playurl, clear=True)
2016-09-02 03:20:09 +10:00
playurl = tryEncode(playutils.audioSubsPref(
listitem, tryDecode(playurl)))
2016-02-17 19:13:37 +11:00
window('emby_%s.playmethod' % playurl, value="Transcode")
2016-02-05 06:23:04 +11:00
listitem.setPath(playurl)
self.setProperties(playurl, listitem)
2016-02-03 23:01:13 +11:00
############### PLAYBACK ################
2016-05-31 16:06:42 +10:00
if homeScreen and seektime and window('plex_customplaylist') != "true":
2016-09-02 03:20:09 +10:00
log.info("Play as a widget item.")
2016-03-15 03:47:05 +11:00
API.CreateListItemFromPlexItem(listitem)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
2016-05-31 16:06:42 +10:00
elif ((introsPlaylist and window('plex_customplaylist') == "true") or
2016-02-17 19:13:37 +11:00
(homeScreen and not sizePlaylist)):
# Playlist was created just now, play it.
2016-09-02 03:20:09 +10:00
log.info("Play playlist.")
2016-09-05 02:30:06 +10:00
xbmc.Player().play(kodiPl, startpos=startPos)
else:
2016-09-02 03:20:09 +10:00
log.info("Play as a regular item.")
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
2016-01-30 06:07:21 +11:00
2016-02-09 05:40:58 +11:00
def AddTrailers(self, xml):
"""
Adds trailers to a movie, if applicable. Returns True if trailers were
added
"""
# Failure when downloading trailer playQueue
2016-04-12 01:50:56 +10:00
if xml in (None, 401):
2016-02-09 05:40:58 +11:00
return False
# Failure when getting trailers, e.g. when no plex pass
if xml.attrib.get('size') == '1':
return False
2016-09-02 03:20:09 +10:00
if settings('askCinema') == "true":
2016-09-02 03:44:15 +10:00
resp = xbmcgui.Dialog().yesno(addonName, "Play trailers?")
2016-02-09 05:40:58 +11:00
if not resp:
# User selected to not play trailers
2016-09-02 03:20:09 +10:00
log.info("Skip trailers.")
2016-02-09 05:40:58 +11:00
return False
# Playurl needs to point back so we can get metadata!
path = "plugin://plugin.video.plexkodiconnect.movies/"
params = {
'mode': "play",
'dbid': 999999999
}
for counter, intro in enumerate(xml):
# Don't process the last item - it's the original movie
if counter == len(xml)-1:
break
# The server randomly returns intros, process them.
# introListItem = xbmcgui.ListItem()
# introPlayurl = putils.PlayUtils(intro).getPlayUrl()
introAPI = PlexAPI.API(intro)
params['id'] = introAPI.getRatingKey()
params['filename'] = introAPI.getKey()
introPlayurl = path + '?' + urlencode(params)
2016-09-02 03:20:09 +10:00
log.info("Adding Intro: %s" % introPlayurl)
2016-02-09 05:40:58 +11:00
self.pl.insertintoPlaylist(self.currentPosition, url=introPlayurl)
self.currentPosition += 1
return True
2015-12-25 07:07:00 +11:00
def setProperties(self, playurl, listitem):
# Set all properties necessary for plugin path playback
2016-02-09 05:40:58 +11:00
itemid = self.API.getRatingKey()
itemtype = self.API.getType()
userdata = self.API.getUserData()
2015-12-25 07:07:00 +11:00
embyitem = "emby_%s" % playurl
window('%s.runtime' % embyitem, value=str(userdata['Runtime']))
2016-02-17 19:13:37 +11:00
window('%s.type' % embyitem, value=itemtype)
window('%s.itemid' % embyitem, value=itemid)
window('%s.playcount' % embyitem, value=str(userdata['PlayCount']))
2015-12-25 07:07:00 +11:00
2016-02-09 05:40:58 +11:00
if itemtype == "episode":
window('%s.refreshid' % embyitem,
2016-02-20 06:03:06 +11:00
value=self.API.getParentRatingKey())
2015-12-25 07:07:00 +11:00
else:
2016-02-17 19:13:37 +11:00
window('%s.refreshid' % embyitem, value=itemid)
2015-12-25 07:07:00 +11:00
# Append external subtitles to stream
2016-09-02 03:20:09 +10:00
playmethod = window('%s.playmethod' % embyitem)
if playmethod in ("DirectStream", "DirectPlay"):
subtitles = self.API.externalSubs(playurl)
2015-12-25 07:07:00 +11:00
listitem.setSubtitles(subtitles)
self.setArtwork(listitem)
def externalSubs(self, playurl):
externalsubs = []
mapping = {}
itemid = self.API.getRatingKey()
mediastreams = self.API.getMediaStreams()
2015-12-25 07:07:00 +11:00
kodiindex = 0
for stream in mediastreams:
index = stream['Index']
2016-09-02 03:20:09 +10:00
# Since Emby returns all possible tracks together, have to pull
# only external subtitles. IsTextSubtitleStream if true, is
# available to download from emby.
if (stream['Type'] == "Subtitle" and
2015-12-25 07:07:00 +11:00
stream['IsExternal'] and stream['IsTextSubtitleStream']):
# Direct stream
url = ("%s/Videos/%s/%s/Subtitles/%s/Stream.srt"
2016-09-02 03:20:09 +10:00
% (self.server, itemid, itemid, index))
2015-12-25 07:07:00 +11:00
# map external subtitles for mapping
mapping[kodiindex] = index
externalsubs.append(url)
kodiindex += 1
mapping = json.dumps(mapping)
2016-09-02 03:20:09 +10:00
window('emby_%s.indexMapping' % playurl, value=mapping)
2015-12-25 07:07:00 +11:00
return externalsubs
def setArtwork(self, listItem):
2016-02-09 05:40:58 +11:00
allartwork = self.API.getAllArtwork(parentInfo=True)
2015-12-25 07:07:00 +11:00
arttypes = {
'poster': "Primary",
'tvshow.poster': "Thumb",
2015-12-25 07:07:00 +11:00
'clearart': "Art",
'tvshow.clearart': "Art",
2016-02-09 05:40:58 +11:00
'clearart': "Primary",
'tvshow.clearart': "Primary",
2015-12-25 07:07:00 +11:00
'clearlogo': "Logo",
'tvshow.clearlogo': "Logo",
'discart': "Disc",
'fanart_image': "Backdrop",
'landscape': "Backdrop",
"banner": "Banner"
2015-12-25 07:07:00 +11:00
}
for arttype in arttypes:
art = arttypes[arttype]
if art == "Backdrop":
try:
# Backdrop is a list, grab the first backdrop
2015-12-25 07:07:00 +11:00
self.setArtProp(listItem, arttype, allartwork[art][0])
except:
pass
2015-12-25 07:07:00 +11:00
else:
self.setArtProp(listItem, arttype, allartwork[art])
def setArtProp(self, listItem, arttype, path):
if arttype in (
'thumb', 'fanart_image', 'small_poster', 'tiny_poster',
'medium_landscape', 'medium_poster', 'small_fanartimage',
'medium_fanartimage', 'fanart_noindicators'):
listItem.setProperty(arttype, path)
else:
listItem.setArt({arttype: path})