PlexKodiConnect/resources/lib/playbackutils.py

350 lines
13 KiB
Python
Raw Normal View History

2015-12-25 07:07:00 +11:00
# -*- coding: utf-8 -*-
#################################################################################################
import json
import sys
import xbmc
import xbmcgui
import xbmcplugin
import artwork
import downloadutils
import playutils as putils
import playlist
import read_embyserver as embyserver
import utils
2016-01-30 06:07:21 +11:00
import embydb_functions
2015-12-25 07:07:00 +11:00
2016-01-02 00:40:40 +11:00
import PlexAPI
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 PlaybackUtils():
2016-01-30 06:07:21 +11:00
2016-02-03 23:01:13 +11:00
def __init__(self, xml):
2015-12-25 07:07:00 +11:00
2016-02-03 23:01:13 +11:00
self.item = xml
2015-12-25 07:07:00 +11:00
self.doUtils = downloadutils.DownloadUtils()
self.userid = utils.window('emby_currUser')
self.server = utils.window('emby_server%s' % self.userid)
self.machineIdentifier = utils.window('plex_machineIdentifier')
2015-12-25 07:07:00 +11:00
self.artwork = artwork.Artwork()
self.emby = embyserver.Read_EmbyServer()
self.pl = playlist.Playlist()
def StartPlay(self, resume=None, resumeId=None):
2016-02-03 23:01:13 +11:00
"""
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)
2016-01-30 06:07:21 +11:00
self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
2016-02-03 23:01:13 +11:00
2016-01-30 06:07:21 +11:00
self.startPos = max(self.playlist.getposition(), 0) # Can return -1
2016-02-03 23:01:13 +11:00
self.sizePlaylist = self.playlist.size()
2016-01-30 06:07:21 +11:00
self.currentPosition = self.startPos
2016-02-03 23:01:13 +11:00
self.logMsg("Playlist size to start: %s" % self.sizePlaylist, 1)
2016-01-30 06:07:21 +11:00
self.logMsg("Playlist start position: %s" % self.startPos, 1)
self.logMsg("Playlist position we're starting with: %s"
% self.currentPosition, 1)
2016-02-03 23:01:13 +11:00
# 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
2016-01-30 06:07:21 +11:00
2016-02-03 23:01:13 +11:00
# Run through the passed PMS playlist and construct self.playlist
listitems = []
2016-02-05 01:57:24 +11:00
# Open DB
embyconn = utils.kodiSQL('emby')
embycursor = embyconn.cursor()
emby_db = embydb_functions.Embydb_Functions(embycursor)
2016-01-30 06:07:21 +11:00
for mediaItem in self.item:
2016-02-05 01:57:24 +11:00
listitems += self.AddMediaItemToPlaylist(mediaItem, emby_db)
# Close DB
embyconn.close()
2016-02-03 23:01:13 +11:00
2016-02-07 23:26:28 +11:00
self.logMsg("Playlist size now: %s. Files before deletion:"
% self.playlist.size(), 2)
for i in range(self.playlist.size()):
self.logMsg(self.playlist[i].getfilename(), 2)
# Kick off playback
2016-02-03 23:01:13 +11:00
if startPlayer:
2016-02-07 23:26:28 +11:00
self.logMsg("Starting up a new xbmc.Player() instance", 2)
2016-02-07 22:38:50 +11:00
self.logMsg("Starting position: %s" % self.startPos, 1)
2016-02-03 23:01:13 +11:00
Player = xbmc.Player()
Player.play(self.playlist, startpos=self.startPos)
if resume:
try:
Player.seekTime(resume)
except:
self.logMsg("Error, could not resume", -1)
2016-02-03 23:01:13 +11:00
else:
2016-02-07 23:26:28 +11:00
self.logMsg("xbmc.Player() instance already up. Files playing:", 2)
# Delete the last playlist item because we have added it already
filename = self.playlist[-1].getfilename()
self.playlist.remove(filename)
2016-02-07 23:26:28 +11:00
for i in range(self.playlist.size()):
self.logMsg(self.playlist[i].getfilename(), 2)
xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitems[0])
2016-01-30 06:07:21 +11:00
2016-02-05 01:57:24 +11:00
def AddMediaItemToPlaylist(self, item, emby_db):
2016-01-30 06:07:21 +11:00
"""
2016-02-03 23:01:13 +11:00
Feed with ONE media item from PMS xml response
2016-01-30 06:07:21 +11:00
(on level with e.g. key=/library/metadata/220493 present)
An item may consist of several parts (e.g. movie in 2 pieces/files)
2016-02-03 23:01:13 +11:00
Returns a list of tuples: (playlistPosition, listitem)
2016-01-30 06:07:21 +11:00
"""
2016-02-03 23:01:13 +11:00
self.API = PlexAPI.API(item)
2016-01-30 06:07:21 +11:00
playutils = putils.PlayUtils(item)
2016-02-05 01:57:24 +11:00
pl = playlist.Playlist()
2015-12-25 07:07:00 +11:00
2016-01-30 06:07:21 +11:00
# Get playurls per part and process them
listitems = []
2016-02-05 06:23:04 +11:00
for counter, playurl in enumerate(playutils.getPlayUrl()):
2016-02-05 01:57:24 +11:00
# Add item via Kodi db, if found. Preserves metadata
emby_dbitem = emby_db.getItem_byId(self.API.getRatingKey())
if emby_dbitem:
kodi_id = emby_dbitem[0]
media_type = emby_dbitem[4]
pl.insertintoPlaylist(
self.currentPosition,
kodi_id,
media_type)
# Retrieve listitem that we just added by JSON
listitem = self.playlist[self.currentPosition]
# Also update the playurl below, otherwise we'll get a loop!
# E.g. Trailers
else:
self.logMsg('emby_dbitem not found. Plex ratingKey was %s'
% self.API.getRatingKey(), 1)
listitem = xbmcgui.ListItem()
2016-02-05 06:23:04 +11:00
self.setArtwork(listitem)
2016-02-05 01:57:24 +11:00
self.setListItem(listitem)
self.playlist.add(
playurl, listitem, index=self.currentPosition)
2016-01-30 06:07:21 +11:00
2016-02-05 06:23:04 +11:00
playmethod = utils.window('emby_%s.playmethod' % playurl)
2016-01-30 06:07:21 +11:00
# For transcoding only, ask for audio/subs pref
2016-02-05 06:23:04 +11:00
if playmethod == "Transcode":
utils.window('emby_%s.playmethod' % playurl, clear=True)
playurl = playutils.audioSubsPref(
2016-02-07 22:38:50 +11:00
listitem, playurl, part=counter)
utils.window('emby_%s.playmethod' % playurl, "Transcode")
2016-01-30 06:07:21 +11:00
2016-02-05 06:23:04 +11:00
self.setProperties(playurl, listitem)
2016-02-05 01:57:24 +11:00
# Update the playurl to the PMS xml response (hence no loop)
2016-02-03 23:01:13 +11:00
listitem.setPath(playurl)
2016-02-05 06:23:04 +11:00
# Append external subtitles to stream
# Only for direct play and direct stream
if playmethod != "Transcode":
# Direct play automatically appends external
listitem.setSubtitles(self.API.externalSubs(playurl))
listitems.append(listitem)
2016-02-03 23:01:13 +11:00
self.currentPosition += 1
return listitems
2016-01-30 06:07:21 +11:00
2015-12-25 07:07:00 +11:00
def setProperties(self, playurl, listitem):
# Set all properties necessary for plugin path playback
2016-01-30 06:07:21 +11:00
itemid = self.API.getRatingKey()
itemtype = self.API.getType()
2016-01-02 00:40:40 +11:00
resume, runtime = self.API.getRuntime()
2015-12-25 07:07:00 +11:00
embyitem = "emby_%s" % playurl
2016-01-02 00:40:40 +11:00
utils.window('%s.runtime' % embyitem, value=str(runtime))
2015-12-25 07:07:00 +11:00
utils.window('%s.type' % embyitem, value=itemtype)
utils.window('%s.itemid' % embyitem, value=itemid)
2016-02-05 06:23:04 +11:00
# We need to keep track of playQueueItemIDs for Plex Companion
utils.window(
2016-02-07 22:38:50 +11:00
'plex_%s.playQueueItemID'
% playurl, self.API.GetPlayQueueItemID())
2016-02-05 06:23:04 +11:00
utils.window(
'plex_%s.playlistPosition'
% playurl, str(self.currentPosition))
2016-02-07 22:38:50 +11:00
utils.window(
'plex_%s.guid'
% playurl, self.API.getGuid())
2016-02-05 06:23:04 +11:00
2016-01-30 06:07:21 +11:00
if itemtype == "episode":
utils.window('%s.refreshid' % embyitem,
2016-02-03 23:01:13 +11:00
value=self.API.getParentRatingKey())
2015-12-25 07:07:00 +11:00
else:
utils.window('%s.refreshid' % embyitem, value=itemid)
def externalSubs(self, playurl):
externalsubs = []
mapping = {}
item = self.item
itemid = item['Id']
try:
mediastreams = item['MediaSources'][0]['MediaStreams']
except (TypeError, KeyError, IndexError):
return
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))
# map external subtitles for mapping
mapping[kodiindex] = index
externalsubs.append(url)
kodiindex += 1
mapping = json.dumps(mapping)
utils.window('emby_%s.indexMapping' % playurl, value=mapping)
return externalsubs
def setArtwork(self, listItem):
2016-01-02 00:40:40 +11:00
# allartwork = artwork.getAllArtwork(item, parentInfo=True)
allartwork = self.API.getAllArtwork(parentInfo=True)
2016-02-05 01:57:24 +11:00
# arttypes = {
# 'poster': "Primary",
# 'tvshow.poster': "Primary",
# 'clearart': "Art",
# 'tvshow.clearart': "Art",
# 'clearlogo': "Logo",
# 'tvshow.clearlogo': "Logo",
# 'discart': "Disc",
# 'fanart_image': "Backdrop",
# 'landscape': "Thumb"
# }
2015-12-25 07:07:00 +11:00
arttypes = {
'poster': "Primary",
'tvshow.poster': "Primary",
'clearart': "Art",
'tvshow.clearart': "Art",
2016-02-05 01:57:24 +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",
2016-02-05 01:57:24 +11:00
'landscape': "Backdrop"
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
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):
API = self.API
2016-02-03 23:01:13 +11:00
mediaType = API.getType()
2015-12-25 07:07:00 +11:00
people = API.getPeople()
userdata = API.getUserData()
2016-02-03 23:01:13 +11:00
title, sorttitle = API.getTitle()
2015-12-25 07:07:00 +11:00
metadata = {
2016-02-03 23:01:13 +11:00
'genre': API.joinList(API.getGenres()),
2016-01-02 19:28:31 +11:00
'year': API.getYear(),
2016-02-03 23:01:13 +11:00
'rating': API.getAudienceRating(),
'playcount': userdata['PlayCount'],
2016-02-03 23:01:13 +11:00
'cast': people['Cast'],
2016-01-02 19:28:31 +11:00
'director': API.joinList(people.get('Director')),
2016-02-03 23:01:13 +11:00
'plot': API.getPlot(),
'title': title,
'sorttitle': sorttitle,
'duration': userdata['Runtime'],
2016-02-03 23:01:13 +11:00
'studio': API.joinList(API.getStudios()),
'tagline': API.getTagline(),
2016-01-02 19:28:31 +11:00
'writer': API.joinList(people.get('Writer')),
2016-02-03 23:01:13 +11:00
'premiered': API.getPremiereDate(),
'dateadded': API.getDateCreated(),
'lastplayed': userdata['LastPlayedDate'],
2015-12-25 07:07:00 +11:00
'mpaa': API.getMpaa(),
2016-02-05 06:23:04 +11:00
'aired': API.getPremiereDate()
2015-12-25 07:07:00 +11:00
}
2016-02-03 23:01:13 +11:00
if "Episode" in mediaType:
2015-12-25 07:07:00 +11:00
# Only for tv shows
2016-02-03 23:01:13 +11:00
key, show, season, episode = API.getEpisodeDetails()
2015-12-25 07:07:00 +11:00
metadata['episode'] = episode
2016-02-03 23:01:13 +11:00
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'])
2015-12-25 07:07:00 +11:00
listItem.setProperty('IsPlayable', 'true')
listItem.setProperty('IsFolder', 'false')
listItem.setLabel(metadata['title'])
2016-02-03 23:01:13 +11:00
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)
"""