mirror of
https://github.com/jellyfin/jellyfin-kodi.git
synced 2025-08-15 03:51:35 +00:00
Version 4.0.0 (#182)
* Adjust refresh behavior * Fix favorites * Add option to mask info * Fix keymap delete * Fix empty show * Version bump 3.1.14 * Reset rescan flag * Fix subtitles encoding * Fix path verification * Fix update library Plug in remove library percentage * Fix unauthorized behavior Reprompt user with login * Fix series pooling * Version bump 3.1.15 * Fix for additional users Return all users, not just public users * Fix http potential errors Prevent from going further if {server} or {userid} is requested but not filled to avoid 401 errors * Fix extra fanart * Fix patch make a case insensitive search * Version bump 3.1.16 Additional logging, fix kodi source. * Fix library tags on update * Version bump 3.1.17 * Fix season artwork * Fix season artwork * Fix logging * Fix blank files sources * Add backup option * Fix userdata song * Transfer data.txt to data.json Use default port for webserver caching * Fix mixed content shortcut * Fix path encoding for patch Hopefully this works... * Fix source nonetype error Just incase, wrap in a try/except because it's not important. * Base fast sync on server time Try to fix music video refresh to prevent cursor from moving up. * Prep subfolders for dynamic Support homevideos for now * Fix empty artist, missing Title * Version bump 3.1.18a * Version bump for objects 171076013 * Notify user of large updates Give option to back out if the user wants to manually update the libraries * Fix sources.xml verification * Prevent error in monitor Put in place try/except in case data is None * Remember sync position for manual triggers Allow to resume sync on restart for manual user triggers (update, repair). Automatically refresh boxsets if movie library is selected. use waitForAbort and emby_should_stop prop to terminate threads * Update string for sync later * Add subfolders for dynamic movies * Small fixes * Version bump 3.1.19 * Fix fast sync try/except, default back to previous behavior. * Fix artwork * Change settings name To ensure it takes default value instead of previous value set in 3.0.34 * Fix transcode flac and live tv * Fix episodes for series pooling * Add live tv support * Version bump 3.1.20 * Revert "Small fixes" This reverts commit9ec1fa3585
. * Version bump 3.1.21 * Fix playback starting server connection instance * Fix show update * Fix boxsets * Fix lastplayed * Patch to support pre 3.6 libraries * Fix slowness * Plug in settings for threading * Plug in settings for threading * Adjust sleep behavior * Version bump 3.1.22 * Fix server detection in monitor * Version bump 3.1.23 * Fix potential error with checksum * Fix missing new artists * Fix library sync Adjust lock, re-add screensaver deactivated during sync, prep compare sync, stop library updates from being processed before startup sync is completed * Version bump 3.1.25 * Fix local trailers * Adjust lock modification * Check db version * Prevent error from creating nodes The addon automatically creates nodes at startup with prefilled information. Prevent errors in the event something goes wrong. It will fix itself down the line, after user has logged in. * Version bump 3.1.26 * Revert "Version bump 3.1.26" This reverts commitc583a69a4b
. * Fix screensaver toggle * Fix source selection for direct stream * Version bump 3.1.26 * Add progress for updates * Revise progress bar Fix typos and subsetting * content notification * Remove content with update library Now remove irrelevant content as well * Fix slowness * Version bump 3.1.27 * Stop trying to get items if server offline * Fix content type for dynamic music * Fix resume sync Now save progress, unless exited due to path validation * Fix artwork for shortcuts on profile switch * Add force transcode settings * Fix audiobooks back to video type Add shortcuts. Audiobook can't be music type otherwise it break resume behavior and it won't play the right item. Has to be video type. * Update general info To finish, download and installation * Update README.md * Move welcome message to service * Prevent patch loop Try once, then let it go, to avoid locking user in a restart loop * Review library threads * Prep for audiobook transcode Still need to implement universal for audio transcode * Version bump 3.1.28 * Fix emby database locked * Fix regression to welcome message * Version bump 3.1.29 * Adjust playback Allow direct play for http streams * Ensure all threads are terminated correctly * Fix empty results due to error 500 * Fix boxset refresh * Fix resume sync behavior Allow to complete the startup sync in the event user backs out of resume sync * Version bump 3.1.30 * Update patch Move patch from cache to addon_data. No longer need to restart Kodi to apply the first patch. * Fix inital sync leading to fast sync * Fix user settings Due to api change in 3.6.0.55 * krypton update * Adjust for resume settings With .55 the resume setting is set per library. Instead query server to see if the item is played to offer delete * Restart service upon check for updates To reload the new objects module. * Fix update library Only do the compare when user selects update library, also add a restart service option in the add-on settings > advanced * Version bump 3.1.31 * Update dependencies * Update FR translation * Update DE translation * Add translation * Support up next * Small service adjustment * Krypton update to support upnext * Add a verification onwake Somehow, Kodi can trigger OnWake without first trigger OnSleep. * Fix loading if special char in path * Add logging and small fixes Prepare userdata by date modified * Version bump 3.1.32 * Change default behavior of startup dialog In case it is forced closed by Kodi, allow the sync to proceed * Ensure deliveryurl is an actual url * Update README.md * Fix nextup * Fix dynamic widgets * Detect coreelect, etc * Fix progress report Silent RefreshProgress in websocket * Follow emby settings for subtitles * Version bump 3.1.33 * Add Italian translation * Fix playback for server 3.6.0.61 * Version bump 3.1.34a * Add silent catch for errors * Adjust playback progress monitor Only track progress report if the item is an emby item * Fix subtitles not following server settings * Add remove libraries, fix mixed libraries * Fix live tv For now, use transcode since direct play returns a 127.0.0.1 unusable address as the path. * Allow live tv to direct stream * Fix LiveTV * Add setting to sync during playback * Fix updates * Fix encoding error * Add optional rotten tomatoes option * Version bump 3.1.35 * Fix emby connect auth string Was preventing proper device detection when using emby connect, play to, etc. * Add setup RT * Fix audio/sub change Only for addon playback * Add developer mode * Update patch Check for updates + dev = forced grab from github * Fix RT string * Fix patch Allow dev mode to redownload zip * Fix patch ugh sleep!! * Verify patch connection * Version bump 3.1.36 * Fix libraries being wiped Catch errors to prevent false positive * Add dateutil library * Prep convert to local time * Fix string * Prep for multi db version support * Fix service restart * Add shortcut restart addon Add notification * Add database discovery * Ensure previous playback terminated * Update translation New: Polish, Dutch Updated: German, French, Italian * Version bump 3.1.37 * Quick fix for new library dateutil * Catch error for dateutil In the event the server has some weird date that can't be converted * Version bump 3.1.38 * Fix dateutil import * Fix db discovery Ignore emby.db * Version bump 3.1.39 * Add a delay if setup not completed Avoid crash from everything loading at once. * Fix database discovery Add table verification + date modified verification * Container optional playutils * Version bump 3.1.40 * Adjust database discovery Compare loaded vs discovered to avoid loading old databases by accident. * Version bump 3.1.41 * Fix discovery toggle * Version bump 3.1.42 * Add webservice for playback prep * Fix service restart * Version bump 3.1.43 * Update default sync indicator Based on overall feedback * Fix check update * Fix if server is selected but unavailable * Support songs without albums * Fix encode and params * Increase retry timeout * Fix update generating duplicates * Add manage libraries Too many entries * Fix database discovery * Fixed transcode via context menu * Fix context transcode * Quiet webservice * Update Krypton objects * Fix database discovery prompt * fixed video listitem issues for krypton * load all item details for playlists * Fix playlist * Version bump 3.1.44 * Fix force hi10p transcoding behavior Fixes the "Force Hi10p transcoding" option to only apply to h264 video codecs * Clear playlist on player.onstop * Don't clear playlist if busy spinner is active * Fix case sensitive issue at calling the log function * fix db stuff (#164) * Reload objects upon initial setup * Fix database discovery ignore db-journal * Update translation German, Italian * Use LastConnectionMode for server test * Fix compare sync * Version bump 3.1.45 * Ensure widgets get updated Container.Refresh alone doesn't seem to work * Update database discovery * Re-add texture to database discovery * Add option to enable/disable service * Remove unused strings * Fix object reload upon restart service * Update Krypton objects * Update translation Dutch, Polish * Version bump 3.1.46 * Adjust client api * Adjust subtitles behavior * Fix string typo * Only run one full sync instance Prevent user from launching multiple syncs and freezing the add-on. * added "playlists" to wnodes * Disable Audiobooks Server doesn't have a set structure yet. This feature is broken atm. * Version bump 4.0.0 * License GPL v3 * Update readme
This commit is contained in:
parent
b8613e1e66
commit
bab67ddf9b
349 changed files with 67373 additions and 21636 deletions
24
resources/lib/entrypoint/__init__.py
Normal file
24
resources/lib/entrypoint/__init__.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
#################################################################################################
|
||||
|
||||
import logging
|
||||
|
||||
import xbmc
|
||||
import xbmcvfs
|
||||
|
||||
from helper import loghandler
|
||||
from emby import Emby
|
||||
|
||||
#################################################################################################
|
||||
|
||||
Emby.set_loghandler(loghandler.LogHandler, logging.DEBUG)
|
||||
loghandler.reset()
|
||||
loghandler.config()
|
||||
LOG = logging.getLogger('EMBY.entrypoint')
|
||||
|
||||
#################################################################################################
|
||||
|
||||
from default import Events
|
||||
from service import Service
|
||||
from context import Context
|
176
resources/lib/entrypoint/context.py
Normal file
176
resources/lib/entrypoint/context.py
Normal file
|
@ -0,0 +1,176 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
#################################################################################################
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
import xbmc
|
||||
import xbmcaddon
|
||||
|
||||
import database
|
||||
from dialogs import context
|
||||
from helper import _, settings, dialog
|
||||
from downloader import TheVoid
|
||||
from objects import Actions
|
||||
|
||||
#################################################################################################
|
||||
|
||||
LOG = logging.getLogger("EMBY."+__name__)
|
||||
XML_PATH = (xbmcaddon.Addon('plugin.video.emby').getAddonInfo('path'), "default", "1080i")
|
||||
OPTIONS = {
|
||||
'Refresh': _(30410),
|
||||
'Delete': _(30409),
|
||||
'Addon': _(30408),
|
||||
'AddFav': _(30405),
|
||||
'RemoveFav': _(30406),
|
||||
'Transcode': _(30412)
|
||||
}
|
||||
|
||||
#################################################################################################
|
||||
|
||||
|
||||
class Context(object):
|
||||
|
||||
_selected_option = None
|
||||
|
||||
def __init__(self, transcode=False, delete=False):
|
||||
|
||||
try:
|
||||
self.kodi_id = sys.listitem.getVideoInfoTag().getDbId() or None
|
||||
self.media = self.get_media_type()
|
||||
self.server = sys.listitem.getProperty('embyserver') or None
|
||||
item_id = sys.listitem.getProperty('embyid')
|
||||
except AttributeError:
|
||||
self.server = None
|
||||
|
||||
if xbmc.getInfoLabel('ListItem.Property(embyid)'):
|
||||
item_id = xbmc.getInfoLabel('ListItem.Property(embyid)')
|
||||
else:
|
||||
self.kodi_id = xbmc.getInfoLabel('ListItem.DBID')
|
||||
self.media = xbmc.getInfoLabel('ListItem.DBTYPE')
|
||||
item_id = None
|
||||
|
||||
if self.server or item_id:
|
||||
self.item = TheVoid('GetItem', {'ServerId': self.server, 'Id': item_id}).get()
|
||||
else:
|
||||
self.item = self.get_item_id()
|
||||
|
||||
if self.item:
|
||||
|
||||
if transcode:
|
||||
self.transcode()
|
||||
|
||||
elif delete:
|
||||
self.delete_item()
|
||||
|
||||
elif self.select_menu():
|
||||
self.action_menu()
|
||||
|
||||
if self._selected_option.decode('utf-8') in (OPTIONS['Delete'], OPTIONS['AddFav'], OPTIONS['RemoveFav']):
|
||||
|
||||
xbmc.sleep(500)
|
||||
xbmc.executebuiltin('Container.Refresh')
|
||||
|
||||
def get_media_type(self):
|
||||
|
||||
''' Get media type based on sys.listitem. If unfilled, base on visible window.
|
||||
'''
|
||||
media = sys.listitem.getVideoInfoTag().getMediaType()
|
||||
|
||||
if not media:
|
||||
|
||||
if xbmc.getCondVisibility('Container.Content(albums)'):
|
||||
media = "album"
|
||||
elif xbmc.getCondVisibility('Container.Content(artists)'):
|
||||
media = "artist"
|
||||
elif xbmc.getCondVisibility('Container.Content(songs)'):
|
||||
media = "song"
|
||||
elif xbmc.getCondVisibility('Container.Content(pictures)'):
|
||||
media = "picture"
|
||||
else:
|
||||
LOG.info("media is unknown")
|
||||
|
||||
return media.decode('utf-8')
|
||||
|
||||
def get_item_id(self):
|
||||
|
||||
''' Get synced item from embydb.
|
||||
'''
|
||||
item = database.get_item(self.kodi_id, self.media)
|
||||
|
||||
if not item:
|
||||
return
|
||||
|
||||
return {
|
||||
'Id': item[0],
|
||||
'UserData': json.loads(item[4]) if item[4] else {},
|
||||
'Type': item[3]
|
||||
}
|
||||
|
||||
def select_menu(self):
|
||||
|
||||
''' Display the select dialog.
|
||||
Favorites, Refresh, Delete (opt), Settings.
|
||||
'''
|
||||
options = []
|
||||
|
||||
if self.item['Type'] not in ('Season'):
|
||||
|
||||
if self.item['UserData'].get('IsFavorite'):
|
||||
options.append(OPTIONS['RemoveFav'])
|
||||
else:
|
||||
options.append(OPTIONS['AddFav'])
|
||||
|
||||
options.append(OPTIONS['Refresh'])
|
||||
|
||||
if settings('enableContextDelete.bool'):
|
||||
options.append(OPTIONS['Delete'])
|
||||
|
||||
options.append(OPTIONS['Addon'])
|
||||
|
||||
context_menu = context.ContextMenu("script-emby-context.xml", *XML_PATH)
|
||||
context_menu.set_options(options)
|
||||
context_menu.doModal()
|
||||
|
||||
if context_menu.is_selected():
|
||||
self._selected_option = context_menu.get_selected()
|
||||
|
||||
return self._selected_option
|
||||
|
||||
def action_menu(self):
|
||||
|
||||
selected = self._selected_option.decode('utf-8')
|
||||
|
||||
if selected == OPTIONS['Refresh']:
|
||||
TheVoid('RefreshItem', {'ServerId': self.server, 'Id': self.item['Id']})
|
||||
|
||||
elif selected == OPTIONS['AddFav']:
|
||||
TheVoid('FavoriteItem', {'ServerId': self.server, 'Id': self.item['Id'], 'Favorite': True})
|
||||
|
||||
elif selected == OPTIONS['RemoveFav']:
|
||||
TheVoid('FavoriteItem', {'ServerId': self.server, 'Id': self.item['Id'], 'Favorite': False})
|
||||
|
||||
elif selected == OPTIONS['Addon']:
|
||||
xbmc.executebuiltin('Addon.OpenSettings(plugin.video.emby)')
|
||||
|
||||
elif selected == OPTIONS['Delete']:
|
||||
self.delete_item()
|
||||
|
||||
def delete_item(self):
|
||||
|
||||
delete = True
|
||||
|
||||
if not settings('skipContextMenu.bool'):
|
||||
|
||||
if not dialog("yesno", heading="{emby}", line1=_(33015)):
|
||||
delete = False
|
||||
|
||||
if delete:
|
||||
TheVoid('DeleteItem', {'ServerId': self.server, 'Id': self.item['Id']})
|
||||
|
||||
def transcode(self):
|
||||
filename = xbmc.getInfoLabel("ListItem.Filenameandpath")
|
||||
filename += "&transcode=true"
|
||||
xbmc.executebuiltin("PlayMedia(%s)" % filename)
|
899
resources/lib/entrypoint/default.py
Normal file
899
resources/lib/entrypoint/default.py
Normal file
|
@ -0,0 +1,899 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
#################################################################################################
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import urlparse
|
||||
import urllib
|
||||
import os
|
||||
import sys
|
||||
|
||||
import xbmc
|
||||
import xbmcvfs
|
||||
import xbmcgui
|
||||
import xbmcplugin
|
||||
import xbmcaddon
|
||||
|
||||
import client
|
||||
from database import reset, get_sync, Database, emby_db, get_credentials
|
||||
from objects import Objects, Actions
|
||||
from downloader import TheVoid
|
||||
from helper import _, event, settings, window, dialog, api, JSONRPC
|
||||
from emby import Emby
|
||||
|
||||
#################################################################################################
|
||||
|
||||
LOG = logging.getLogger("EMBY."+__name__)
|
||||
|
||||
#################################################################################################
|
||||
|
||||
|
||||
class Events(object):
|
||||
|
||||
|
||||
def __init__(self):
|
||||
|
||||
''' Parse the parameters. Reroute to our service.py
|
||||
where user is fully identified already.
|
||||
'''
|
||||
base_url = sys.argv[0]
|
||||
path = sys.argv[2]
|
||||
|
||||
try:
|
||||
params = dict(urlparse.parse_qsl(path[1:]))
|
||||
except Exception:
|
||||
params = {}
|
||||
|
||||
mode = params.get('mode')
|
||||
server = params.get('server')
|
||||
|
||||
if server == 'None':
|
||||
server = None
|
||||
|
||||
LOG.warn("path: %s params: %s", path, json.dumps(params, indent=4))
|
||||
|
||||
if '/extrafanart' in base_url:
|
||||
|
||||
emby_path = path[1:]
|
||||
emby_id = params.get('id')
|
||||
get_fanart(emby_id, emby_path, server)
|
||||
|
||||
elif '/Extras' in base_url or '/VideoFiles' in base_url:
|
||||
|
||||
emby_path = path[1:]
|
||||
emby_id = params.get('id')
|
||||
get_video_extras(emby_id, emby_path, server)
|
||||
|
||||
elif mode =='play':
|
||||
|
||||
item = TheVoid('GetItem', {'Id': params['id'], 'ServerId': server}).get()
|
||||
Actions(server).play(item, params.get('dbid'), params.get('transcode') == 'true', playlist=params.get('playlist') == 'true')
|
||||
|
||||
elif mode == 'playlist':
|
||||
event('PlayPlaylist', {'Id': params['id'], 'ServerId': server})
|
||||
elif mode == 'deviceid':
|
||||
client.reset_device_id()
|
||||
elif mode == 'reset':
|
||||
reset()
|
||||
elif mode == 'delete':
|
||||
delete_item()
|
||||
elif mode == 'refreshboxsets':
|
||||
event('SyncLibrary', {'Id': "Boxsets:Refresh"})
|
||||
elif mode == 'nextepisodes':
|
||||
get_next_episodes(params['id'], params['limit'])
|
||||
elif mode == 'browse':
|
||||
browse(params.get('type'), params.get('id'), params.get('folder'), server)
|
||||
elif mode == 'synclib':
|
||||
event('SyncLibrary', {'Id': params.get('id')})
|
||||
elif mode == 'updatelib':
|
||||
event('SyncLibrary', {'Id': params.get('id'), 'Update': True})
|
||||
elif mode == 'repairlib':
|
||||
event('RepairLibrary', {'Id': params.get('id')})
|
||||
elif mode == 'removelib':
|
||||
event('RemoveLibrary', {'Id': params.get('id')})
|
||||
elif mode == 'repairlibs':
|
||||
event('RepairLibrarySelection')
|
||||
elif mode == 'updatelibs':
|
||||
event('SyncLibrarySelection')
|
||||
elif mode == 'removelibs':
|
||||
event('RemoveLibrarySelection')
|
||||
elif mode == 'addlibs':
|
||||
event('AddLibrarySelection')
|
||||
elif mode == 'connect':
|
||||
event('EmbyConnect')
|
||||
elif mode == 'addserver':
|
||||
event('AddServer')
|
||||
elif mode == 'login':
|
||||
event('ServerConnect', {'Id': server})
|
||||
elif mode == 'removeserver':
|
||||
event('RemoveServer', {'Id': server})
|
||||
elif mode == 'settings':
|
||||
xbmc.executebuiltin('Addon.OpenSettings(plugin.video.emby)')
|
||||
elif mode == 'adduser':
|
||||
add_user()
|
||||
elif mode == 'checkupdate':
|
||||
event('CheckUpdate')
|
||||
elif mode == 'updateserver':
|
||||
event('UpdateServer')
|
||||
elif mode == 'thememedia':
|
||||
get_themes()
|
||||
elif mode == 'managelibs':
|
||||
manage_libraries()
|
||||
elif mode == 'backup':
|
||||
backup()
|
||||
elif mode == 'restartservice':
|
||||
window('emby.restart.bool', True)
|
||||
else:
|
||||
listing()
|
||||
|
||||
|
||||
def listing():
|
||||
|
||||
''' Display all emby nodes and dynamic entries when appropriate.
|
||||
'''
|
||||
total = int(window('Emby.nodes.total') or 0)
|
||||
sync = get_sync()
|
||||
whitelist = [x.replace('Mixed:', "") for x in sync['Whitelist']]
|
||||
servers = get_credentials()['Servers'][1:]
|
||||
|
||||
for i in range(total):
|
||||
|
||||
window_prop = "Emby.nodes.%s" % i
|
||||
path = window('%s.index' % window_prop)
|
||||
|
||||
if not path:
|
||||
path = window('%s.content' % window_prop) or window('%s.path' % window_prop)
|
||||
|
||||
label = window('%s.title' % window_prop)
|
||||
node = window('%s.type' % window_prop)
|
||||
artwork = window('%s.artwork' % window_prop)
|
||||
view_id = window('%s.id' % window_prop)
|
||||
context = []
|
||||
|
||||
if view_id and node in ('movies', 'tvshows', 'musicvideos', 'music', 'mixed') and view_id not in whitelist:
|
||||
label = "%s %s" % (label.decode('utf-8'), _(33166))
|
||||
context.append((_(33123), "RunPlugin(plugin://plugin.video.emby/?mode=synclib&id=%s)" % view_id))
|
||||
|
||||
if view_id and node in ('movies', 'tvshows', 'musicvideos', 'music') and view_id in whitelist:
|
||||
|
||||
context.append((_(33136), "RunPlugin(plugin://plugin.video.emby/?mode=updatelib&id=%s)" % view_id))
|
||||
context.append((_(33132), "RunPlugin(plugin://plugin.video.emby/?mode=repairlib&id=%s)" % view_id))
|
||||
context.append((_(33133), "RunPlugin(plugin://plugin.video.emby/?mode=removelib&id=%s)" % view_id))
|
||||
|
||||
LOG.debug("--[ listing/%s/%s ] %s", node, label, path)
|
||||
|
||||
if path:
|
||||
if xbmc.getCondVisibility('Window.IsActive(Pictures)') and node in ('photos', 'homevideos'):
|
||||
directory(label, path, artwork=artwork)
|
||||
elif xbmc.getCondVisibility('Window.IsActive(Videos)') and node not in ('photos', 'homevideos', 'music', 'audiobooks'):
|
||||
directory(label, path, artwork=artwork, context=context)
|
||||
elif xbmc.getCondVisibility('Window.IsActive(Music)') and node in ('music'):
|
||||
directory(label, path, artwork=artwork, context=context)
|
||||
elif not xbmc.getCondVisibility('Window.IsActive(Videos) | Window.IsActive(Pictures) | Window.IsActive(Music)'):
|
||||
directory(label, path, artwork=artwork)
|
||||
|
||||
for server in servers:
|
||||
context = []
|
||||
|
||||
if server.get('ManualAddress'):
|
||||
context.append((_(33141), "RunPlugin(plugin://plugin.video.emby/?mode=removeserver&server=%s)" % server['Id']))
|
||||
|
||||
if 'AccessToken' not in server:
|
||||
directory("%s (%s)" % (server['Name'], _(30539)), "plugin://plugin.video.emby/?mode=login&server=%s" % server['Id'], False, context=context)
|
||||
else:
|
||||
directory(server['Name'], "plugin://plugin.video.emby/?mode=browse&server=%s" % server['Id'], context=context)
|
||||
|
||||
|
||||
directory(_(33194), "plugin://plugin.video.emby/?mode=managelibs", True)
|
||||
directory(_(33134), "plugin://plugin.video.emby/?mode=addserver", False)
|
||||
directory(_(33054), "plugin://plugin.video.emby/?mode=adduser", False)
|
||||
directory(_(5), "plugin://plugin.video.emby/?mode=settings", False)
|
||||
directory(_(33058), "plugin://plugin.video.emby/?mode=reset", False)
|
||||
directory(_(33192), "plugin://plugin.video.emby/?mode=restartservice", False)
|
||||
|
||||
if settings('backupPath'):
|
||||
directory(_(33092), "plugin://plugin.video.emby/?mode=backup", False)
|
||||
|
||||
directory(_(33163), None, False, artwork="special://home/addons/plugin.video.emby/donations.png")
|
||||
|
||||
xbmcplugin.setContent(int(sys.argv[1]), 'files')
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def directory(label, path, folder=True, artwork=None, fanart=None, context=None):
|
||||
|
||||
''' Add directory listitem. context should be a list of tuples [(label, action)*]
|
||||
'''
|
||||
li = dir_listitem(label, path, artwork, fanart)
|
||||
|
||||
if context:
|
||||
li.addContextMenuItems(context)
|
||||
|
||||
xbmcplugin.addDirectoryItem(int(sys.argv[1]), path, li, folder)
|
||||
|
||||
return li
|
||||
|
||||
def dir_listitem(label, path, artwork=None, fanart=None):
|
||||
|
||||
li = xbmcgui.ListItem(label, path=path)
|
||||
li.setThumbnailImage(artwork or "special://home/addons/plugin.video.emby/icon.png")
|
||||
li.setArt({"fanart": fanart or "special://home/addons/plugin.video.emby/fanart.jpg"})
|
||||
li.setArt({"landscape": artwork or fanart or "special://home/addons/plugin.video.emby/fanart.jpg"})
|
||||
|
||||
return li
|
||||
|
||||
def manage_libraries():
|
||||
|
||||
directory(_(33098), "plugin://plugin.video.emby/?mode=refreshboxsets", False)
|
||||
directory(_(33154), "plugin://plugin.video.emby/?mode=addlibs", False)
|
||||
directory(_(33139), "plugin://plugin.video.emby/?mode=updatelibs", False)
|
||||
directory(_(33140), "plugin://plugin.video.emby/?mode=repairlibs", False)
|
||||
directory(_(33184), "plugin://plugin.video.emby/?mode=removelibs", False)
|
||||
directory(_(33060), "plugin://plugin.video.emby/?mode=thememedia", False)
|
||||
|
||||
xbmcplugin.setContent(int(sys.argv[1]), 'files')
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def browse(media, view_id=None, folder=None, server_id=None):
|
||||
|
||||
''' Browse content dynamically.
|
||||
'''
|
||||
LOG.info("--[ v:%s/%s ] %s", view_id, media, folder)
|
||||
|
||||
if not window('emby_online.bool') and server_id is None:
|
||||
|
||||
monitor = xbmc.Monitor()
|
||||
|
||||
for i in range(300):
|
||||
if window('emby_online.bool'):
|
||||
break
|
||||
elif monitor.waitForAbort(0.1):
|
||||
return
|
||||
else:
|
||||
LOG.error("Default server is not online.")
|
||||
|
||||
return
|
||||
|
||||
folder = folder.lower() if folder else None
|
||||
|
||||
if folder is None and media in ('homevideos', 'movies', 'books', 'audiobooks'):
|
||||
return browse_subfolders(media, view_id, server_id)
|
||||
|
||||
if folder and folder == 'firstletter':
|
||||
return browse_letters(media, view_id, server_id)
|
||||
|
||||
if view_id:
|
||||
|
||||
view = TheVoid('GetItem', {'ServerId': server_id, 'Id': view_id}).get()
|
||||
xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name'])
|
||||
|
||||
content_type = "files"
|
||||
|
||||
if media in ('tvshows', 'seasons', 'episodes', 'movies', 'musicvideos', 'songs', 'albums'):
|
||||
content_type = media
|
||||
elif media in ('homevideos', 'photos'):
|
||||
content_type = "images"
|
||||
elif media in ('books', 'audiobooks'):
|
||||
content_type = "videos"
|
||||
elif media == 'music':
|
||||
content_type = "artists"
|
||||
|
||||
|
||||
if folder == 'recentlyadded':
|
||||
listing = TheVoid('RecentlyAdded', {'Id': view_id, 'ServerId': server_id}).get()
|
||||
elif folder == 'genres':
|
||||
listing = TheVoid('Genres', {'Id': view_id, 'ServerId': server_id}).get()
|
||||
elif media == 'livetv':
|
||||
listing = TheVoid('LiveTV', {'Id': view_id, 'ServerId': server_id}).get()
|
||||
elif folder == 'unwatched':
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsUnplayed']}).get()
|
||||
elif folder == 'favorite':
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsFavorite']}).get()
|
||||
elif folder == 'inprogress':
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Filters': ['IsResumable']}).get()
|
||||
elif folder == 'boxsets':
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type('boxsets'), 'Recursive': True}).get()
|
||||
elif folder == 'random':
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Sort': "Random", 'Limit': 25, 'Recursive': True}).get()
|
||||
elif (folder or "").startswith('firstletter-'):
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Params': {'NameStartsWith': folder.split('-')[1]}}).get()
|
||||
elif (folder or "").startswith('genres-'):
|
||||
listing = TheVoid('Browse', {'Id': view_id, 'ServerId': server_id, 'Media': get_media_type(content_type), 'Params': {'GenreIds': folder.split('-')[1]}}).get()
|
||||
elif folder == 'favepisodes':
|
||||
listing = TheVoid('Browse', {'Media': get_media_type(content_type), 'ServerId': server_id, 'Limit': 25, 'Filters': ['IsFavorite']}).get()
|
||||
elif media == 'homevideos':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': False}).get()
|
||||
elif media == 'movies':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': True}).get()
|
||||
elif media in ('boxset', 'library'):
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': True}).get()
|
||||
elif media == 'episodes':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'Media': get_media_type(content_type), 'ServerId': server_id, 'Recursive': True}).get()
|
||||
elif media == 'boxsets':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False, 'Filters': ["Boxsets"]}).get()
|
||||
elif media == 'tvshows':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': True, 'Media': get_media_type(content_type)}).get()
|
||||
elif media == 'seasons':
|
||||
listing = TheVoid('BrowseSeason', {'Id': folder, 'ServerId': server_id}).get()
|
||||
elif media != 'files':
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False, 'Media': get_media_type(content_type)}).get()
|
||||
else:
|
||||
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False}).get()
|
||||
|
||||
|
||||
if listing:
|
||||
|
||||
actions = Actions(server_id)
|
||||
list_li = []
|
||||
listing = listing if type(listing) == list else listing.get('Items', [])
|
||||
|
||||
for item in listing:
|
||||
|
||||
li = xbmcgui.ListItem()
|
||||
li.setProperty('embyid', item['Id'])
|
||||
li.setProperty('embyserver', server_id)
|
||||
actions.set_listitem(item, li)
|
||||
|
||||
if item.get('IsFolder'):
|
||||
|
||||
params = {
|
||||
'id': view_id or item['Id'],
|
||||
'mode': "browse",
|
||||
'type': get_folder_type(item, media) or media,
|
||||
'folder': item['Id'],
|
||||
'server': server_id
|
||||
}
|
||||
path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params))
|
||||
context = []
|
||||
|
||||
if item['Type'] in ('Series', 'Season', 'Playlist'):
|
||||
context.append(("Play", "RunPlugin(plugin://plugin.video.emby/?mode=playlist&id=%s&server=%s)" % (item['Id'], server_id)))
|
||||
|
||||
if item['UserData']['Played']:
|
||||
context.append((_(16104), "RunPlugin(plugin://plugin.video.emby/?mode=unwatched&id=%s&server=%s)" % (item['Id'], server_id)))
|
||||
else:
|
||||
context.append((_(16103), "RunPlugin(plugin://plugin.video.emby/?mode=watched&id=%s&server=%s)" % (item['Id'], server_id)))
|
||||
|
||||
li.addContextMenuItems(context)
|
||||
list_li.append((path, li, True))
|
||||
|
||||
elif item['Type'] == 'Genre':
|
||||
|
||||
params = {
|
||||
'id': view_id or item['Id'],
|
||||
'mode': "browse",
|
||||
'type': get_folder_type(item, media) or media,
|
||||
'folder': 'genres-%s' % item['Id'],
|
||||
'server': server_id
|
||||
}
|
||||
path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params))
|
||||
list_li.append((path, li, True))
|
||||
|
||||
else:
|
||||
if item['Type'] not in ('Photo', 'PhotoAlbum'):
|
||||
params = {
|
||||
'id': item['Id'],
|
||||
'mode': "play",
|
||||
'server': server_id
|
||||
}
|
||||
path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params))
|
||||
li.setProperty('path', path)
|
||||
context = [(_(13412), "RunPlugin(plugin://plugin.video.emby/?mode=playlist&id=%s&server=%s)" % (item['Id'], server_id))]
|
||||
|
||||
if item['UserData']['Played']:
|
||||
context.append((_(16104), "RunPlugin(plugin://plugin.video.emby/?mode=unwatched&id=%s&server=%s)" % (item['Id'], server_id)))
|
||||
else:
|
||||
context.append((_(16103), "RunPlugin(plugin://plugin.video.emby/?mode=watched&id=%s&server=%s)" % (item['Id'], server_id)))
|
||||
|
||||
li.addContextMenuItems(context)
|
||||
|
||||
list_li.append((li.getProperty('path'), li, False))
|
||||
|
||||
xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_li, len(list_li))
|
||||
|
||||
if content_type == 'images':
|
||||
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)
|
||||
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
|
||||
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_RATING)
|
||||
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
|
||||
|
||||
xbmcplugin.setContent(int(sys.argv[1]), content_type)
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def browse_subfolders(media, view_id, server_id=None):
|
||||
|
||||
''' Display submenus for emby views.
|
||||
'''
|
||||
from views import DYNNODES
|
||||
|
||||
view = TheVoid('GetItem', {'ServerId': server_id, 'Id': view_id}).get()
|
||||
xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name'])
|
||||
nodes = DYNNODES[media]
|
||||
|
||||
for node in nodes:
|
||||
|
||||
params = {
|
||||
'id': view_id,
|
||||
'mode': "browse",
|
||||
'type': media,
|
||||
'folder': view_id if node[0] == 'all' else node[0],
|
||||
'server': server_id
|
||||
}
|
||||
path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params))
|
||||
directory(node[1] or view['Name'], path)
|
||||
|
||||
xbmcplugin.setContent(int(sys.argv[1]), 'files')
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def browse_letters(media, view_id, server_id=None):
|
||||
|
||||
''' Display letters as options.
|
||||
'''
|
||||
letters = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
|
||||
view = TheVoid('GetItem', {'ServerId': server_id, 'Id': view_id}).get()
|
||||
xbmcplugin.setPluginCategory(int(sys.argv[1]), view['Name'])
|
||||
|
||||
for node in letters:
|
||||
|
||||
params = {
|
||||
'id': view_id,
|
||||
'mode': "browse",
|
||||
'type': media,
|
||||
'folder': 'firstletter-%s' % node,
|
||||
'server': server_id
|
||||
}
|
||||
path = "%s?%s" % ("plugin://plugin.video.emby/", urllib.urlencode(params))
|
||||
directory(node, path)
|
||||
|
||||
xbmcplugin.setContent(int(sys.argv[1]), 'files')
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def get_folder_type(item, content_type=None):
|
||||
|
||||
media = item['Type']
|
||||
|
||||
if media == 'Series':
|
||||
return "seasons"
|
||||
elif media == 'Season':
|
||||
return "episodes"
|
||||
elif media == 'BoxSet':
|
||||
return "boxset"
|
||||
elif media == 'MusicArtist':
|
||||
return "albums"
|
||||
elif media == 'MusicAlbum':
|
||||
return "songs"
|
||||
elif media == 'CollectionFolder':
|
||||
return item.get('CollectionType', 'library')
|
||||
elif media == 'Folder' and content_type == 'music':
|
||||
return "albums"
|
||||
|
||||
|
||||
def get_media_type(media):
|
||||
|
||||
if media == 'movies':
|
||||
return "Movie,BoxSet"
|
||||
elif media == 'homevideos':
|
||||
return "Video,Folder,PhotoAlbum,Photo"
|
||||
elif media == 'episodes':
|
||||
return "Episode"
|
||||
elif media == 'boxsets':
|
||||
return "BoxSet"
|
||||
elif media == 'tvshows':
|
||||
return "Series"
|
||||
elif media == 'music':
|
||||
return "MusicArtist,MusicAlbum,Audio"
|
||||
|
||||
def get_fanart(item_id, path, server_id=None):
|
||||
|
||||
''' Get extra fanart for listitems. This is called by skinhelper.
|
||||
Images are stored locally, due to the Kodi caching system.
|
||||
'''
|
||||
if not item_id and 'plugin.video.emby' in path:
|
||||
item_id = path.split('/')[-2]
|
||||
|
||||
if not item_id:
|
||||
return
|
||||
|
||||
LOG.info("[ extra fanart ] %s", item_id)
|
||||
objects = Objects()
|
||||
list_li = []
|
||||
directory = xbmc.translatePath("special://thumbnails/emby/%s/" % item_id).decode('utf-8')
|
||||
server = TheVoid('GetServerAddress', {'ServerId': server_id}).get()
|
||||
|
||||
if not xbmcvfs.exists(directory):
|
||||
|
||||
xbmcvfs.mkdirs(directory)
|
||||
item = TheVoid('GetItem', {'ServerId': server_id, 'Id': item_id}).get()
|
||||
obj = objects.map(item, 'Artwork')
|
||||
backdrops = api.API(item, server).get_all_artwork(obj)
|
||||
tags = obj['BackdropTags']
|
||||
|
||||
for index, backdrop in enumerate(backdrops):
|
||||
|
||||
tag = tags[index]
|
||||
fanart = os.path.join(directory, "fanart%s.jpg" % tag)
|
||||
li = xbmcgui.ListItem(tag, path=fanart)
|
||||
xbmcvfs.copy(backdrop, fanart)
|
||||
list_li.append((fanart, li, False))
|
||||
else:
|
||||
LOG.debug("cached backdrop found")
|
||||
dirs, files = xbmcvfs.listdir(directory)
|
||||
|
||||
for file in files:
|
||||
fanart = os.path.join(directory, file.decode('utf-8'))
|
||||
li = xbmcgui.ListItem(file, path=fanart)
|
||||
list_li.append((fanart, li, False))
|
||||
|
||||
xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_li, len(list_li))
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def get_video_extras(item_id, path, server_id=None):
|
||||
|
||||
''' Returns the video files for the item as plugin listing, can be used
|
||||
to browse actual files or video extras, etc.
|
||||
'''
|
||||
if not item_id and 'plugin.video.emby' in path:
|
||||
item_id = path.split('/')[-2]
|
||||
|
||||
if not item_id:
|
||||
return
|
||||
|
||||
item = TheVoid('GetItem', {'ServerId': server_id, 'Id': item_id}).get()
|
||||
# TODO
|
||||
|
||||
"""
|
||||
def getVideoFiles(embyId,embyPath):
|
||||
#returns the video files for the item as plugin listing, can be used for browsing the actual files or videoextras etc.
|
||||
emby = embyserver.Read_EmbyServer()
|
||||
if not embyId:
|
||||
if "plugin.video.emby" in embyPath:
|
||||
embyId = embyPath.split("/")[-2]
|
||||
if embyId:
|
||||
item = emby.getItem(embyId)
|
||||
putils = playutils.PlayUtils(item)
|
||||
if putils.isDirectPlay():
|
||||
#only proceed if we can access the files directly. TODO: copy local on the fly if accessed outside
|
||||
filelocation = putils.directPlay()
|
||||
if not filelocation.endswith("/"):
|
||||
filelocation = filelocation.rpartition("/")[0]
|
||||
dirs, files = xbmcvfs.listdir(filelocation)
|
||||
for file in files:
|
||||
file = filelocation + file
|
||||
li = xbmcgui.ListItem(file, path=file)
|
||||
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=file, listitem=li)
|
||||
for dir in dirs:
|
||||
dir = filelocation + dir
|
||||
li = xbmcgui.ListItem(dir, path=dir)
|
||||
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=dir, listitem=li, isFolder=True)
|
||||
#xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
"""
|
||||
|
||||
def get_next_episodes(item_id, limit):
|
||||
|
||||
''' Only for synced content.
|
||||
'''
|
||||
with Database('emby') as embydb:
|
||||
|
||||
db = emby_db.EmbyDatabase(embydb.cursor)
|
||||
library = db.get_view_name(item_id)
|
||||
|
||||
if not library:
|
||||
return
|
||||
|
||||
result = JSONRPC('VideoLibrary.GetTVShows').execute({
|
||||
'sort': {'order': "descending", 'method': "lastplayed"},
|
||||
'filter': {
|
||||
'and': [
|
||||
{'operator': "true", 'field': "inprogress", 'value': ""},
|
||||
{'operator': "is", 'field': "tag", 'value': "%s" % library}
|
||||
]},
|
||||
'properties': ['title', 'studio', 'mpaa', 'file', 'art']
|
||||
})
|
||||
|
||||
try:
|
||||
items = result['result']['tvshows']
|
||||
except (KeyError, TypeError):
|
||||
return
|
||||
|
||||
list_li = []
|
||||
|
||||
for item in items:
|
||||
if settings('ignoreSpecialsNextEpisodes.bool'):
|
||||
params = {
|
||||
'tvshowid': item['tvshowid'],
|
||||
'sort': {'method': "episode"},
|
||||
'filter': {
|
||||
'and': [
|
||||
{'operator': "lessthan", 'field': "playcount", 'value': "1"},
|
||||
{'operator': "greaterthan", 'field': "season", 'value': "0"}
|
||||
]},
|
||||
'properties': [
|
||||
"title", "playcount", "season", "episode", "showtitle",
|
||||
"plot", "file", "rating", "resume", "tvshowid", "art",
|
||||
"streamdetails", "firstaired", "runtime", "writer",
|
||||
"dateadded", "lastplayed"
|
||||
],
|
||||
'limits': {"end": 1}
|
||||
}
|
||||
else:
|
||||
params = {
|
||||
'tvshowid': item['tvshowid'],
|
||||
'sort': {'method': "episode"},
|
||||
'filter': {'operator': "lessthan", 'field': "playcount", 'value': "1"},
|
||||
'properties': [
|
||||
"title", "playcount", "season", "episode", "showtitle",
|
||||
"plot", "file", "rating", "resume", "tvshowid", "art",
|
||||
"streamdetails", "firstaired", "runtime", "writer",
|
||||
"dateadded", "lastplayed"
|
||||
],
|
||||
'limits': {"end": 1}
|
||||
}
|
||||
|
||||
result = JSONRPC('VideoLibrary.GetEpisodes').execute(params)
|
||||
|
||||
try:
|
||||
episodes = result['result']['episodes']
|
||||
except (KeyError, TypeError):
|
||||
pass
|
||||
else:
|
||||
for episode in episodes:
|
||||
|
||||
li = create_listitem(episode)
|
||||
list_li.append((episode['file'], li))
|
||||
|
||||
if len(list_li) == limit:
|
||||
break
|
||||
|
||||
xbmcplugin.addDirectoryItems(int(sys.argv[1]), list_li, len(list_li))
|
||||
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
|
||||
xbmcplugin.endOfDirectory(int(sys.argv[1]))
|
||||
|
||||
def create_listitem(item):
|
||||
|
||||
''' Listitem based on jsonrpc items.
|
||||
'''
|
||||
title = item['title']
|
||||
label2 = ""
|
||||
li = xbmcgui.ListItem(title)
|
||||
li.setProperty('IsPlayable', "true")
|
||||
|
||||
metadata = {
|
||||
'Title': title,
|
||||
'duration': str(item['runtime']/60),
|
||||
'Plot': item['plot'],
|
||||
'Playcount': item['playcount']
|
||||
}
|
||||
|
||||
if "showtitle" in item:
|
||||
metadata['TVshowTitle'] = item['showtitle']
|
||||
label2 = item['showtitle']
|
||||
|
||||
if "episodeid" in item:
|
||||
# Listitem of episode
|
||||
metadata['mediatype'] = "episode"
|
||||
metadata['dbid'] = item['episodeid']
|
||||
|
||||
# TODO: Review once Krypton is RC - probably no longer needed if there's dbid
|
||||
if "episode" in item:
|
||||
episode = item['episode']
|
||||
metadata['Episode'] = episode
|
||||
|
||||
if "season" in item:
|
||||
season = item['season']
|
||||
metadata['Season'] = season
|
||||
|
||||
if season and episode:
|
||||
episodeno = "s%.2de%.2d" % (season, episode)
|
||||
li.setProperty('episodeno', episodeno)
|
||||
label2 = "%s - %s" % (label2, episodeno) if label2 else episodeno
|
||||
|
||||
if "firstaired" in item:
|
||||
metadata['Premiered'] = item['firstaired']
|
||||
|
||||
if "rating" in item:
|
||||
metadata['Rating'] = str(round(float(item['rating']),1))
|
||||
|
||||
if "director" in item:
|
||||
metadata['Director'] = " / ".join(item['director'])
|
||||
|
||||
if "writer" in item:
|
||||
metadata['Writer'] = " / ".join(item['writer'])
|
||||
|
||||
if "cast" in item:
|
||||
cast = []
|
||||
castandrole = []
|
||||
for person in item['cast']:
|
||||
name = person['name']
|
||||
cast.append(name)
|
||||
castandrole.append((name, person['role']))
|
||||
metadata['Cast'] = cast
|
||||
metadata['CastAndRole'] = castandrole
|
||||
|
||||
li.setLabel2(label2)
|
||||
li.setInfo(type="Video", infoLabels=metadata)
|
||||
li.setProperty('resumetime', str(item['resume']['position']))
|
||||
li.setProperty('totaltime', str(item['resume']['total']))
|
||||
li.setArt(item['art'])
|
||||
li.setThumbnailImage(item['art'].get('thumb',''))
|
||||
li.setIconImage('DefaultTVShows.png')
|
||||
li.setProperty('dbid', str(item['episodeid']))
|
||||
li.setProperty('fanart_image', item['art'].get('tvshow.fanart',''))
|
||||
|
||||
for key, value in item['streamdetails'].iteritems():
|
||||
for stream in value:
|
||||
li.addStreamInfo(key, stream)
|
||||
|
||||
return li
|
||||
|
||||
def add_user():
|
||||
|
||||
''' Add or remove users from the default server session.
|
||||
'''
|
||||
if not window('emby_online.bool'):
|
||||
return
|
||||
|
||||
session = TheVoid('GetSession', {}).get()
|
||||
users = TheVoid('GetUsers', {'IsDisabled': False, 'IsHidden': False}).get()
|
||||
current = session[0]['AdditionalUsers']
|
||||
|
||||
result = dialog("select", _(33061), [_(33062), _(33063)] if current else [_(33062)])
|
||||
|
||||
if result < 0:
|
||||
return
|
||||
|
||||
if not result: # Add user
|
||||
eligible = [x for x in users if x['Id'] not in [current_user['UserId'] for current_user in current]]
|
||||
resp = dialog("select", _(33064), [x['Name'] for x in eligible])
|
||||
|
||||
if resp < 0:
|
||||
return
|
||||
|
||||
user = eligible[resp]
|
||||
event('AddUser', {'Id': user['Id'], 'Add': True})
|
||||
else: # Remove user
|
||||
resp = dialog("select", _(33064), [x['UserName'] for x in current])
|
||||
|
||||
if resp < 0:
|
||||
return
|
||||
|
||||
user = current[resp]
|
||||
event('AddUser', {'Id': user['UserId'], 'Add': False})
|
||||
|
||||
def get_themes():
|
||||
|
||||
''' Add theme media locally, via strm. This is only for tv tunes.
|
||||
If another script is used, adjust this code.
|
||||
'''
|
||||
from helper.utils import normalize_string
|
||||
from helper.playutils import PlayUtils
|
||||
from helper.xmls import tvtunes_nfo
|
||||
|
||||
library = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/library").decode('utf-8')
|
||||
play = settings('useDirectPaths') == "1"
|
||||
|
||||
if not xbmcvfs.exists(library + '/'):
|
||||
xbmcvfs.mkdir(library)
|
||||
|
||||
if xbmc.getCondVisibility('System.HasAddon(script.tvtunes)'):
|
||||
|
||||
tvtunes = xbmcaddon.Addon(id="script.tvtunes")
|
||||
tvtunes.setSetting('custom_path_enable', "true")
|
||||
tvtunes.setSetting('custom_path', library)
|
||||
LOG.info("TV Tunes custom path is enabled and set.")
|
||||
else:
|
||||
dialog("ok", heading="{emby}", line1=_(33152))
|
||||
|
||||
return
|
||||
|
||||
with Database('emby') as embydb:
|
||||
all_views = emby_db.EmbyDatabase(embydb.cursor).get_views()
|
||||
views = [x[0] for x in all_views if x[2] in ('movies', 'tvshows', 'mixed')]
|
||||
|
||||
|
||||
items = {}
|
||||
server = TheVoid('GetServerAddress', {'ServerId': None}).get()
|
||||
token = TheVoid('GetToken', {'ServerId': None}).get()
|
||||
|
||||
for view in views:
|
||||
result = TheVoid('GetThemes', {'Type': "Video", 'Id': view}).get()
|
||||
|
||||
for item in result['Items']:
|
||||
|
||||
folder = normalize_string(item['Name'].encode('utf-8'))
|
||||
items[item['Id']] = folder
|
||||
|
||||
result = TheVoid('GetThemes', {'Type': "Song", 'Id': view}).get()
|
||||
|
||||
for item in result['Items']:
|
||||
|
||||
folder = normalize_string(item['Name'].encode('utf-8'))
|
||||
items[item['Id']] = folder
|
||||
|
||||
for item in items:
|
||||
|
||||
nfo_path = os.path.join(library, items[item])
|
||||
nfo_file = os.path.join(nfo_path, "tvtunes.nfo")
|
||||
|
||||
if not xbmcvfs.exists(nfo_path):
|
||||
xbmcvfs.mkdir(nfo_path)
|
||||
|
||||
themes = TheVoid('GetTheme', {'Id': item}).get()
|
||||
paths = []
|
||||
|
||||
for theme in themes['ThemeVideosResult']['Items'] + themes['ThemeSongsResult']['Items']:
|
||||
putils = PlayUtils(theme, False, None, server, token)
|
||||
|
||||
if play:
|
||||
paths.append(putils.direct_play(theme['MediaSources'][0]).encode('utf-8'))
|
||||
else:
|
||||
paths.append(putils.direct_url(theme['MediaSources'][0]).encode('utf-8'))
|
||||
|
||||
tvtunes_nfo(nfo_file, paths)
|
||||
|
||||
dialog("notification", heading="{emby}", message=_(33153), icon="{emby}", time=1000, sound=False)
|
||||
|
||||
def delete_item():
|
||||
|
||||
''' Delete keymap action.
|
||||
'''
|
||||
import context
|
||||
|
||||
context.Context(delete=True)
|
||||
|
||||
def backup():
|
||||
|
||||
''' Emby backup.
|
||||
'''
|
||||
from helper.utils import delete_folder, copytree
|
||||
|
||||
path = settings('backupPath')
|
||||
folder_name = "Kodi%s.%s" % (xbmc.getInfoLabel('System.BuildVersion')[:2], xbmc.getInfoLabel('System.Date(dd-mm-yy)'))
|
||||
folder_name = dialog("input", heading=_(33089), defaultt=folder_name)
|
||||
|
||||
if not folder_name:
|
||||
return
|
||||
|
||||
backup = os.path.join(path, folder_name)
|
||||
|
||||
if xbmcvfs.exists(backup + '/'):
|
||||
if not dialog("yesno", heading="{emby}", line1=_(33090)):
|
||||
|
||||
return backup()
|
||||
|
||||
delete_folder(backup)
|
||||
|
||||
addon_data = xbmc.translatePath("special://profile/addon_data/plugin.video.emby").decode('utf-8')
|
||||
destination_data = os.path.join(backup, "addon_data", "plugin.video.emby")
|
||||
destination_databases = os.path.join(backup, "Database")
|
||||
|
||||
if not xbmcvfs.mkdirs(path) or not xbmcvfs.mkdirs(destination_databases):
|
||||
|
||||
LOG.info("Unable to create all directories")
|
||||
dialog("notification", heading="{emby}", icon="{emby}", message=_(33165), sound=False)
|
||||
|
||||
return
|
||||
|
||||
copytree(addon_data, destination_data)
|
||||
|
||||
databases = Objects().objects
|
||||
|
||||
db = xbmc.translatePath(databases['emby']).decode('utf-8')
|
||||
xbmcvfs.copy(db, os.path.join(destination_databases, db.rsplit('\\', 1)[1]))
|
||||
LOG.info("copied emby.db")
|
||||
|
||||
db = xbmc.translatePath(databases['video']).decode('utf-8')
|
||||
filename = db.rsplit('\\', 1)[1]
|
||||
xbmcvfs.copy(db, os.path.join(destination_databases, filename))
|
||||
LOG.info("copied %s", filename)
|
||||
|
||||
if settings('enableMusic.bool'):
|
||||
|
||||
db = xbmc.translatePath(databases['music']).decode('utf-8')
|
||||
filename = db.rsplit('\\', 1)[1]
|
||||
xbmcvfs.copy(db, os.path.join(destination_databases, filename))
|
||||
LOG.info("copied %s", filename)
|
||||
|
||||
LOG.info("backup completed")
|
||||
dialog("ok", heading="{emby}", line1="%s %s" % (_(33091), backup))
|
520
resources/lib/entrypoint/service.py
Normal file
520
resources/lib/entrypoint/service.py
Normal file
|
@ -0,0 +1,520 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
#################################################################################################
|
||||
|
||||
import _strptime # Workaround for threads using datetime: _striptime is locked
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
import xbmc
|
||||
import xbmcgui
|
||||
|
||||
import objects
|
||||
import connect
|
||||
import client
|
||||
import library
|
||||
import setup
|
||||
import monitor
|
||||
from libraries import requests
|
||||
from views import Views, verify_kodi_defaults
|
||||
from helper import _, window, settings, event, dialog, find, compare_version
|
||||
from downloader import get_objects
|
||||
from emby import Emby
|
||||
from database import Database, emby_db, reset
|
||||
|
||||
#################################################################################################
|
||||
|
||||
LOG = logging.getLogger("EMBY."+__name__)
|
||||
|
||||
#################################################################################################
|
||||
|
||||
|
||||
class Service(xbmc.Monitor):
|
||||
|
||||
running = True
|
||||
library_thread = None
|
||||
monitor = None
|
||||
play_event = None
|
||||
warn = True
|
||||
settings = {'last_progress': datetime.today(), 'last_progress_report': datetime.today()}
|
||||
|
||||
|
||||
def __init__(self):
|
||||
|
||||
window('emby_should_stop', clear=True)
|
||||
|
||||
self.settings['addon_version'] = client.get_version()
|
||||
self.settings['profile'] = xbmc.translatePath('special://profile')
|
||||
self.settings['mode'] = settings('useDirectPaths')
|
||||
self.settings['log_level'] = settings('logLevel') or "1"
|
||||
self.settings['auth_check'] = True
|
||||
self.settings['enable_context'] = settings('enableContext.bool')
|
||||
self.settings['enable_context_transcode'] = settings('enableContextTranscode.bool')
|
||||
self.settings['kodi_companion'] = settings('kodiCompanion.bool')
|
||||
window('emby_logLevel', value=str(self.settings['log_level']))
|
||||
window('emby_kodiProfile', value=self.settings['profile'])
|
||||
settings('platformDetected', client.get_platform())
|
||||
|
||||
if self.settings['enable_context']:
|
||||
window('emby_context.bool', True)
|
||||
if self.settings['enable_context_transcode']:
|
||||
window('emby_context_transcode.bool', True)
|
||||
|
||||
LOG.warn("--->>>[ %s ]", client.get_addon_name())
|
||||
LOG.warn("Version: %s", client.get_version())
|
||||
LOG.warn("KODI Version: %s", xbmc.getInfoLabel('System.BuildVersion'))
|
||||
LOG.warn("Platform: %s", settings('platformDetected'))
|
||||
LOG.warn("Python Version: %s", sys.version)
|
||||
LOG.warn("Using dynamic paths: %s", settings('useDirectPaths') == "0")
|
||||
LOG.warn("Log Level: %s", self.settings['log_level'])
|
||||
|
||||
self.check_version()
|
||||
verify_kodi_defaults()
|
||||
|
||||
try:
|
||||
Views().get_nodes()
|
||||
except Exception as error:
|
||||
LOG.error(error)
|
||||
|
||||
window('emby.connected.bool', True)
|
||||
self.check_update()
|
||||
settings('groupedSets.bool', objects.utils.get_grouped_set())
|
||||
xbmc.Monitor.__init__(self)
|
||||
|
||||
def service(self):
|
||||
|
||||
''' Keeps the service monitor going.
|
||||
Exit on Kodi shutdown or profile switch.
|
||||
|
||||
if profile switch happens more than once,
|
||||
Threads depending on abortRequest will not trigger.
|
||||
'''
|
||||
self.monitor = monitor.Monitor()
|
||||
player = self.monitor.player
|
||||
self.connect = connect.Connect()
|
||||
self.start_default()
|
||||
|
||||
self.settings['mode'] = settings('useDirectPaths')
|
||||
|
||||
while self.running:
|
||||
if window('emby_online.bool'):
|
||||
|
||||
if self.settings['profile'] != window('emby_kodiProfile'):
|
||||
LOG.info("[ profile switch ] %s", self.settings['profile'])
|
||||
|
||||
break
|
||||
|
||||
if player.isPlaying() and player.is_playing_file(player.get_playing_file()):
|
||||
difference = datetime.today() - self.settings['last_progress']
|
||||
|
||||
if difference.seconds > 10:
|
||||
self.settings['last_progress'] = datetime.today()
|
||||
|
||||
update = (datetime.today() - self.settings['last_progress_report']).seconds > 250
|
||||
event('ReportProgressRequested', {'Report': update})
|
||||
|
||||
if update:
|
||||
self.settings['last_progress_report'] = datetime.today()
|
||||
|
||||
if window('emby.restart.bool'):
|
||||
|
||||
window('emby.restart', clear=True)
|
||||
dialog("notification", heading="{emby}", message=_(33193), icon="{emby}", time=1000, sound=False)
|
||||
|
||||
raise Exception('RestartService')
|
||||
|
||||
if self.waitForAbort(1):
|
||||
break
|
||||
|
||||
self.shutdown()
|
||||
|
||||
raise Exception("ExitService")
|
||||
|
||||
def start_default(self):
|
||||
|
||||
try:
|
||||
self.connect.register()
|
||||
setup.Setup()
|
||||
except Exception as error:
|
||||
LOG.error(error)
|
||||
|
||||
def stop_default(self):
|
||||
|
||||
window('emby_online', clear=True)
|
||||
Emby().close()
|
||||
|
||||
if self.library_thread is not None:
|
||||
|
||||
self.library_thread.stop_client()
|
||||
self.library_thread = None
|
||||
|
||||
def check_version(self):
|
||||
|
||||
''' Check the database version to ensure we do not need to do a reset.
|
||||
'''
|
||||
with Database('emby') as embydb:
|
||||
|
||||
version = emby_db.EmbyDatabase(embydb.cursor).get_version()
|
||||
LOG.info("---[ db/%s ]", version)
|
||||
|
||||
if version and compare_version(version, "3.1.0") < 0:
|
||||
resp = dialog("yesno", heading=_('addon_name'), line1=_(33022))
|
||||
|
||||
if not resp:
|
||||
|
||||
LOG.warn("Database version is out of date! USER IGNORED!")
|
||||
dialog("ok", heading=_('addon_name'), line1=_(33023))
|
||||
|
||||
raise Exception("User backed out of a required database reset")
|
||||
else:
|
||||
reset()
|
||||
|
||||
raise Exception("Completed database reset")
|
||||
|
||||
def check_update(self, forced=False):
|
||||
|
||||
''' Check for objects build version and compare.
|
||||
This pulls a dict that contains all the information for the build needed.
|
||||
'''
|
||||
LOG.info("--[ check updates/%s ]", objects.version)
|
||||
kodi = "DEV" if settings('devMode.bool') else xbmc.getInfoLabel('System.BuildVersion')
|
||||
|
||||
try:
|
||||
versions = requests.get('http://kodi.emby.media/Public%20testing/Dependencies/databases.json').json()
|
||||
build = find(versions, kodi)
|
||||
|
||||
if not build:
|
||||
raise Exception("build %s incompatible?!" % kodi)
|
||||
|
||||
label, zipfile = build.split('-', 1)
|
||||
|
||||
if label == 'DEV' and forced:
|
||||
LOG.info("--[ force/objects/%s ]", label)
|
||||
|
||||
elif label == objects.version:
|
||||
LOG.info("--[ objects/%s ]", objects.version)
|
||||
|
||||
return False
|
||||
|
||||
get_objects(zipfile, label + '.zip')
|
||||
self.reload_objects()
|
||||
|
||||
dialog("notification", heading="{emby}", message=_(33156), icon="{emby}")
|
||||
LOG.info("--[ new objects/%s ]", objects.version)
|
||||
|
||||
try:
|
||||
if compare_version(self.settings['addon_version'], objects.embyversion) < 0:
|
||||
dialog("ok", heading="{emby}", line1="%s %s" % (_(33160), objects.embyversion))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as error:
|
||||
LOG.exception(error)
|
||||
|
||||
return True
|
||||
|
||||
def onNotification(self, sender, method, data):
|
||||
|
||||
''' All notifications are sent via NotifyAll built-in or Kodi.
|
||||
Central hub.
|
||||
'''
|
||||
if sender.lower() not in ('plugin.video.emby', 'xbmc'):
|
||||
return
|
||||
|
||||
if sender == 'plugin.video.emby':
|
||||
method = method.split('.')[1]
|
||||
|
||||
if method not in ('ServerUnreachable', 'ServerShuttingDown', 'UserDataChanged', 'ServerConnect',
|
||||
'LibraryChanged', 'ServerOnline', 'SyncLibrary', 'RepairLibrary', 'RemoveLibrary',
|
||||
'EmbyConnect', 'SyncLibrarySelection', 'RepairLibrarySelection', 'AddServer',
|
||||
'Unauthorized', 'UpdateServer', 'UserConfigurationUpdated', 'ServerRestarting',
|
||||
'RemoveServer', 'AddLibrarySelection', 'CheckUpdate', 'RemoveLibrarySelection'):
|
||||
return
|
||||
|
||||
data = json.loads(data)[0]
|
||||
else:
|
||||
if method not in ('System.OnQuit', 'System.OnSleep', 'System.OnWake'):
|
||||
return
|
||||
|
||||
data = json.loads(data)
|
||||
|
||||
LOG.debug("[ %s: %s ] %s", sender, method, json.dumps(data, indent=4))
|
||||
|
||||
if method == 'ServerOnline':
|
||||
if data.get('ServerId') is None:
|
||||
|
||||
window('emby_online.bool', True)
|
||||
self.settings['auth_check'] = True
|
||||
self.warn = True
|
||||
|
||||
if settings('connectMsg.bool'):
|
||||
|
||||
users = [user for user in (settings('additionalUsers') or "").decode('utf-8').split(',') if user]
|
||||
users.insert(0, settings('username').decode('utf-8'))
|
||||
dialog("notification", heading="{emby}", message="%s %s" % (_(33000), ", ".join(users)),
|
||||
icon="{emby}", time=1500, sound=False)
|
||||
|
||||
if self.library_thread is None:
|
||||
|
||||
self.library_thread = library.Library(self)
|
||||
self.library_thread.start()
|
||||
|
||||
elif method in ('ServerUnreachable', 'ServerShuttingDown'):
|
||||
|
||||
if self.warn or data.get('ServerId'):
|
||||
|
||||
self.warn = data.get('ServerId') is not None
|
||||
dialog("notification", heading="{emby}", message=_(33146) if data.get('ServerId') is None else _(33149), icon=xbmcgui.NOTIFICATION_ERROR)
|
||||
|
||||
if data.get('ServerId') is None:
|
||||
self.stop_default()
|
||||
|
||||
if self.waitForAbort(120):
|
||||
return
|
||||
|
||||
self.start_default()
|
||||
|
||||
elif method == 'Unauthorized':
|
||||
dialog("notification", heading="{emby}", message=_(33147) if data['ServerId'] is None else _(33148), icon=xbmcgui.NOTIFICATION_ERROR)
|
||||
|
||||
if data.get('ServerId') is None and self.settings['auth_check']:
|
||||
|
||||
self.settings['auth_check'] = False
|
||||
self.stop_default()
|
||||
|
||||
if self.waitForAbort(5):
|
||||
return
|
||||
|
||||
self.start_default()
|
||||
|
||||
elif method == 'ServerRestarting':
|
||||
if data.get('ServerId'):
|
||||
return
|
||||
|
||||
if settings('restartMsg.bool'):
|
||||
dialog("notification", heading="{emby}", message=_(33006), icon="{emby}")
|
||||
|
||||
self.stop_default()
|
||||
|
||||
if self.waitForAbort(15):
|
||||
return
|
||||
|
||||
self.start_default()
|
||||
|
||||
elif method == 'ServerConnect':
|
||||
self.connect.register(data['Id'])
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'EmbyConnect':
|
||||
self.connect.setup_login_connect()
|
||||
|
||||
elif method == 'AddServer':
|
||||
|
||||
self.connect.setup_manual_server()
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'RemoveServer':
|
||||
|
||||
self.connect.remove_server(data['Id'])
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'UpdateServer':
|
||||
|
||||
dialog("ok", heading="{emby}", line1=_(33151))
|
||||
self.connect.setup_manual_server()
|
||||
|
||||
elif method == 'UserDataChanged' and self.library_thread:
|
||||
if data.get('ServerId') or not window('emby_startup.bool'):
|
||||
return
|
||||
|
||||
LOG.info("[ UserDataChanged ] %s", data)
|
||||
self.library_thread.userdata(data['UserDataList'])
|
||||
|
||||
elif method == 'LibraryChanged' and self.library_thread:
|
||||
if data.get('ServerId') or not window('emby_startup.bool'):
|
||||
return
|
||||
|
||||
LOG.info("[ LibraryChanged ] %s", data)
|
||||
self.library_thread.updated(data['ItemsUpdated'] + data['ItemsAdded'])
|
||||
self.library_thread.removed(data['ItemsRemoved'])
|
||||
|
||||
elif method == 'System.OnQuit':
|
||||
window('emby_should_stop.bool', True)
|
||||
self.running = False
|
||||
|
||||
elif method in ('SyncLibrarySelection', 'RepairLibrarySelection', 'AddLibrarySelection', 'RemoveLibrarySelection'):
|
||||
self.library_thread.select_libraries(method)
|
||||
|
||||
elif method == 'SyncLibrary':
|
||||
if not data.get('Id'):
|
||||
return
|
||||
|
||||
self.library_thread.add_library(data['Id'], data.get('Update', False))
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'RepairLibrary':
|
||||
if not data.get('Id'):
|
||||
return
|
||||
|
||||
libraries = data['Id'].split(',')
|
||||
|
||||
for lib in libraries:
|
||||
self.library_thread.remove_library(lib)
|
||||
|
||||
self.library_thread.add_library(data['Id'])
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'RemoveLibrary':
|
||||
libraries = data['Id'].split(',')
|
||||
|
||||
for lib in libraries:
|
||||
self.library_thread.remove_library(lib)
|
||||
|
||||
xbmc.executebuiltin("Container.Refresh")
|
||||
|
||||
elif method == 'System.OnSleep':
|
||||
|
||||
LOG.info("-->[ sleep ]")
|
||||
window('emby_should_stop.bool', True)
|
||||
|
||||
if self.library_thread is not None:
|
||||
|
||||
self.library_thread.stop_client()
|
||||
self.library_thread = None
|
||||
|
||||
Emby.close_all()
|
||||
self.monitor.server = []
|
||||
self.monitor.sleep = True
|
||||
|
||||
elif method == 'System.OnWake':
|
||||
|
||||
if not self.monitor.sleep:
|
||||
LOG.warn("System.OnSleep was never called, skip System.OnWake")
|
||||
|
||||
return
|
||||
|
||||
LOG.info("--<[ sleep ]")
|
||||
xbmc.sleep(10000)# Allow network to wake up
|
||||
self.monitor.sleep = False
|
||||
window('emby_should_stop', clear=True)
|
||||
|
||||
try:
|
||||
self.connect.register()
|
||||
except Exception as error:
|
||||
LOG.error(error)
|
||||
|
||||
elif method == 'GUI.OnScreensaverDeactivated':
|
||||
|
||||
LOG.info("--<[ screensaver ]")
|
||||
xbmc.sleep(5000)
|
||||
|
||||
if self.library_thread is not None:
|
||||
self.library_thread.fast_sync()
|
||||
|
||||
elif method == 'UserConfigurationUpdated':
|
||||
|
||||
if data.get('ServerId') is None:
|
||||
Views().get_views()
|
||||
|
||||
elif method == 'CheckUpdate':
|
||||
|
||||
if not self.check_update(True):
|
||||
dialog("notification", heading="{emby}", message=_(21341), icon="{emby}", sound=False)
|
||||
else:
|
||||
dialog("notification", heading="{emby}", message=_(33181), icon="{emby}", sound=False)
|
||||
window('emby.restart.bool', True)
|
||||
|
||||
def onSettingsChanged(self):
|
||||
|
||||
''' React to setting changes that impact window values.
|
||||
'''
|
||||
if window('emby_should_stop.bool'):
|
||||
return
|
||||
|
||||
if settings('logLevel') != self.settings['log_level']:
|
||||
|
||||
log_level = settings('logLevel')
|
||||
window('emby_logLevel', str(log_level))
|
||||
self.settings['logLevel'] = log_level
|
||||
LOG.warn("New log level: %s", log_level)
|
||||
|
||||
if settings('enableContext.bool') != self.settings['enable_context']:
|
||||
|
||||
window('emby_context', settings('enableContext'))
|
||||
self.settings['enable_context'] = settings('enableContext.bool')
|
||||
LOG.warn("New context setting: %s", self.settings['enable_context'])
|
||||
|
||||
if settings('enableContextTranscode.bool') != self.settings['enable_context_transcode']:
|
||||
|
||||
window('emby_context_transcode', settings('enableContextTranscode'))
|
||||
self.settings['enable_context_transcode'] = settings('enableContextTranscode.bool')
|
||||
LOG.warn("New context transcode setting: %s", self.settings['enable_context_transcode'])
|
||||
|
||||
if settings('useDirectPaths') != self.settings['mode'] and self.library_thread.started:
|
||||
|
||||
self.settings['mode'] = settings('useDirectPaths')
|
||||
LOG.warn("New playback mode setting: %s", self.settings['mode'])
|
||||
|
||||
if not self.settings.get('mode_warn'):
|
||||
|
||||
self.settings['mode_warn'] = True
|
||||
dialog("yesno", heading="{emby}", line1=_(33118))
|
||||
|
||||
if settings('kodiCompanion.bool') != self.settings['kodi_companion']:
|
||||
self.settings['kodi_companion'] = settings('kodiCompanion.bool')
|
||||
|
||||
if not self.settings['kodi_companion']:
|
||||
dialog("ok", heading="{emby}", line1=_(33138))
|
||||
|
||||
def reload_objects(self):
|
||||
|
||||
''' Reload objects which depends on the patch module.
|
||||
This allows to see the changes in code without restarting the python interpreter.
|
||||
'''
|
||||
import full_sync
|
||||
|
||||
reload_modules = ['objects.movies', 'objects.musicvideos', 'objects.tvshows',
|
||||
'objects.music', 'objects.obj', 'objects.actions', 'objects.kodi.kodi',
|
||||
'objects.kodi.movies', 'objects.kodi.musicvideos', 'objects.kodi.tvshows',
|
||||
'objects.kodi.music', 'objects.kodi.artwork', 'objects.kodi.queries',
|
||||
'objects.kodi.queries_music', 'objects.kodi.queries_texture']
|
||||
|
||||
for mod in reload_modules:
|
||||
del sys.modules[mod]
|
||||
|
||||
reload(objects.kodi)
|
||||
reload(objects)
|
||||
reload(library)
|
||||
reload(full_sync)
|
||||
reload(monitor)
|
||||
|
||||
LOG.warn("---[ objects reloaded ]")
|
||||
|
||||
def shutdown(self):
|
||||
|
||||
LOG.warn("---<[ EXITING ]")
|
||||
window('emby_should_stop.bool', True)
|
||||
|
||||
properties = [ # TODO: review
|
||||
"emby_state", "emby_serverStatus",
|
||||
"emby_syncRunning", "emby_currUser",
|
||||
|
||||
"emby_play", "emby_online", "emby.connected", "emby.resume", "emby_startup",
|
||||
"emby.external", "emby.external_check", "emby_deviceId", "emby_db_check", "emby_pathverified"
|
||||
]
|
||||
for prop in properties:
|
||||
window(prop, clear=True)
|
||||
|
||||
Emby.close_all()
|
||||
|
||||
if self.library_thread is not None:
|
||||
self.library_thread.stop_client()
|
||||
|
||||
if self.monitor is not None:
|
||||
|
||||
self.monitor.listener.stop()
|
||||
self.monitor.webservice.stop()
|
||||
|
||||
LOG.warn("---<<<[ %s ]", client.get_addon_name())
|
Loading…
Add table
Add a link
Reference in a new issue