This commit is contained in:
angelblue05 2016-09-27 01:33:09 -05:00 committed by GitHub
parent 38182fcc37
commit 04d4865074
6 changed files with 78 additions and 120 deletions

View file

@ -154,10 +154,10 @@ class ConnectManager(object):
dialog.doModal() dialog.doModal()
if dialog.is_user_selected(): if dialog.is_user_selected():
user = dialog.get_user() user = dialog.get_user()
username = user['Name'] username = user['Name']
if user['HasPassword']: if user['HasPassword']:
log.debug("User has password, present manual login") log.debug("User has password, present manual login")
try: try:

View file

@ -122,12 +122,13 @@ class ContextMenu(object):
options.append(OPTIONS['Addon']) options.append(OPTIONS['Addon'])
addon = xbmcaddon.Addon('plugin.video.emby') addon = xbmcaddon.Addon('plugin.video.emby')
XML_PATH = (addon.getAddonInfo('path'), "default", "1080i") xml_path = (addon.getAddonInfo('path'), "default", "1080i")
dialog = context.ContextMenu("script-emby-context.xml", *XML_PATH) context_menu = context.ContextMenu("script-emby-context.xml", *xml_path)
dialog.set_options(options) context_menu.set_options(options)
dialog.doModal() context_menu.doModal()
if dialog.is_selected():
self._selected_option = dialog.get_selected() if context_menu.is_selected():
self._selected_option = context_menu.get_selected()
return self._selected_option return self._selected_option

View file

@ -8,7 +8,7 @@ import os
import xbmcgui import xbmcgui
import xbmcaddon import xbmcaddon
from utils import window, language as lang from utils import window
################################################################################################## ##################################################################################################

View file

@ -43,14 +43,16 @@ class DownloadUtils(object):
self.client_info = clientinfo.ClientInfo() self.client_info = clientinfo.ClientInfo()
def _set_session(self, **kwargs): def set_session(self, **kwargs):
# Reserved for userclient only # Reserved for userclient only
info = {} info = {}
for key in kwargs: for key in kwargs:
info[key] = kwargs[key] info[key] = kwargs[key]
self.session.update(info) self.session.update(info)
log.info("Set info for server %s: %s", self.session['ServerId'], self.session) window('emby_server.json', value=json.dumps(self.session))
log.debug("Set info for server %s: %s", self.session['ServerId'], self.session)
def add_server(self, server, ssl): def add_server(self, server, ssl):
# Reserved for userclient only # Reserved for userclient only
@ -155,20 +157,19 @@ class DownloadUtils(object):
) )
self.downloadUrl(url, postBody={}, action_type="POST") self.downloadUrl(url, postBody={}, action_type="POST")
def start_session(self): def start_session(self):
# User is identified from this point # User is identified from this point
# Attach authenticated header to the session # Attach authenticated header to the session
# Start session # Start session
s = requests.Session() session = requests.Session()
s.headers = self.get_header() session.headers = self.get_header()
s.verify = self.session['SSL'] session.verify = self.session['SSL']
# Retry connections to the server # Retry connections to the server
s.mount("http://", requests.adapters.HTTPAdapter(max_retries=1)) session.mount("http://", requests.adapters.HTTPAdapter(max_retries=1))
s.mount("https://", requests.adapters.HTTPAdapter(max_retries=1)) session.mount("https://", requests.adapters.HTTPAdapter(max_retries=1))
self.session_requests = s self.session_requests = session
log.info("Requests session started on: %s" % self.session['Server']) log.info("requests session started on: %s", self.session['Server'])
def stop_session(self): def stop_session(self):
try: try:
@ -185,7 +186,7 @@ class DownloadUtils(object):
if authenticate: if authenticate:
user = self.get_user(server_id) user = self._get_session_info(server_id)
user_id = user['UserId'] user_id = user['UserId']
token = user['Token'] token = user['Token']
@ -211,20 +212,6 @@ class DownloadUtils(object):
}) })
return header return header
def get_user(self, server_id=None):
if server_id is None:
return {
'UserId': self.session['UserId'],
'Token': self.session['Token']
}
else:
server = self.servers[server_id]
return {
'UserId': server['UserId'],
'Token': server['Token']
}
def downloadUrl(self, url, postBody=None, action_type="GET", parameters=None, def downloadUrl(self, url, postBody=None, action_type="GET", parameters=None,
authenticate=True, server_id=None): authenticate=True, server_id=None):
@ -234,30 +221,22 @@ class DownloadUtils(object):
kwargs = {} kwargs = {}
default_link = "" default_link = ""
try: # Ensure server info is loaded try:
if not self._ensure_server(server_id): # Ensure server info is loaded
raise AttributeError("unable to load server information: %s" % server_id) self._ensure_server(server_id)
server = self.session if server_id is None else self.servers[server_id]
if server_id is None: if server_id is None and self.session_requests is not None: # Main server
if self.session_requests is not None: session = self.session_requests
session = self.session_requests
else:
kwargs.update({
'verify': self.session['SSL'],
'headers': self.get_header(authenticate=authenticate)
})
# Replace for the real values
url = url.replace("{server}", self.session['Server'])
url = url.replace("{UserId}", self.session['UserId'])
else: else:
server = self.servers[server_id]
kwargs.update({ kwargs.update({
'verify': server['SSL'], 'verify': server['SSL'],
'headers': self.get_header(server_id, authenticate) 'headers': self.get_header(server_id, authenticate)
}) })
# Replace for the real values
url = url.replace("{server}", server['Server']) # Replace for the real values
url = url.replace("{UserId}", server['UserId']) url = url.replace("{server}", server['Server'])
url = url.replace("{UserId}", server['UserId'])
##### PREPARE REQUEST ##### ##### PREPARE REQUEST #####
kwargs.update({ kwargs.update({
@ -285,7 +264,7 @@ class DownloadUtils(object):
log.debug("Response: %s" % r) log.debug("Response: %s" % r)
return r return r
except: except Exception:
if r.headers.get('content-type') != "text/html": if r.headers.get('content-type') != "text/html":
log.info("Unable to convert the response for: %s" % url) log.info("Unable to convert the response for: %s" % url)
@ -301,10 +280,10 @@ class DownloadUtils(object):
log.error("Server unreachable at: %s" % url) log.error("Server unreachable at: %s" % url)
window('emby_online', value="false") window('emby_online', value="false")
except requests.exceptions.ConnectTimeout as e: except requests.exceptions.ConnectTimeout as error:
log.error("Server timeout at: %s" % url) log.error("Server timeout at: %s", url)
except requests.exceptions.HTTPError as e: except requests.exceptions.HTTPError as error:
if r.status_code == 401: if r.status_code == 401:
# Unauthorized # Unauthorized
@ -331,28 +310,18 @@ class DownloadUtils(object):
elif status not in ("401", "Auth"): elif status not in ("401", "Auth"):
# Tell userclient token has been revoked. # Tell userclient token has been revoked.
window('emby_serverStatus', value="401") window('emby_serverStatus', value="401")
log.error("HTTP Error: %s" % e) log.error("HTTP Error: %s", error)
xbmcgui.Dialog().notification( xbmcgui.Dialog().notification(
heading="Error connecting", heading="Error connecting",
message="Unauthorized.", message="Unauthorized.",
icon=xbmcgui.NOTIFICATION_ERROR) icon=xbmcgui.NOTIFICATION_ERROR)
raise Warning('401') raise Warning('401')
elif r.status_code in (301, 302): except requests.exceptions.SSLError as error:
# Redirects log.error("invalid SSL certificate for: %s", url)
pass
elif r.status_code == 400:
# Bad requests
pass
except requests.exceptions.SSLError as e: except requests.exceptions.RequestException as error:
log.error("Invalid SSL certificate for: %s" % url) log.error("unknown error connecting to: %s" % url)
except requests.exceptions.RequestException as e:
log.error("Unknown error connecting to: %s" % url)
except AttributeError as error:
log.error(error)
return default_link return default_link
@ -360,51 +329,39 @@ class DownloadUtils(object):
def _ensure_server(self, server_id=None): def _ensure_server(self, server_id=None):
if server_id is None and self.session_requests is None: if server_id is None and self.session_requests is None:
if not self.session:
server = self._get_session_info() server = self._get_session_info()
self.session.update(server) self.session = server
elif server_id and server_id not in self.servers: elif server_id and server_id not in self.servers:
if server_id not in self.servers:
server = self._get_session_info(server_id) server = self._get_session_info(server_id)
if server is None: self.servers[server_id] = server
return False
self.servers[server_id] = server
return True return True
@classmethod @classmethod
def _get_session_info(cls, server_id=None): def _get_session_info(cls, server_id=None):
info = {} info = {
'UserId': "",
'Server': "",
'Token': "",
'SSL': False
}
if server_id is None: # Main server if server_id is None: # Main server
server = window('emby_server.json')
user_id = window('emby_currUser')
info.update({
'UserId': user_id,
'Server': window('emby_server%s' % user_id),
'Token': window('emby_accessToken%s' % user_id)
})
verifyssl = False
# If user enables ssl verification
if settings('sslverify') == "true":
verifyssl = True
if settings('sslcert') != "None":
verifyssl = settings('sslcert')
info['SSL'] = verifyssl
else: # Other connect servers else: # Other connect servers
server = window('emby_server%s.json' % server_id) server = window('emby_server%s.json' % server_id)
if server:
info.update(json.loads(server)) if server:
info.update(json.loads(server))
return info return info
@classmethod @classmethod
def _requests(cls, action, session=requests, **kwargs): def _requests(cls, action, session, **kwargs):
if action == "GET": if action == "GET":
response = session.get(**kwargs) response = session.get(**kwargs)
@ -413,4 +370,4 @@ class DownloadUtils(object):
elif action == "DELETE": elif action == "DELETE":
response = session.delete(**kwargs) response = session.delete(**kwargs)
return response return response

View file

@ -112,12 +112,12 @@ class UserClient(threading.Thread):
except Warning as error: except Warning as error:
if self._has_access and "restricted" in error: if self._has_access and "restricted" in error:
self._has_access = False self._has_access = False
log.info("Access is restricted") log.info("access is restricted")
else: else:
if not self._has_access: if not self._has_access:
self._has_access = True self._has_access = True
window('emby_serverStatus', clear=True) window('emby_serverStatus', clear=True)
log.info("Access is granted") log.info("access is granted")
xbmcgui.Dialog().notification(lang(29999), lang(33007)) xbmcgui.Dialog().notification(lang(29999), lang(33007))
@classmethod @classmethod
@ -200,10 +200,21 @@ class UserClient(threading.Thread):
token = self.get_token() token = self.get_token()
# Set properties # Set properties
# TODO: Remove old reference once code converted
window('emby_currUser', value=userid) window('emby_currUser', value=userid)
window('emby_server%s' % userid, value=server) window('emby_server%s' % userid, value=server)
window('emby_accessToken%s' % userid, value=token) window('emby_accessToken%s' % userid, value=token)
server_json = {
'UserId': userid,
'Server': server,
'ServerId': settings('serverId'),
'Token': token,
'SSL': self.get_ssl()
}
# Set downloadutils.py values
doutils.set_session(**server_json)
# Test the validity of the current token # Test the validity of the current token
if not authenticated: if not authenticated:
try: try:
@ -213,18 +224,7 @@ class UserClient(threading.Thread):
# Token is not longer valid # Token is not longer valid
raise raise
# Set downloadutils.py values try: # verify user access
session = {
'UserId': userid,
'Server': server,
'ServerId': settings('serverId'),
'Token': token,
'SSL': self.get_ssl()
}
doutils._set_session(**session)
# verify user access
try:
self._set_access() self._set_access()
except Warning: # We don't need to raise any exceptions except Warning: # We don't need to raise any exceptions
pass pass
@ -238,7 +238,7 @@ class UserClient(threading.Thread):
# Set connect servers # Set connect servers
if not settings('connectUsername'): if not settings('connectUsername'):
return return
servers = self.connectmanager.get_connect_servers() servers = self.connectmanager.get_connect_servers()
added_servers = [] added_servers = []
for server in servers: for server in servers:
@ -246,7 +246,7 @@ class UserClient(threading.Thread):
# TODO: SSL setup # TODO: SSL setup
self.doutils.add_server(server, False) self.doutils.add_server(server, False)
added_servers.append(server['Id']) added_servers.append(server['Id'])
# Set properties # Set properties
log.info(added_servers) log.info(added_servers)
window('emby_servers', value=json.dumps(added_servers)) window('emby_servers', value=json.dumps(added_servers))
@ -275,7 +275,7 @@ class UserClient(threading.Thread):
monitor = xbmc.Monitor() monitor = xbmc.Monitor()
log.warn("----===## Starting UserClient ##===----") log.warn("----====# Starting UserClient #====----")
while not self._stop_thread: while not self._stop_thread:
@ -318,7 +318,7 @@ class UserClient(threading.Thread):
break break
self.doutils.stop_session() self.doutils.stop_session()
log.warn("##===---- UserClient Stopped ----===##") log.warn("#====---- UserClient Stopped ----====#")
def stop_client(self): def stop_client(self):
self._stop_thread = True self._stop_thread = True

View file

@ -328,7 +328,7 @@ class WebSocketClient(threading.Thread):
if window('emby_online') == "true": if window('emby_online') == "true":
self._client.run_forever(ping_interval=10) self._client.run_forever(ping_interval=10)
if self._stop_websocket: if self._stop_websocket:
break break