client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions

This commit is contained in:
TrueTechy 2019-09-07 04:14:32 +01:00
commit d9bb931fd8
10 changed files with 74 additions and 69 deletions

View file

@ -81,9 +81,9 @@ class Connect(object):
''' Get Jellyfin client. ''' Get Jellyfin client.
''' '''
client = Jellyfin(server_id) client = Jellyfin(server_id)
client['config/app']("Kodi", self.info['Version'], self.info['DeviceName'], self.info['DeviceId']) client.config.app("Kodi", self.info['Version'], self.info['DeviceName'], self.info['DeviceId'])
client['config']['http.user_agent'] = "Jellyfin-Kodi/%s" % self.info['Version'] client.config.data['http.user_agent'] = "Jellyfin-Kodi/%s" % self.info['Version']
client['config']['auth.ssl'] = self.get_ssl() client.config.data['auth.ssl'] = self.get_ssl()
return client return client
@ -94,7 +94,7 @@ class Connect(object):
self.connect_manager = client.auth self.connect_manager = client.auth
if server_id is None: if server_id is None:
client['config']['app.default'] = True client.config.data['app.default'] = True
try: try:
state = client.authenticate(credentials or {}, options or {}) state = client.authenticate(credentials or {}, options or {})
@ -107,8 +107,8 @@ class Connect(object):
client.callback = event client.callback = event
self.get_user(client) self.get_user(client)
settings('serverName', client['config/auth.server-name']) settings('serverName', client.config.data['auth.server-name'])
settings('server', client['config/auth.server']) settings('server', client.config.data['auth.server'])
event('ServerOnline', {'ServerId': server_id}) event('ServerOnline', {'ServerId': server_id})
event('LoadServer', {'ServerId': server_id}) event('LoadServer', {'ServerId': server_id})

View file

@ -45,11 +45,11 @@ class Jellyfin(object):
from jellyfin import Jellyfin from jellyfin import Jellyfin
Jellyfin('123456')['config/app'] Jellyfin('123456').config.data['app']
# Permanent client reference # Permanent client reference
client = Jellyfin('123456').get_client() client = Jellyfin('123456').get_client()
client['config/app'] client.config.data['app']
''' '''
# Borg - multiple instances, shared state # Borg - multiple instances, shared state

View file

@ -85,6 +85,7 @@ class JellyfinClient(object):
def __getitem__(self, key): def __getitem__(self, key):
LOG.debug("__getitem__(%r)", key) LOG.debug("__getitem__(%r)", key)
<<<<<<< HEAD
if key.startswith('config'): if key.startswith('config'):
return self.config[key.replace('config/', "", 1)] if "/" in key else self.config return self.config[key.replace('config/', "", 1)] if "/" in key else self.config
@ -92,6 +93,9 @@ class JellyfinClient(object):
return self.http.__shortcuts__(key.replace('http/', "", 1)) return self.http.__shortcuts__(key.replace('http/', "", 1))
elif key.startswith('websocket'): elif key.startswith('websocket'):
=======
if key.startswith('websocket'):
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
return self.wsc.__shortcuts__(key.replace('websocket/', "", 1)) return self.wsc.__shortcuts__(key.replace('websocket/', "", 1))
elif key.startswith('callback'): elif key.startswith('callback'):

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def jellyfin_url(client, handler): def jellyfin_url(client, handler):
return "%s/emby/%s" % (client.config['auth.server'], handler) return "%s/emby/%s" % (client.config.data['auth.server'], handler)
def basic_info(): def basic_info():

View file

@ -25,27 +25,6 @@ class Config(object):
self.data = {} self.data = {}
self.http() self.http()
def __shortcuts__(self, key):
LOG.debug("__shortcuts__(%r)", key)
if key == "auth":
return self.auth
elif key == "app":
return self.app
elif key == "http":
return self.http
elif key == "data":
return self
return
def __getitem__(self, key):
LOG.debug("__getitem__(%r)", key)
return self.data.get(key, self.__shortcuts__(key))
def __setitem__(self, key, value):
self.data[key] = value
def app(self, name, version, device_name, device_id, capabilities=None, device_pixel_ratio=None): def app(self, name, version, device_name, device_id, capabilities=None, device_pixel_ratio=None):
LOG.info("Begin app constructor.") LOG.info("Begin app constructor.")

View file

@ -117,7 +117,7 @@ class ConnectionManager(object):
self['server']['AccessToken'] = None self['server']['AccessToken'] = None
self.credentials.get_credentials(self.credentials.get_credentials()) self.credentials.get_credentials(self.credentials.get_credentials())
self.config['auth.token'] = None self.config.data['auth.token'] = None
def get_available_servers(self): def get_available_servers(self):
@ -261,7 +261,7 @@ class ConnectionManager(object):
raise raise
def _add_app_info(self): def _add_app_info(self):
return "%s/%s" % (self.config['app.name'], self.config['app.version']) return "%s/%s" % (self.config.data['app.name'], self.config.data['app.version'])
def _get_headers(self, request): def _get_headers(self, request):
@ -526,15 +526,15 @@ class ConnectionManager(object):
if options.get('enableAutoLogin') == False: if options.get('enableAutoLogin') == False:
self.config['auth.user_id'] = server.pop('UserId', None) self.config.data['auth.user_id'] = server.pop('UserId', None)
self.config['auth.token'] = server.pop('AccessToken', None) self.config.data['auth.token'] = server.pop('AccessToken', None)
elif verify_authentication and server.get('AccessToken'): elif verify_authentication and server.get('AccessToken'):
if self._validate_authentication(server, connection_mode, options) is not False: if self._validate_authentication(server, connection_mode, options) is not False:
self.config['auth.user_id'] = server['UserId'] self.config.data['auth.user_id'] = server['UserId']
self.config['auth.token'] = server['AccessToken'] self.config.data['auth.token'] = server['AccessToken']
return self._after_connect_validated(server, credentials, system_info, connection_mode, False, options) return self._after_connect_validated(server, credentials, system_info, connection_mode, False, options)
return self._resolve_failure() return self._resolve_failure()
@ -551,10 +551,10 @@ class ConnectionManager(object):
self.server_id = server['Id'] self.server_id = server['Id']
# Update configs # Update configs
self.config['auth.server'] = get_server_address(server, connection_mode) self.config.data['auth.server'] = get_server_address(server, connection_mode)
self.config['auth.server-name'] = server['Name'] self.config.data['auth.server-name'] = server['Name']
self.config['auth.server=id'] = server['Id'] self.config.data['auth.server=id'] = server['Id']
self.config['auth.ssl'] = options.get('ssl', self.config['auth.ssl']) self.config.data['auth.ssl'] = options.get('ssl', self.config.data['auth.ssl'])
result = { result = {
'Servers': [server] 'Servers': [server]
@ -602,8 +602,8 @@ class ConnectionManager(object):
credentials = self.credentials.get_credentials() credentials = self.credentials.get_credentials()
self.config['auth.user_id'] = result['User']['Id'] self.config.data['auth.user_id'] = result['User']['Id']
self.config['auth.token'] = result['AccessToken'] self.config.data['auth.token'] = result['AccessToken']
for server in credentials['Servers']: for server in credentials['Servers']:
if server['Id'] == result['ServerId']: if server['Id'] == result['ServerId']:

View file

@ -24,7 +24,7 @@ class HTTP(object):
def __init__(self, client): def __init__(self, client):
self.client = client self.client = client
self.config = client['config'] self.config = client.config
def __shortcuts__(self, key): def __shortcuts__(self, key):
LOG.debug("__shortcuts__(%r)", key) LOG.debug("__shortcuts__(%r)", key)
@ -38,7 +38,7 @@ class HTTP(object):
self.session = requests.Session() self.session = requests.Session()
max_retries = self.config['http.max_retries'] max_retries = self.config.data['http.max_retries']
self.session.mount("http://", requests.adapters.HTTPAdapter(max_retries=max_retries)) self.session.mount("http://", requests.adapters.HTTPAdapter(max_retries=max_retries))
self.session.mount("https://", requests.adapters.HTTPAdapter(max_retries=max_retries)) self.session.mount("https://", requests.adapters.HTTPAdapter(max_retries=max_retries))
@ -56,14 +56,14 @@ class HTTP(object):
def _replace_user_info(self, string): def _replace_user_info(self, string):
if '{server}' in string: if '{server}' in string:
if self.config['auth.server']: if self.config.data['auth.server']:
string = string.decode('utf-8').replace("{server}", self.config['auth.server']) string = string.decode('utf-8').replace("{server}", self.config.data['auth.server'])
else: else:
raise Exception("Server address not set.") raise Exception("Server address not set.")
if '{UserId}'in string: if '{UserId}'in string:
if self.config['auth.user_id']: if self.config.data['auth.user_id']:
string = string.decode('utf-8').replace("{UserId}", self.config['auth.user_id']) string = string.decode('utf-8').replace("{UserId}", self.config.data['auth.user_id'])
else: else:
raise Exception("UserId is not set.") raise Exception("UserId is not set.")
@ -108,7 +108,7 @@ class HTTP(object):
continue continue
LOG.error(error) LOG.error(error)
self.client['callback']("ServerUnreachable", {'ServerId': self.config['auth.server-id']}) self.client['callback']("ServerUnreachable", {'ServerId': self.config.data['auth.server-id']})
raise HTTPException("ServerUnreachable", error) raise HTTPException("ServerUnreachable", error)
@ -130,11 +130,11 @@ class HTTP(object):
if r.status_code == 401: if r.status_code == 401:
if 'X-Application-Error-Code' in r.headers: if 'X-Application-Error-Code' in r.headers:
self.client['callback']("AccessRestricted", {'ServerId': self.config['auth.server-id']}) self.client['callback']("AccessRestricted", {'ServerId': self.config.data['auth.server-id']})
raise HTTPException("AccessRestricted", error) raise HTTPException("AccessRestricted", error)
else: else:
self.client['callback']("Unauthorized", {'ServerId': self.config['auth.server-id']}) self.client['callback']("Unauthorized", {'ServerId': self.config.data['auth.server-id']})
self.client['auth/revoke-token'] self.client['auth/revoke-token']
raise HTTPException("Unauthorized", error) raise HTTPException("Unauthorized", error)
@ -155,14 +155,14 @@ class HTTP(object):
raise HTTPException(r.status_code, error) raise HTTPException(r.status_code, error)
except requests.exceptions.MissingSchema as error: except requests.exceptions.MissingSchema as error:
raise HTTPException("MissingSchema", {'Id': self.config['auth.server']}) raise HTTPException("MissingSchema", {'Id': self.config.data['auth.server']})
except Exception as error: except Exception as error:
raise raise
else: else:
try: try:
self.config['server-time'] = r.headers['Date'] self.config.data['server-time'] = r.headers['Date']
elapsed = int(r.elapsed.total_seconds() * 1000) elapsed = int(r.elapsed.total_seconds() * 1000)
response = r.json() response = r.json()
LOG.debug("---<[ http ][%s ms]", elapsed) LOG.debug("---<[ http ][%s ms]", elapsed)
@ -175,11 +175,11 @@ class HTTP(object):
def _request(self, data): def _request(self, data):
if 'url' not in data: if 'url' not in data:
data['url'] = "%s/emby/%s" % (self.config['auth.server'], data.pop('handler', "")) data['url'] = "%s/emby/%s" % (self.config.data['auth.server'], data.pop('handler', ""))
self._get_header(data) self._get_header(data)
data['timeout'] = data.get('timeout') or self.config['http.timeout'] data['timeout'] = data.get('timeout') or self.config.data['http.timeout']
data['verify'] = data.get('verify') or self.config['auth.ssl'] or False data['verify'] = data.get('verify') or self.config.data['auth.ssl'] or False
data['url'] = self._replace_user_info(data['url']) data['url'] = self._replace_user_info(data['url'])
self._process_params(data.get('params') or {}) self._process_params(data.get('params') or {})
self._process_params(data.get('json') or {}) self._process_params(data.get('json') or {})
@ -206,7 +206,7 @@ class HTTP(object):
'Content-type': "application/json", 'Content-type': "application/json",
'Accept-Charset': "UTF-8,*", 'Accept-Charset': "UTF-8,*",
'Accept-encoding': "gzip", 'Accept-encoding': "gzip",
'User-Agent': self.config['http.user_agent'] or "%s/%s" % (self.config['app.name'], self.config['app.version']) 'User-Agent': self.config.data['http.user_agent'] or "%s/%s" % (self.config.data['app.name'], self.config.data['app.version'])
}) })
if 'x-emby-authorization' not in data['headers']: if 'x-emby-authorization' not in data['headers']:
@ -217,17 +217,17 @@ class HTTP(object):
def _authorization(self, data): def _authorization(self, data):
auth = "MediaBrowser " auth = "MediaBrowser "
auth += "Client=%s, " % self.config['app.name'].encode('utf-8') auth += "Client=%s, " % self.config.data['app.name'].encode('utf-8')
auth += "Device=%s, " % self.config['app.device_name'].encode('utf-8') auth += "Device=%s, " % self.config.data['app.device_name'].encode('utf-8')
auth += "DeviceId=%s, " % self.config['app.device_id'].encode('utf-8') auth += "DeviceId=%s, " % self.config.data['app.device_id'].encode('utf-8')
auth += "Version=%s" % self.config['app.version'].encode('utf-8') auth += "Version=%s" % self.config.data['app.version'].encode('utf-8')
data['headers'].update({'x-emby-authorization': auth}) data['headers'].update({'x-emby-authorization': auth})
if self.config['auth.token'] and self.config['auth.user_id']: if self.config.data.get('auth.token') and self.config.data.get('auth.user_id'):
auth += ', UserId=%s' % self.config['auth.user_id'].encode('utf-8') auth += ', UserId=%s' % self.config.data['auth.user_id'].encode('utf-8')
data['headers'].update({'x-emby-authorization': auth, 'X-MediaBrowser-Token': self.config['auth.token'].encode('utf-8')}) data['headers'].update({'x-emby-authorization': auth, 'X-MediaBrowser-Token': self.config.data['auth.token'].encode('utf-8')})
return data return data

View file

@ -50,9 +50,9 @@ class WSClient(threading.Thread):
def run(self): def run(self):
monitor = xbmc.Monitor() monitor = xbmc.Monitor()
token = self.client['config/auth.token'] token = self.client.config.data['auth.token']
device_id = self.client['config/app.device_id'] device_id = self.client.config.data['app.device_id']
server = self.client['config/auth.server'] server = self.client.config.data['auth.server']
server = server.replace('https', "wss") if server.startswith('https') else server.replace('http', "ws") server = server.replace('https', "wss") if server.startswith('https') else server.replace('http', "ws")
wsc_url = "%s/embywebsocket?api_key=%s&device_id=%s" % (server, token, device_id) wsc_url = "%s/embywebsocket?api_key=%s&device_id=%s" % (server, token, device_id)
@ -88,7 +88,7 @@ class WSClient(threading.Thread):
return return
if not self.client['config/app.default']: if not self.client.config.data['app.default']:
data['ServerId'] = self.client['auth/server-id'] data['ServerId'] = self.client['auth/server-id']
self.client['callback_ws'](message['MessageType'], data) self.client['callback_ws'](message['MessageType'], data)

View file

@ -456,7 +456,7 @@ class Library(threading.Thread):
def save_last_sync(self): def save_last_sync(self):
try: try:
time_now = datetime.strptime(self.server['config/server-time'].split(', ', 1)[1], '%d %b %Y %H:%M:%S GMT') - timedelta(minutes=2) time_now = datetime.strptime(self.server.config.data['server-time'].split(', ', 1)[1], '%d %b %Y %H:%M:%S GMT') - timedelta(minutes=2)
except Exception as error: except Exception as error:
LOG.exception(error) LOG.exception(error)

View file

@ -235,7 +235,11 @@ class Monitor(xbmc.Monitor):
elif method == 'PlayPlaylist': elif method == 'PlayPlaylist':
<<<<<<< HEAD
server['api'].post_session(server['config/app.session'], "Playing", { server['api'].post_session(server['config/app.session'], "Playing", {
=======
server.jellyfin.post_session(server.config.data['app.session'], "Playing", {
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
'PlayCommand': "PlayNow", 'PlayCommand': "PlayNow",
'ItemIds': data['Id'], 'ItemIds': data['Id'],
'StartPositionTicks': 0 'StartPositionTicks': 0
@ -262,7 +266,11 @@ class Monitor(xbmc.Monitor):
self.server_instance(data['ServerId']) self.server_instance(data['ServerId'])
elif method == 'AddUser': elif method == 'AddUser':
<<<<<<< HEAD
server['api'].session_add_user(server['config/app.session'], data['Id'], data['Add']) server['api'].session_add_user(server['config/app.session'], data['Id'], data['Add'])
=======
server.jellyfin.session_add_user(server.config.data['app.session'], data['Id'], data['Add'])
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
self.additional_users(server) self.additional_users(server)
elif method == 'Player.OnPlay': elif method == 'Player.OnPlay':
@ -292,7 +300,11 @@ class Monitor(xbmc.Monitor):
for user in all_users: for user in all_users:
if user['Name'].lower() in additional.decode('utf-8').lower(): if user['Name'].lower() in additional.decode('utf-8').lower():
<<<<<<< HEAD
server['api'].session_add_user(server['config/app.session'], user['Id'], True) server['api'].session_add_user(server['config/app.session'], user['Id'], True)
=======
server.jellyfin.session_add_user(server.config.data['app.session'], user['Id'], True)
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
self.additional_users(server) self.additional_users(server)
@ -316,8 +328,13 @@ class Monitor(xbmc.Monitor):
'IconUrl': "https://raw.githubusercontent.com/jellyfin/jellyfin-kodi/master/kodi_icon.png", 'IconUrl': "https://raw.githubusercontent.com/jellyfin/jellyfin-kodi/master/kodi_icon.png",
}) })
<<<<<<< HEAD
session = server['api'].get_device(self.device_id) session = server['api'].get_device(self.device_id)
server['config']['app.session'] = session[0]['Id'] server['config']['app.session'] = session[0]['Id']
=======
session = server.jellyfin.get_device(self.device_id)
server.config.data['app.session'] = session[0]['Id']
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
def additional_users(self, server): def additional_users(self, server):
@ -335,8 +352,13 @@ class Monitor(xbmc.Monitor):
for index, user in enumerate(session[0]['AdditionalUsers']): for index, user in enumerate(session[0]['AdditionalUsers']):
<<<<<<< HEAD
info = server['api'].get_user(user['UserId']) info = server['api'].get_user(user['UserId'])
image = api.API(info, server['config/auth.server']).get_user_artwork(user['UserId']) image = api.API(info, server['config/auth.server']).get_user_artwork(user['UserId'])
=======
info = server.jellyfin.get_user(user['UserId'])
image = api.API(info, server.config.data['auth.server']).get_user_artwork(user['UserId'])
>>>>>>> 66679ce... client.py - remove "config" & configuration.py - removed shortcuts and get/set item functions
window('JellyfinAdditionalUserImage.%s' % index, image) window('JellyfinAdditionalUserImage.%s' % index, image)
window('JellyfinAdditionalUserPosition.%s' % user['UserId'], str(index)) window('JellyfinAdditionalUserPosition.%s' % user['UserId'], str(index))