Some fixes

This commit is contained in:
tomkat83 2017-07-02 14:42:52 +02:00
parent 051006a1ef
commit 40ba9a495f
6 changed files with 78 additions and 80 deletions

View file

@ -7,7 +7,7 @@ from urllib import quote_plus
import re import re
from copy import deepcopy from copy import deepcopy
import downloadutils from downloadutils import DownloadUtils
from utils import settings, tryEncode from utils import settings, tryEncode
from variables import PLEX_TO_KODI_TIMEFACTOR from variables import PLEX_TO_KODI_TIMEFACTOR
@ -100,10 +100,60 @@ def SelectStreams(url, args):
Does a PUT request to tell the PMS what audio and subtitle streams we have Does a PUT request to tell the PMS what audio and subtitle streams we have
chosen. chosen.
""" """
downloadutils.DownloadUtils().downloadUrl( DownloadUtils().downloadUrl(
url + '?' + urlencode(args), action_type='PUT') url + '?' + urlencode(args), action_type='PUT')
def check_connection(url, token=None, verifySSL=None):
"""
Checks connection to a Plex server, available at url. Can also be used
to check for connection with plex.tv.
Override SSL to skip the check by setting verifySSL=False
if 'None', SSL will be checked (standard requests setting)
if 'True', SSL settings from file settings are used (False/True)
Input:
url URL to Plex server (e.g. https://192.168.1.1:32400)
token appropriate token to access server. If None is passed,
the current token is used
Output:
False if server could not be reached or timeout occured
200 if connection was successfull
int or other HTML status codes as received from the server
"""
headerOptions = {'X-Plex-Token': token} if token is not None else None
if verifySSL is True:
verifySSL = None if settings('sslverify') == 'true' \
else False
if 'plex.tv' in url:
url = 'https://plex.tv/api/home/users'
else:
url = url + '/library/onDeck'
log.debug("Checking connection to server %s with verifySSL=%s"
% (url, verifySSL))
answer = DownloadUtils().downloadUrl(url,
authenticate=False,
headerOptions=headerOptions,
verifySSL=verifySSL)
if answer is None:
log.debug("Could not connect to %s" % url)
return False
try:
# xml received?
answer.attrib
except:
if answer is True:
# Maybe no xml but connection was successful nevertheless
answer = 200
else:
# Success - we downloaded an xml!
answer = 200
# We could connect but maybe were not authenticated. No worries
log.debug("Checking connection successfull. Answer: %s" % answer)
return answer
def GetPlexMetadata(key): def GetPlexMetadata(key):
""" """
Returns raw API metadata for key as an etree XML. Returns raw API metadata for key as an etree XML.
@ -130,7 +180,7 @@ def GetPlexMetadata(key):
# 'includeConcerts': 1 # 'includeConcerts': 1
} }
url = url + '?' + urlencode(arguments) url = url + '?' + urlencode(arguments)
xml = downloadutils.DownloadUtils().downloadUrl(url) xml = DownloadUtils().downloadUrl(url)
if xml == 401: if xml == 401:
# Either unauthorized (taken care of by doUtils) or PMS under strain # Either unauthorized (taken care of by doUtils) or PMS under strain
return 401 return 401
@ -187,8 +237,7 @@ def DownloadChunks(url):
'X-Plex-Container-Size': CONTAINERSIZE, 'X-Plex-Container-Size': CONTAINERSIZE,
'X-Plex-Container-Start': pos 'X-Plex-Container-Start': pos
} }
xmlpart = downloadutils.DownloadUtils().downloadUrl( xmlpart = DownloadUtils().downloadUrl(url + urlencode(args))
url + urlencode(args))
# If something went wrong - skip in the hope that it works next time # If something went wrong - skip in the hope that it works next time
try: try:
xmlpart.attrib xmlpart.attrib
@ -263,8 +312,7 @@ def get_plex_sections():
""" """
Returns all Plex sections (libraries) of the PMS as an etree xml Returns all Plex sections (libraries) of the PMS as an etree xml
""" """
return downloadutils.DownloadUtils().downloadUrl( return DownloadUtils().downloadUrl('{server}/library/sections')
'{server}/library/sections')
def init_plex_playqueue(itemid, librarySectionUUID, mediatype='movie', def init_plex_playqueue(itemid, librarySectionUUID, mediatype='movie',
@ -283,7 +331,7 @@ def init_plex_playqueue(itemid, librarySectionUUID, mediatype='movie',
} }
if trailers is True: if trailers is True:
args['extrasPrefixCount'] = settings('trailerNumber') args['extrasPrefixCount'] = settings('trailerNumber')
xml = downloadutils.DownloadUtils().downloadUrl( xml = DownloadUtils().downloadUrl(
url + '?' + urlencode(args), action_type="POST") url + '?' + urlencode(args), action_type="POST")
try: try:
xml[0].tag xml[0].tag
@ -314,7 +362,7 @@ def PMSHttpsEnabled(url):
Prefers HTTPS over HTTP Prefers HTTPS over HTTP
""" """
doUtils = downloadutils.DownloadUtils().downloadUrl doUtils = DownloadUtils().downloadUrl
res = doUtils('https://%s/identity' % url, res = doUtils('https://%s/identity' % url,
authenticate=False, authenticate=False,
verifySSL=False) verifySSL=False)
@ -344,10 +392,10 @@ def GetMachineIdentifier(url):
Returns None if something went wrong Returns None if something went wrong
""" """
xml = downloadutils.DownloadUtils().downloadUrl('%s/identity' % url, xml = DownloadUtils().downloadUrl('%s/identity' % url,
authenticate=False, authenticate=False,
verifySSL=False, verifySSL=False,
timeout=10) timeout=10)
try: try:
machineIdentifier = xml.attrib['machineIdentifier'] machineIdentifier = xml.attrib['machineIdentifier']
except (AttributeError, KeyError): except (AttributeError, KeyError):
@ -374,7 +422,7 @@ def GetPMSStatus(token):
or an empty dict. or an empty dict.
""" """
answer = {} answer = {}
xml = downloadutils.DownloadUtils().downloadUrl( xml = DownloadUtils().downloadUrl(
'{server}/status/sessions', '{server}/status/sessions',
headerOptions={'X-Plex-Token': token}) headerOptions={'X-Plex-Token': token})
try: try:
@ -414,7 +462,7 @@ def scrobble(ratingKey, state):
url = "{server}/:/unscrobble?" + urlencode(args) url = "{server}/:/unscrobble?" + urlencode(args)
else: else:
return return
downloadutils.DownloadUtils().downloadUrl(url) DownloadUtils().downloadUrl(url)
log.info("Toggled watched state for Plex item %s" % ratingKey) log.info("Toggled watched state for Plex item %s" % ratingKey)
@ -425,7 +473,7 @@ def delete_item_from_pms(plexid):
Returns True if successful, False otherwise Returns True if successful, False otherwise
""" """
if downloadutils.DownloadUtils().downloadUrl( if DownloadUtils().downloadUrl(
'{server}/library/metadata/%s' % plexid, '{server}/library/metadata/%s' % plexid,
action_type="DELETE") is True: action_type="DELETE") is True:
log.info('Successfully deleted Plex id %s from the PMS' % plexid) log.info('Successfully deleted Plex id %s from the PMS' % plexid)
@ -441,7 +489,7 @@ def get_pms_settings(url, token):
Call with url: scheme://ip:port Call with url: scheme://ip:port
""" """
return downloadutils.DownloadUtils().downloadUrl( return DownloadUtils().downloadUrl(
'%s/:/prefs' % url, '%s/:/prefs' % url,
authenticate=False, authenticate=False,
verifySSL=False, verifySSL=False,

View file

@ -236,9 +236,9 @@ def list_plex_home_users(token):
If any value is missing, None is returned instead (or "" from plex.tv) If any value is missing, None is returned instead (or "" from plex.tv)
If an error is encountered, False is returned If an error is encountered, False is returned
""" """
xml = DownloadUtils.downloadUrl('https://plex.tv/api/home/users/', xml = DownloadUtils().downloadUrl('https://plex.tv/api/home/users/',
authenticate=False, authenticate=False,
headerOptions={'X-Plex-Token': token}) headerOptions={'X-Plex-Token': token})
try: try:
xml.attrib xml.attrib
except: except:

View file

@ -8,7 +8,8 @@ from dialogs.serverconnect import ServerConnect
from connect.plex_tv import plex_tv_sign_in_with_pin from connect.plex_tv import plex_tv_sign_in_with_pin
from userclient import UserClient from userclient import UserClient
from utils import window, settings, tryEncode, language as lang, dialog from utils import window, settings, tryEncode, language as lang, dialog
from PlexFunctions import GetMachineIdentifier, get_pms_settings from PlexFunctions import GetMachineIdentifier, get_pms_settings, \
check_connection
import variables as v import variables as v
############################################################################### ###############################################################################
@ -20,58 +21,6 @@ log = getLogger("PLEX."+__name__)
############################################################################### ###############################################################################
def check_connection(url, token=None, verifySSL=None):
"""
Checks connection to a Plex server, available at url. Can also be used
to check for connection with plex.tv.
Override SSL to skip the check by setting verifySSL=False
if 'None', SSL will be checked (standard requests setting)
if 'True', SSL settings from file settings are used (False/True)
Input:
url URL to Plex server (e.g. https://192.168.1.1:32400)
token appropriate token to access server. If None is passed,
the current token is used
Output:
False if server could not be reached or timeout occured
200 if connection was successfull
int or other HTML status codes as received from the server
"""
headerOptions = None
if token is not None:
headerOptions = {'X-Plex-Token': token}
if verifySSL is True:
verifySSL = None if settings('sslverify') == 'true' \
else False
if 'plex.tv' in url:
url = 'https://plex.tv/api/home/users'
else:
url = url + '/library/onDeck'
log.debug("Checking connection to server %s with verifySSL=%s"
% (url, verifySSL))
answer = DownloadUtils().downloadUrl(url,
authenticate=False,
headerOptions=headerOptions,
verifySSL=verifySSL)
if answer is None:
log.debug("Could not connect to %s" % url)
return False
try:
# xml received?
answer.attrib
except:
if answer is True:
# Maybe no xml but connection was successful nevertheless
answer = 200
else:
# Success - we downloaded an xml!
answer = 200
# We could connect but maybe were not authenticated. No worries
log.debug("Checking connection successfull. Answer: %s" % answer)
return answer
def get_plex_login_from_settings(): def get_plex_login_from_settings():
""" """
Returns a dict: Returns a dict:

View file

@ -15,7 +15,7 @@ log = getLogger("PLEX."+__name__)
############################################################################### ###############################################################################
def setup(self): def setup():
""" """
Initial setup. Run once upon startup. Initial setup. Run once upon startup.
@ -47,11 +47,13 @@ def setup(self):
# If a Plex server IP has already been set # If a Plex server IP has already been set
# return only if the right machine identifier is found # return only if the right machine identifier is found
if connectmanager.server: if connectmanager.server:
log.info("PMS is already set: %s. Checking now..." % self.server) log.info("PMS is already set: %s. Checking now..."
% connectmanager.server)
if connectmanager.check_pms(): if connectmanager.check_pms():
log.info("Using PMS %s with machineIdentifier %s" log.info("Using PMS %s with machineIdentifier %s"
% (self.server, self.serverid)) % (connectmanager.server, connectmanager.serverid))
connectmanager.write_pms_settings(self.server, self.pms_token) connectmanager.write_pms_settings(connectmanager.server,
connectmanager.pms_token)
return return
# If not already retrieved myplex info, optionally let user sign in # If not already retrieved myplex info, optionally let user sign in

View file

@ -14,10 +14,9 @@ from utils import window, settings, language as lang, thread_methods
import downloadutils import downloadutils
import PlexAPI import PlexAPI
from connectmanager import check_connection
from connect.plex_tv import get_user_artwork_url from connect.plex_tv import get_user_artwork_url
from PlexFunctions import GetMachineIdentifier from PlexFunctions import GetMachineIdentifier, check_connection
import state import state
############################################################################### ###############################################################################

View file

@ -151,7 +151,7 @@ class Service():
self.command_pipeline.start() self.command_pipeline.start()
# Server auto-detect # Server auto-detect
initialsetup.InitialSetup().setup() initialsetup.setup()
# Initialize important threads, handing over self for callback purposes # Initialize important threads, handing over self for callback purposes
self.user = UserClient(self) self.user = UserClient(self)