jellyfin-kodi/resources/lib/playbackutils.py

381 lines
14 KiB
Python
Raw Normal View History

2016-03-31 15:58:49 +00:00
# -*- coding: utf-8 -*-
#################################################################################################
import json
import logging
import requests
import os
import shutil
2016-03-31 15:58:49 +00:00
import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcvfs
2016-03-31 15:58:49 +00:00
import api
import artwork
import downloadutils
import playutils as putils
import playlist
import read_embyserver as embyserver
import shutil
from utils import window, settings, language as lang
#################################################################################################
log = logging.getLogger("EMBY."+__name__)
2016-03-31 15:58:49 +00:00
#################################################################################################
class PlaybackUtils():
def __init__(self, item):
self.item = item
self.API = api.API(self.item)
self.doUtils = downloadutils.DownloadUtils().downloadUrl
2016-06-16 05:43:36 +00:00
self.userid = window('emby_currUser')
self.server = window('emby_server%s' % self.userid)
2016-03-31 15:58:49 +00:00
self.artwork = artwork.Artwork()
self.emby = embyserver.Read_EmbyServer()
self.pl = playlist.Playlist()
def play(self, itemid, dbid=None):
listitem = xbmcgui.ListItem()
2016-03-31 16:30:52 +00:00
playutils = putils.PlayUtils(self.item)
2016-03-31 15:58:49 +00:00
log.info("Play called.")
2016-03-31 15:58:49 +00:00
playurl = playutils.getPlayUrl()
if not playurl:
return xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)
if dbid is None:
# Item is not in Kodi database
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)')
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
startPos = max(playlist.getposition(), 0) # Can return -1
sizePlaylist = playlist.size()
currentPosition = startPos
propertiesPlayback = window('emby_playbackProps') == "true"
introsPlaylist = False
dummyPlaylist = False
log.debug("Playlist start position: %s" % startPos)
log.debug("Playlist plugin position: %s" % currentPosition)
log.debug("Playlist size: %s" % sizePlaylist)
2016-03-31 15:58:49 +00:00
############### RESUME POINT ################
2016-09-10 11:15:58 +00:00
userdata = self.API.get_userdata()
seektime = self.API.adjust_resume(userdata['Resume'])
2016-03-31 15:58:49 +00:00
# We need to ensure we add the intro and additional parts only once.
# Otherwise we get a loop.
if not propertiesPlayback:
window('emby_playbackProps', value="true")
log.info("Setting up properties in playlist.")
2016-03-31 15:58:49 +00:00
2016-06-16 05:43:36 +00:00
if not homeScreen and not seektime and window('emby_customPlaylist') != "true":
2016-03-31 15:58:49 +00:00
log.debug("Adding dummy file to playlist.")
2016-03-31 15:58:49 +00:00
dummyPlaylist = True
playlist.add(playurl, listitem, index=startPos)
# Remove the original item from playlist
2016-09-09 03:13:25 +00:00
self.pl.remove_from_playlist(startPos+1)
2016-03-31 15:58:49 +00:00
# Readd the original item to playlist - via jsonrpc so we have full metadata
2016-09-09 03:13:25 +00:00
self.pl.insert_to_playlist(currentPosition+1, dbid, self.item['Type'].lower())
2016-03-31 15:58:49 +00:00
currentPosition += 1
############### -- CHECK FOR INTROS ################
if settings('enableCinema') == "true" and not seektime:
# if we have any play them when the movie/show is not being resumed
url = "{server}/emby/Users/{UserId}/Items/%s/Intros?format=json" % itemid
2016-03-31 16:30:52 +00:00
intros = self.doUtils(url)
2016-03-31 15:58:49 +00:00
if intros['TotalRecordCount'] != 0:
getTrailers = True
if settings('askCinema') == "true":
2016-06-16 05:43:36 +00:00
resp = xbmcgui.Dialog().yesno("Emby for Kodi", lang(33016))
2016-03-31 15:58:49 +00:00
if not resp:
# User selected to not play trailers
getTrailers = False
log.info("Skip trailers.")
2016-03-31 15:58:49 +00:00
if getTrailers:
for intro in intros['Items']:
# The server randomly returns intros, process them.
introListItem = xbmcgui.ListItem()
introPlayurl = putils.PlayUtils(intro).getPlayUrl()
log.info("Adding Intro: %s" % introPlayurl)
2016-03-31 15:58:49 +00:00
# Set listitem and properties for intros
pbutils = PlaybackUtils(intro)
pbutils.setProperties(introPlayurl, introListItem)
2016-09-09 03:13:25 +00:00
self.pl.insert_to_playlist(currentPosition, url=introPlayurl)
2016-03-31 15:58:49 +00:00
introsPlaylist = True
currentPosition += 1
############### -- 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
log.info("Adding main item to playlist.")
2016-09-09 03:13:25 +00:00
self.pl.add_to_playlist(dbid, self.item['Type'].lower())
2016-03-31 15:58:49 +00:00
# Ensure that additional parts are played after the main item
currentPosition += 1
############### -- CHECK FOR ADDITIONAL PARTS ################
2016-03-31 16:30:52 +00:00
if self.item.get('PartCount'):
2016-03-31 15:58:49 +00:00
# Only add to the playlist after intros have played
2016-03-31 16:30:52 +00:00
partcount = self.item['PartCount']
2016-03-31 15:58:49 +00:00
url = "{server}/emby/Videos/%s/AdditionalParts?format=json" % itemid
2016-03-31 16:30:52 +00:00
parts = self.doUtils(url)
2016-03-31 15:58:49 +00:00
for part in parts['Items']:
additionalListItem = xbmcgui.ListItem()
additionalPlayurl = putils.PlayUtils(part).getPlayUrl()
log.info("Adding additional part: %s" % partcount)
2016-03-31 15:58:49 +00:00
# Set listitem and properties for each additional parts
pbutils = PlaybackUtils(part)
pbutils.setProperties(additionalPlayurl, additionalListItem)
pbutils.setArtwork(additionalListItem)
playlist.add(additionalPlayurl, additionalListItem, index=currentPosition)
2016-09-09 03:13:25 +00:00
self.pl.verify_playlist()
2016-03-31 15:58:49 +00:00
currentPosition += 1
if dummyPlaylist:
# Added a dummy file to the playlist,
# because the first item is going to fail automatically.
log.info("Processed as a playlist. First item is skipped.")
2016-03-31 15:58:49 +00:00
return xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, listitem)
# We just skipped adding properties. Reset flag for next time.
elif propertiesPlayback:
log.debug("Resetting properties playback flag.")
2016-03-31 15:58:49 +00:00
window('emby_playbackProps', clear=True)
2016-09-09 03:13:25 +00:00
#self.pl.verify_playlist()
2016-03-31 15:58:49 +00:00
########## SETUP MAIN ITEM ##########
# For transcoding only, ask for audio/subs pref
if window('emby_%s.playmethod' % playurl) == "Transcode":
# Filter ISO since Emby does not probe anymore
if self.item.get('VideoType') == "Iso":
log.info("Skipping audio/subs prompt, ISO detected.")
else:
playurl = playutils.audioSubsPref(playurl, listitem)
window('emby_%s.playmethod' % playurl, value="Transcode")
2016-03-31 15:58:49 +00:00
listitem.setPath(playurl)
self.setProperties(playurl, listitem)
############### PLAYBACK ################
if homeScreen and seektime and window('emby_customPlaylist') != "true":
log.info("Play as a widget item.")
2016-03-31 15:58:49 +00:00
self.setListItem(listitem)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
elif ((introsPlaylist and window('emby_customPlaylist') == "true") or
(homeScreen and not sizePlaylist)):
# Playlist was created just now, play it.
log.info("Play playlist.")
2016-03-31 15:58:49 +00:00
xbmc.Player().play(playlist, startpos=startPos)
else:
log.info("Play as a regular item.")
2016-03-31 15:58:49 +00:00
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
def setProperties(self, playurl, listitem):
# Set all properties necessary for plugin path playback
2016-03-31 16:30:52 +00:00
itemid = self.item['Id']
itemtype = self.item['Type']
2016-03-31 15:58:49 +00:00
embyitem = "emby_%s" % playurl
2016-03-31 16:30:52 +00:00
window('%s.runtime' % embyitem, value=str(self.item.get('RunTimeTicks')))
2016-03-31 15:58:49 +00:00
window('%s.type' % embyitem, value=itemtype)
window('%s.itemid' % embyitem, value=itemid)
if itemtype == "Episode":
2016-03-31 16:30:52 +00:00
window('%s.refreshid' % embyitem, value=self.item.get('SeriesId'))
2016-03-31 15:58:49 +00:00
else:
window('%s.refreshid' % embyitem, value=itemid)
# Append external subtitles to stream
2016-06-16 05:43:36 +00:00
playmethod = window('%s.playmethod' % embyitem)
2016-03-31 15:58:49 +00:00
# Only for direct stream
if playmethod in ("DirectStream") and settings('enableExternalSubs') == "true":
2016-03-31 15:58:49 +00:00
# Direct play automatically appends external
subtitles = self.externalSubs(playurl)
listitem.setSubtitles(subtitles)
self.setArtwork(listitem)
def externalSubs(self, playurl):
externalsubs = []
mapping = {}
2016-03-31 16:30:52 +00:00
itemid = self.item['Id']
2016-03-31 15:58:49 +00:00
try:
2016-03-31 16:30:52 +00:00
mediastreams = self.item['MediaSources'][0]['MediaStreams']
2016-03-31 15:58:49 +00:00
except (TypeError, KeyError, IndexError):
return
temp = xbmc.translatePath(
"special://profile/addon_data/plugin.video.emby/temp/").decode('utf-8')
2016-03-31 15:58:49 +00:00
kodiindex = 0
for stream in mediastreams:
index = stream['Index']
# 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
stream['IsExternal'] and stream['IsTextSubtitleStream']):
# Direct stream
url = ("%s/Videos/%s/%s/Subtitles/%s/Stream.srt"
% (self.server, itemid, itemid, index))
if settings('downloadExternalSubs') == "true" and "Language" in stream:
filename = "Stream.%s.srt" % stream['Language']
try:
path = self._download_external_subs(url, temp, filename)
externalsubs.append(path)
except Exception as e:
log.error(e)
continue
else:
externalsubs.append(url)
2016-03-31 15:58:49 +00:00
# map external subtitles for mapping
mapping[kodiindex] = index
kodiindex += 1
mapping = json.dumps(mapping)
2016-06-16 05:43:36 +00:00
window('emby_%s.indexMapping' % playurl, value=mapping)
2016-03-31 15:58:49 +00:00
return externalsubs
def _download_external_subs(self, src, dst, filename):
if not xbmcvfs.exists(dst):
xbmcvfs.mkdir(dst)
path = os.path.join(dst, filename)
try:
response = requests.get(src, stream=True)
response.raise_for_status()
except Exception as e:
del response
raise
else:
2016-08-30 05:26:57 +00:00
with open(path, 'wb') as f:
f.write(response.content)
del response
return path
2016-03-31 15:58:49 +00:00
def setArtwork(self, listItem):
# Set up item and item info
2016-09-10 11:15:58 +00:00
allartwork = self.artwork.get_all_artwork(self.item, parent_info=True)
2016-03-31 15:58:49 +00:00
# Set artwork for listitem
arttypes = {
'poster': "Primary",
'tvshow.poster': "Primary",
'clearart': "Art",
'tvshow.clearart': "Art",
'clearlogo': "Logo",
'tvshow.clearlogo': "Logo",
'discart': "Disc",
'fanart_image': "Backdrop",
'landscape': "Thumb"
}
for arttype in arttypes:
art = arttypes[arttype]
if art == "Backdrop":
try: # Backdrop is a list, grab the first backdrop
self.setArtProp(listItem, arttype, allartwork[art][0])
except: pass
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})
def setListItem(self, listItem):
2016-09-10 11:15:58 +00:00
people = self.API.get_people()
studios = self.API.get_studios()
2016-03-31 15:58:49 +00:00
metadata = {
2016-03-31 16:30:52 +00:00
'title': self.item.get('Name', "Missing name"),
'year': self.item.get('ProductionYear'),
2016-09-10 11:15:58 +00:00
'plot': self.API.get_overview(),
2016-03-31 15:58:49 +00:00
'director': people.get('Director'),
'writer': people.get('Writer'),
2016-09-10 11:15:58 +00:00
'mpaa': self.API.get_mpaa(),
2016-03-31 16:30:52 +00:00
'genre': " / ".join(self.item['Genres']),
2016-03-31 15:58:49 +00:00
'studio': " / ".join(studios),
2016-09-10 11:15:58 +00:00
'aired': self.API.get_premiere_date(),
2016-03-31 16:30:52 +00:00
'rating': self.item.get('CommunityRating'),
'votes': self.item.get('VoteCount')
2016-03-31 15:58:49 +00:00
}
2016-03-31 16:30:52 +00:00
if "Episode" in self.item['Type']:
2016-03-31 15:58:49 +00:00
# Only for tv shows
2016-03-31 16:30:52 +00:00
thumbId = self.item.get('SeriesId')
season = self.item.get('ParentIndexNumber', -1)
episode = self.item.get('IndexNumber', -1)
show = self.item.get('SeriesName', "")
2016-03-31 15:58:49 +00:00
metadata['TVShowTitle'] = show
metadata['season'] = season
metadata['episode'] = episode
listItem.setProperty('IsPlayable', 'true')
listItem.setProperty('IsFolder', 'false')
listItem.setLabel(metadata['title'])
2015-12-24 20:07:00 +00:00
listItem.setInfo('video', infoLabels=metadata)