Fix some style issues and one bug where param was missing

This commit is contained in:
Claus Vium 2019-02-03 16:10:44 +01:00
parent 2d0d21aa2b
commit eefe7c6fd7
5 changed files with 264 additions and 273 deletions

View file

@ -2,20 +2,18 @@
################################################################################################# #################################################################################################
import json
import logging import logging
import Queue import Queue
import threading import threading
import os import os
from datetime import datetime
import xbmc import xbmc
import xbmcvfs import xbmcvfs
import xbmcaddon import xbmcaddon
import requests import requests
from helper.utils import should_stop, delete_folder from helper.utils import delete_folder
from helper import settings, stop, event, window, kodi_version, unzip, create_id from helper import settings, stop, event, window, unzip, create_id
from jellyfin import Jellyfin from jellyfin import Jellyfin
from jellyfin.core import api from jellyfin.core import api
from jellyfin.core.exceptions import HTTPException from jellyfin.core.exceptions import HTTPException
@ -28,6 +26,7 @@ CACHE = xbmc.translatePath(os.path.join(xbmcaddon.Addon(id='plugin.video.jellyfi
################################################################################################# #################################################################################################
def get_jellyfinserver_url(handler): def get_jellyfinserver_url(handler):
if handler.startswith('/'): if handler.startswith('/'):
@ -37,26 +36,32 @@ def get_jellyfinserver_url(handler):
return "{server}/emby/%s" % handler return "{server}/emby/%s" % handler
def browse_info(): def browse_info():
return ( return (
"DateCreated,EpisodeCount,SeasonCount,Path,Genres,Studios,Taglines,MediaStreams,Overview,Etag," "DateCreated,EpisodeCount,SeasonCount,Path,Genres,Studios,Taglines,MediaStreams,Overview,Etag,"
"ProductionLocations,Width,Height,RecursiveItemCount,ChildCount" "ProductionLocations,Width,Height,RecursiveItemCount,ChildCount"
) )
def _http(action, url, request={}, server_id=None): def _http(action, url, request={}, server_id=None):
request.update({'url': url, 'type': action}) request.update({'url': url, 'type': action})
return Jellyfin(server_id)['http/request'](request) return Jellyfin(server_id)['http/request'](request)
def _get(handler, params=None, server_id=None): def _get(handler, params=None, server_id=None):
return _http("GET", get_jellyfinserver_url(handler), {'params': params}, server_id) return http("GET", get_jellyfinserver_url(handler), {'params': params}, server_id)
def _post(handler, json=None, params=None, server_id=None): def _post(handler, json=None, params=None, server_id=None):
return _http("POST", get_jellyfinserver_url(handler), {'params': params, 'json': json}, server_id) return http("POST", get_jellyfinserver_url(handler), {'params': params, 'json': json}, server_id)
def _delete(handler, params=None, server_id=None): def _delete(handler, params=None, server_id=None):
return _http("DELETE", get_jellyfinserver_url(handler), {'params': params}, server_id) return _http("DELETE", get_jellyfinserver_url(handler), {'params': params}, server_id)
def validate_view(library_id, item_id): def validate_view(library_id, item_id):
''' This confirms a single item from the library matches the view it belongs to. ''' This confirms a single item from the library matches the view it belongs to.
@ -73,6 +78,7 @@ def validate_view(library_id, item_id):
return True if len(result['Items']) else False return True if len(result['Items']) else False
def get_single_item(parent_id, media): def get_single_item(parent_id, media):
return _get("Users/{UserId}/Items", { return _get("Users/{UserId}/Items", {
'ParentId': parent_id, 'ParentId': parent_id,
@ -81,6 +87,7 @@ def get_single_item(parent_id, media):
'IncludeItemTypes': media 'IncludeItemTypes': media
}) })
def get_filtered_section(parent_id=None, media=None, limit=None, recursive=None, sort=None, sort_order=None, def get_filtered_section(parent_id=None, media=None, limit=None, recursive=None, sort=None, sort_order=None,
filters=None, extra=None, server_id=None): filters=None, extra=None, server_id=None):
@ -99,9 +106,7 @@ def get_filtered_section(parent_id=None, media=None, limit=None, recursive=None,
'Fields': browse_info() 'Fields': browse_info()
} }
if filters: if filters:
if 'Boxsets' in filters: if 'Boxsets' in filters:
filters.remove('Boxsets') filters.remove('Boxsets')
params['CollapseBoxSetItems'] = settings('groupedSets.bool') params['CollapseBoxSetItems'] = settings('groupedSets.bool')
@ -118,11 +123,13 @@ def get_filtered_section(parent_id=None, media=None, limit=None, recursive=None,
return _get("Users/{UserId}/Items", params, server_id) return _get("Users/{UserId}/Items", params, server_id)
def get_movies_by_boxset(boxset_id): def get_movies_by_boxset(boxset_id):
for items in get_items(boxset_id, "Movie"): for items in get_items(boxset_id, "Movie"):
yield items yield items
def get_episode_by_show(show_id): def get_episode_by_show(show_id):
query = { query = {
@ -137,6 +144,7 @@ def get_episode_by_show(show_id):
for items in _get_items(query): for items in _get_items(query):
yield items yield items
def get_episode_by_season(show_id, season_id): def get_episode_by_season(show_id, season_id):
query = { query = {
@ -152,6 +160,7 @@ def get_episode_by_season(show_id, season_id):
for items in _get_items(query): for items in _get_items(query):
yield items yield items
def get_items(parent_id, item_type=None, basic=False, params=None): def get_items(parent_id, item_type=None, basic=False, params=None):
query = { query = {
@ -176,6 +185,7 @@ def get_items(parent_id, item_type=None, basic=False, params=None):
for items in _get_items(query): for items in _get_items(query):
yield items yield items
def get_artists(parent_id=None, basic=False, params=None, server_id=None): def get_artists(parent_id=None, basic=False, params=None, server_id=None):
query = { query = {
@ -201,6 +211,7 @@ def get_artists(parent_id=None, basic=False, params=None, server_id=None):
for items in _get_items(query, server_id): for items in _get_items(query, server_id):
yield items yield items
def get_albums_by_artist(artist_id, basic=False): def get_albums_by_artist(artist_id, basic=False):
params = { params = {
@ -210,6 +221,7 @@ def get_albums_by_artist(artist_id, basic=False):
for items in get_items(None, "MusicAlbum", basic, params): for items in get_items(None, "MusicAlbum", basic, params):
yield items yield items
def get_songs_by_artist(artist_id, basic=False): def get_songs_by_artist(artist_id, basic=False):
params = { params = {
@ -219,6 +231,7 @@ def get_songs_by_artist(artist_id, basic=False):
for items in get_items(None, "Audio", basic, params): for items in get_items(None, "Audio", basic, params):
yield items yield items
@stop() @stop()
def _get_items(query, server_id=None): def _get_items(query, server_id=None):
@ -263,6 +276,7 @@ def _get_items(query, server_id=None):
del items['Items'][:] del items['Items'][:]
index += LIMIT index += LIMIT
class GetItemWorker(threading.Thread): class GetItemWorker(threading.Thread):
is_done = False is_done = False
@ -275,10 +289,8 @@ class GetItemWorker(threading.Thread):
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
with requests.Session() as s: with requests.Session() as s:
while True: while True:
try: try:
item_ids = self.queue.get(timeout=1) item_ids = self.queue.get(timeout=1)
except Queue.Empty: except Queue.Empty:
@ -320,6 +332,7 @@ class GetItemWorker(threading.Thread):
if window('jellyfin_should_stop.bool'): if window('jellyfin_should_stop.bool'):
break break
class TheVoid(object): class TheVoid(object):
def __init__(self, method, data): def __init__(self, method, data):
@ -359,6 +372,7 @@ class TheVoid(object):
xbmc.sleep(100) xbmc.sleep(100)
LOG.info("--[ void/%s ]", self.data['VoidName']) LOG.info("--[ void/%s ]", self.data['VoidName'])
def get_objects(src, filename): def get_objects(src, filename):
''' Download objects dependency to temp cache folder. ''' Download objects dependency to temp cache folder.
@ -383,7 +397,7 @@ def get_objects(src, filename):
LOG.error(error) LOG.error(error)
response = requests.get(src, stream=True, verify=False) response = requests.get(src, stream=True, verify=False)
except Exception as error: except Exception:
raise raise
dl = xbmcvfs.File(path, 'w') dl = xbmcvfs.File(path, 'w')

View file

@ -2,8 +2,6 @@
################################################################################################## ##################################################################################################
import json
import datetime
import logging import logging
from . import settings from . import settings
@ -16,8 +14,6 @@ LOG = logging.getLogger("JELLYFIN."+__name__)
class API(object): class API(object):
def __init__(self, item, server=None): def __init__(self, item, server=None):
''' Get item information in special cases. ''' Get item information in special cases.
@ -161,7 +157,6 @@ class API(object):
def validate_studio(self, studio_name): def validate_studio(self, studio_name):
# Convert studio for Kodi to properly detect them # Convert studio for Kodi to properly detect them
studios = { studios = {
'abc (us)': "ABC", 'abc (us)': "ABC",
'fox (us)': "FOX", 'fox (us)': "FOX",
'mtv (us)': "MTV", 'mtv (us)': "MTV",

View file

@ -1,13 +1,12 @@
# -*- 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['auth.server'], handler)
def basic_info(): def basic_info():
return "Etag" return "Etag"
def info(): def info():
return ( return (
"Path,Genres,SortName,Studios,Writer,Taglines,LocalTrailerCount," "Path,Genres,SortName,Studios,Writer,Taglines,LocalTrailerCount,"
@ -18,6 +17,7 @@ def info():
"MediaSources,VoteCount,RecursiveItemCount,PrimaryImageAspectRatio" "MediaSources,VoteCount,RecursiveItemCount,PrimaryImageAspectRatio"
) )
def music_info(): def music_info():
return ( return (
"Etag,Genres,SortName,Studios,Writer," "Etag,Genres,SortName,Studios,Writer,"
@ -25,7 +25,6 @@ def music_info():
"AirTime,DateCreated,MediaStreams,People,ProviderIds,Overview,ItemCounts" "AirTime,DateCreated,MediaStreams,People,ProviderIds,Overview,ItemCounts"
) )
#################################################################################################
class API(object): class API(object):
@ -58,7 +57,6 @@ class API(object):
return self._get("System/Info/Public") return self._get("System/Info/Public")
def sessions(self, handler="", action="GET", params=None, json=None): def sessions(self, handler="", action="GET", params=None, json=None):
if action == "POST": if action == "POST":
return self._post("Sessions%s" % handler, json, params) return self._post("Sessions%s" % handler, json, params)
elif action == "DELETE": elif action == "DELETE":
@ -67,7 +65,6 @@ class API(object):
return self._get("Sessions%s" % handler, params) return self._get("Sessions%s" % handler, params)
def users(self, handler="", action="GET", params=None, json=None): def users(self, handler="", action="GET", params=None, json=None):
if action == "POST": if action == "POST":
return self._post("Users/{UserId}%s" % handler, json, params) return self._post("Users/{UserId}%s" % handler, json, params)
elif action == "DELETE": elif action == "DELETE":
@ -76,7 +73,6 @@ class API(object):
return self._get("Users/{UserId}%s" % handler, params) return self._get("Users/{UserId}%s" % handler, params)
def items(self, handler="", action="GET", params=None, json=None): def items(self, handler="", action="GET", params=None, json=None):
if action == "POST": if action == "POST":
return self._post("Items%s" % handler, json, params) return self._post("Items%s" % handler, json, params)
elif action == "DELETE": elif action == "DELETE":
@ -94,7 +90,6 @@ class API(object):
return self._get("Videos%s" % handler) return self._get("Videos%s" % handler)
def artwork(self, item_id, art, max_width, ext="jpg", index=None): def artwork(self, item_id, art, max_width, ext="jpg", index=None):
if index is None: if index is None:
return jellyfin_url(self.client, "Items/%s/Images/%s?MaxWidth=%s&format=%s" % (item_id, art, max_width, ext)) return jellyfin_url(self.client, "Items/%s/Images/%s?MaxWidth=%s&format=%s" % (item_id, art, max_width, ext))
@ -143,7 +138,7 @@ class API(object):
return self.items("/%s/Images" % item_id) return self.items("/%s/Images" % item_id)
def get_suggestion(self, media="Movie,Episode", limit=1): def get_suggestion(self, media="Movie,Episode", limit=1):
return self.users("/Suggestions", { return self.users("/Suggestions", params={
'Type': media, 'Type': media,
'Limit': limit 'Limit': limit
}) })

View file

@ -123,8 +123,7 @@ class Library(threading.Thread):
''' Open the databases to test if the file exists. ''' Open the databases to test if the file exists.
''' '''
with Database('video') as kodidb: with Database('video'), Database('music'):
with Database('music') as musicdb:
pass pass
@stop() @stop()
@ -611,11 +610,7 @@ class UpdatedWorker(threading.Thread):
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
with self.lock, self.database as kodidb, Database('jellyfin') as jellyfindb:
with self.lock:
with self.database as kodidb:
with Database('jellyfin') as jellyfindb:
while True: while True:
try: try:
@ -656,10 +651,7 @@ class UserDataWorker(threading.Thread):
def run(self): def run(self):
with self.lock: with self.lock, self.database as kodidb, Database('jellyfin') as jellyfindb:
with self.database as kodidb:
with Database('jellyfin') as jellyfindb:
while True: while True:
try: try:
@ -742,10 +734,7 @@ class RemovedWorker(threading.Thread):
def run(self): def run(self):
with self.lock: with self.lock, self.database as kodidb, Database('jellyfin') as jellyfindb:
with self.database as kodidb:
with Database('jellyfin') as jellyfindb:
while True: while True:
try: try:

View file

@ -165,7 +165,6 @@ class Artwork(object):
from database import Database from database import Database
with Database('texture') as texturedb: with Database('texture') as texturedb:
try: try:
texturedb.cursor.execute(QUTEX.get_cache, (url,)) texturedb.cursor.execute(QUTEX.get_cache, (url,))
cached = texturedb.cursor.fetchone()[0] cached = texturedb.cursor.fetchone()[0]
@ -195,7 +194,6 @@ class GetArtworkWorker(threading.Thread):
''' '''
with requests.Session() as s: with requests.Session() as s:
while True: while True:
try: try:
url = self.queue.get(timeout=2) url = self.queue.get(timeout=2)
except Queue.Empty: except Queue.Empty: