Merge pull request #104 from oddstr13/pr-flake8-1

Most flake8 warnings corrected
This commit is contained in:
mcarlton00 2019-10-04 16:39:02 -04:00 committed by GitHub
commit 739c7efb45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
65 changed files with 1377 additions and 1359 deletions

View file

@ -18,7 +18,7 @@ sys.path.insert(0, __base__)
#################################################################################################
from entrypoint import Context
from entrypoint import Context # noqa: F402
#################################################################################################

View file

@ -18,7 +18,7 @@ sys.path.insert(0, __base__)
#################################################################################################
from entrypoint import Context
from entrypoint import Context # noqa: F402
#################################################################################################

View file

@ -18,7 +18,7 @@ sys.path.insert(0, __base__)
#################################################################################################
from entrypoint import Events
from entrypoint import Events # noqa: F402
#################################################################################################

View file

@ -2,7 +2,6 @@
#################################################################################################
import json
import logging
import os
@ -15,19 +14,22 @@ from helper.utils import create_id
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
def get_addon_name():
''' Used for logging.
'''
return xbmcaddon.Addon(addon_id()).getAddonInfo('name').upper()
def get_version():
return xbmcaddon.Addon(addon_id()).getAddonInfo('version')
def get_platform():
if xbmc.getCondVisibility('system.platform.osx'):
@ -53,6 +55,7 @@ def get_platform():
else:
return "Unknown"
def get_device_name():
''' Detect the device name. If deviceNameOpt, then
@ -68,6 +71,7 @@ def get_device_name():
return device_name
def get_device_id(reset=False):
''' Return the device_id if already loaded.
@ -105,6 +109,7 @@ def get_device_id(reset=False):
return client_id
def reset_device_id():
window('jellyfin_deviceId', clear=True)
@ -112,6 +117,7 @@ def reset_device_id():
dialog("ok", heading="{jellyfin}", line1=_(33033))
xbmc.executebuiltin('RestartApp')
def get_info():
return {
'DeviceName': get_device_name(),

View file

@ -2,25 +2,22 @@
##################################################################################################
import json
import logging
import os
import xbmc
import xbmcaddon
import xbmcvfs
import client
from database import get_credentials, save_credentials
from dialogs import ServerConnect, UsersConnect, LoginManual, ServerManual
from helper import _, settings, addon_id, event, api, dialog, window
from helper import settings, addon_id, event, api, window
from jellyfin import Jellyfin
from jellyfin.core.connection_manager import get_server_address, CONNECTION_STATE
from jellyfin.core.connection_manager import CONNECTION_STATE
from jellyfin.core.exceptions import HTTPException
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
XML_PATH = (xbmcaddon.Addon(addon_id()).getAddonInfo('path'), "default", "1080i")
##################################################################################################
@ -115,8 +112,7 @@ class Connect(object):
return state['Credentials']
elif (server_selection or state['State'] == CONNECTION_STATE['ServerSelection'] or
state['State'] == CONNECTION_STATE['Unavailable'] and not settings('SyncInstallRunDone.bool')):
elif (server_selection or state['State'] == CONNECTION_STATE['ServerSelection'] or state['State'] == CONNECTION_STATE['Unavailable'] and not settings('SyncInstallRunDone.bool')):
self.select_servers(state)
@ -143,7 +139,6 @@ class Connect(object):
return client.get_credentials()
def get_user(self, client):
''' Save user info.
@ -178,7 +173,8 @@ class Connect(object):
LOG.debug("Adding manual server")
try:
self.manual_server()
except RuntimeError: pass
except RuntimeError:
pass
else:
raise RuntimeError("No server selected")
@ -237,14 +233,16 @@ class Connect(object):
LOG.debug("User has password, present manual login")
try:
return self.login_manual(username)
except RuntimeError: pass
except RuntimeError:
pass
else:
return self.connect_manager.login(server, username)
elif dialog.is_manual_login():
try:
return self.login_manual()
except RuntimeError: pass
except RuntimeError:
pass
else:
raise RuntimeError("No user selected")
@ -294,4 +292,3 @@ class Connect(object):
save_credentials(credentials)
LOG.info("[ remove server ] %s", server_id)

View file

@ -18,7 +18,7 @@ from objects import obj
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -105,8 +105,7 @@ class Database(object):
for file in reversed(files):
if (file.startswith(database) and not file.endswith('-wal') and
not file.endswith('-shm') and not file.endswith('db-journal')):
if (file.startswith(database) and not file.endswith('-wal') and not file.endswith('-shm') and not file.endswith('db-journal')):
st = xbmcvfs.Stat(databases + file.decode('utf-8'))
modified_int = st.st_mtime()
@ -184,6 +183,7 @@ class Database(object):
self.cursor.close()
self.conn.close()
def jellyfin_tables(cursor):
''' Create the tables for the jellyfin database.
@ -205,6 +205,7 @@ def jellyfin_tables(cursor):
LOG.info("Add missing column jellyfin_parent_id")
cursor.execute("ALTER TABLE jellyfin ADD COLUMN jellyfin_parent_id 'TEXT'")
def reset():
''' Reset both the jellyfin database and the kodi database.
@ -257,6 +258,7 @@ def reset():
dialog("ok", heading="{jellyfin}", line1=_(33088))
xbmc.executebuiltin('RestartApp')
def reset_kodi():
with Database() as videodb:
@ -281,6 +283,7 @@ def reset_kodi():
LOG.info("[ reset kodi ]")
def reset_jellyfin():
with Database('jellyfin') as jellyfindb:
@ -298,6 +301,7 @@ def reset_jellyfin():
LOG.info("[ reset jellyfin ]")
def reset_artwork():
''' Remove all existing texture.
@ -325,6 +329,7 @@ def reset_artwork():
LOG.info("[ reset artwork ]")
def get_sync():
path = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/").decode('utf-8')
@ -345,6 +350,7 @@ def get_sync():
return sync
def save_sync(sync):
path = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/").decode('utf-8')
@ -358,6 +364,7 @@ def save_sync(sync):
data = json.dumps(sync, sort_keys=True, indent=4, ensure_ascii=False)
outfile.write(unicode(data))
def get_credentials():
path = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/").decode('utf-8')
@ -383,6 +390,7 @@ def get_credentials():
return credentials
def save_credentials(credentials):
credentials = credentials or {}
path = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/").decode('utf-8')
@ -396,6 +404,7 @@ def save_credentials(credentials):
except Exception as e:
LOG.error("Failed to save credentials: {}".format(e))
def get_item(kodi_id, media):
''' Get jellyfin item based on kodi id and media.
@ -409,4 +418,3 @@ def get_item(kodi_id, media):
return
return item

View file

@ -8,7 +8,7 @@ import queries as QU
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################

View file

@ -1,182 +1,169 @@
get_item = """ SELECT kodi_id, kodi_fileid, kodi_pathid, parent_id, media_type,
get_item = """
SELECT kodi_id, kodi_fileid, kodi_pathid, parent_id, media_type,
jellyfin_type, media_folder, jellyfin_parent_id
FROM jellyfin
WHERE jellyfin_id = ?
"""
get_item_obj = [ "{Id}"
]
get_item_series_obj = [ "{SeriesId}"
]
get_item_song_obj = [ "{SongAlbumId}"
]
get_item_id_by_parent = """ SELECT jellyfin_id, kodi_id
FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
get_item_id_by_parent_boxset_obj = [ "{SetId}","movie"
]
get_item_by_parent = """ SELECT jellyfin_id, kodi_id, kodi_fileid
FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
get_item_by_media_folder = """ SELECT jellyfin_id, jellyfin_type
FROM jellyfin
WHERE media_folder = ?
"""
get_item_by_parent_movie_obj = [ "{KodiId}","movie"
]
get_item_by_parent_tvshow_obj = [ "{ParentId}","tvshow"
]
get_item_by_parent_season_obj = [ "{ParentId}","season"
]
get_item_by_parent_episode_obj = [ "{ParentId}","episode"
]
get_item_by_parent_album_obj = [ "{ParentId}","album"
]
get_item_by_parent_song_obj = [ "{ParentId}","song"
]
get_item_by_wild = """ SELECT kodi_id, media_type
FROM jellyfin
WHERE jellyfin_id LIKE ?
"""
get_item_by_wild_obj = [ "{Id}"
]
get_item_by_kodi = """ SELECT jellyfin_id, parent_id, media_folder, jellyfin_type, checksum
FROM jellyfin
WHERE kodi_id = ?
AND media_type = ?
"""
get_checksum = """ SELECT jellyfin_id, checksum
FROM jellyfin
WHERE jellyfin_type = ?
"""
get_view_name = """ SELECT view_name
FROM view
WHERE view_id = ?
"""
get_media_by_id = """ SELECT jellyfin_type
FROM jellyfin
WHERE jellyfin_id = ?
"""
get_media_by_parent_id = """ SELECT jellyfin_id, jellyfin_type, kodi_id, kodi_fileid
FROM jellyfin
WHERE jellyfin_parent_id = ?
"""
get_view = """ SELECT view_name, media_type
FROM view
WHERE view_id = ?
"""
get_views = """ SELECT *
FROM view
"""
get_views_by_media = """ SELECT *
FROM view
WHERE media_type = ?
"""
get_items_by_media = """ SELECT jellyfin_id
FROM jellyfin
WHERE media_type = ?
"""
get_version = """ SELECT idVersion
FROM version
"""
FROM jellyfin
WHERE jellyfin_id = ?
"""
get_item_obj = ["{Id}"]
get_item_series_obj = ["{SeriesId}"]
get_item_song_obj = ["{SongAlbumId}"]
get_item_id_by_parent = """
SELECT jellyfin_id, kodi_id
FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
get_item_id_by_parent_boxset_obj = ["{SetId}", "movie"]
get_item_by_parent = """
SELECT jellyfin_id, kodi_id, kodi_fileid
FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
get_item_by_media_folder = """
SELECT jellyfin_id, jellyfin_type
FROM jellyfin
WHERE media_folder = ?
"""
get_item_by_parent_movie_obj = ["{KodiId}", "movie"]
get_item_by_parent_tvshow_obj = ["{ParentId}", "tvshow"]
get_item_by_parent_season_obj = ["{ParentId}", "season"]
get_item_by_parent_episode_obj = ["{ParentId}", "episode"]
get_item_by_parent_album_obj = ["{ParentId}", "album"]
get_item_by_parent_song_obj = ["{ParentId}", "song"]
get_item_by_wild = """
SELECT kodi_id, media_type
FROM jellyfin
WHERE jellyfin_id LIKE ?
"""
get_item_by_wild_obj = ["{Id}"]
get_item_by_kodi = """
SELECT jellyfin_id, parent_id, media_folder, jellyfin_type, checksum
FROM jellyfin
WHERE kodi_id = ?
AND media_type = ?
"""
get_checksum = """
SELECT jellyfin_id, checksum
FROM jellyfin
WHERE jellyfin_type = ?
"""
get_view_name = """
SELECT view_name
FROM view
WHERE view_id = ?
"""
get_media_by_id = """
SELECT jellyfin_type
FROM jellyfin
WHERE jellyfin_id = ?
"""
get_media_by_parent_id = """
SELECT jellyfin_id, jellyfin_type, kodi_id, kodi_fileid
FROM jellyfin
WHERE jellyfin_parent_id = ?
"""
get_view = """
SELECT view_name, media_type
FROM view
WHERE view_id = ?
"""
get_views = """
SELECT *
FROM view
"""
get_views_by_media = """
SELECT *
FROM view
WHERE media_type = ?
"""
get_items_by_media = """
SELECT jellyfin_id
FROM jellyfin
WHERE media_type = ?
"""
get_version = """
SELECT idVersion
FROM version
"""
add_reference = """ INSERT OR REPLACE INTO jellyfin(jellyfin_id, kodi_id, kodi_fileid, kodi_pathid, jellyfin_type,
add_reference = """
INSERT OR REPLACE INTO jellyfin(jellyfin_id, kodi_id, kodi_fileid, kodi_pathid, jellyfin_type,
media_type, parent_id, checksum, media_folder, jellyfin_parent_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_reference_movie_obj = [ "{Id}","{MovieId}","{FileId}","{PathId}","Movie","movie", None,"{Checksum}","{LibraryId}",
"{JellyfinParentId}"
]
add_reference_boxset_obj = [ "{Id}","{SetId}",None,None,"BoxSet","set",None,"{Checksum}",None,None
]
add_reference_tvshow_obj = [ "{Id}","{ShowId}",None,"{PathId}","Series","tvshow",None,"{Checksum}","{LibraryId}",
"{JellyfinParentId}"
]
add_reference_season_obj = [ "{Id}","{SeasonId}",None,None,"Season","season","{ShowId}",None,None,None
]
add_reference_pool_obj = [ "{SeriesId}","{ShowId}",None,"{PathId}","Series","tvshow",None,"{Checksum}","{LibraryId}",None
]
add_reference_episode_obj = [ "{Id}","{EpisodeId}","{FileId}","{PathId}","Episode","episode","{SeasonId}","{Checksum}",
None,"{JellyfinParentId}"
]
add_reference_mvideo_obj = [ "{Id}","{MvideoId}","{FileId}","{PathId}","MusicVideo","musicvideo",None,"{Checksum}",
"{LibraryId}","{JellyfinParentId}"
]
add_reference_artist_obj = [ "{Id}","{ArtistId}",None,None,"{ArtistType}","artist",None,"{Checksum}","{LibraryId}",
"{JellyfinParentId}"
]
add_reference_album_obj = [ "{Id}","{AlbumId}",None,None,"MusicAlbum","album",None,"{Checksum}",None,"{JellyfinParentId}"
]
add_reference_song_obj = [ "{Id}","{SongId}",None,"{PathId}","Audio","song","{AlbumId}","{Checksum}",
None,"{JellyfinParentId}"
]
add_view = """ INSERT OR REPLACE INTO view(view_id, view_name, media_type)
VALUES (?, ?, ?)
"""
add_version = """ INSERT OR REPLACE INTO version(idVersion)
VALUES (?)
"""
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_reference_movie_obj = ["{Id}", "{MovieId}", "{FileId}", "{PathId}", "Movie", "movie", None, "{Checksum}", "{LibraryId}", "{JellyfinParentId}"]
add_reference_boxset_obj = ["{Id}", "{SetId}", None, None, "BoxSet", "set", None, "{Checksum}", None, None]
add_reference_tvshow_obj = ["{Id}", "{ShowId}", None, "{PathId}", "Series", "tvshow", None, "{Checksum}", "{LibraryId}", "{JellyfinParentId}"]
add_reference_season_obj = ["{Id}", "{SeasonId}", None, None, "Season", "season", "{ShowId}", None, None, None]
add_reference_pool_obj = ["{SeriesId}", "{ShowId}", None, "{PathId}", "Series", "tvshow", None, "{Checksum}", "{LibraryId}", None]
add_reference_episode_obj = ["{Id}", "{EpisodeId}", "{FileId}", "{PathId}", "Episode", "episode", "{SeasonId}", "{Checksum}", None, "{JellyfinParentId}"]
add_reference_mvideo_obj = ["{Id}", "{MvideoId}", "{FileId}", "{PathId}", "MusicVideo", "musicvideo", None, "{Checksum}", "{LibraryId}", "{JellyfinParentId}"]
add_reference_artist_obj = ["{Id}", "{ArtistId}", None, None, "{ArtistType}", "artist", None, "{Checksum}", "{LibraryId}", "{JellyfinParentId}"]
add_reference_album_obj = ["{Id}", "{AlbumId}", None, None, "MusicAlbum", "album", None, "{Checksum}", None, "{JellyfinParentId}"]
add_reference_song_obj = ["{Id}", "{SongId}", None, "{PathId}", "Audio", "song", "{AlbumId}", "{Checksum}", None, "{JellyfinParentId}"]
add_view = """
INSERT OR REPLACE INTO view(view_id, view_name, media_type)
VALUES (?, ?, ?)
"""
add_version = """
INSERT OR REPLACE INTO version(idVersion)
VALUES (?)
"""
update_reference = """ UPDATE jellyfin
SET checksum = ?
WHERE jellyfin_id = ?
"""
update_reference_obj = [ "{Checksum}", "{Id}"
]
update_parent = """ UPDATE jellyfin
SET parent_id = ?
WHERE jellyfin_id = ?
"""
update_parent_movie_obj = [ "{SetId}","{Id}"
]
update_parent_episode_obj = [ "{SeasonId}","{Id}"
]
update_parent_album_obj = [ "{ArtistId}","{AlbumId}"]
update_reference = """
UPDATE jellyfin
SET checksum = ?
WHERE jellyfin_id = ?
"""
update_reference_obj = ["{Checksum}", "{Id}"]
update_parent = """
UPDATE jellyfin
SET parent_id = ?
WHERE jellyfin_id = ?
"""
update_parent_movie_obj = ["{SetId}", "{Id}"]
update_parent_episode_obj = ["{SeasonId}", "{Id}"]
update_parent_album_obj = ["{ArtistId}", "{AlbumId}"]
delete_item = """ DELETE FROM jellyfin
WHERE jellyfin_id = ?
"""
delete_item_obj = [ "{Id}"
]
delete_item_by_parent = """ DELETE FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
delete_item_by_parent_tvshow_obj = [ "{ParentId}","tvshow"
]
delete_item_by_parent_season_obj = [ "{ParentId}","season"
]
delete_item_by_parent_episode_obj = [ "{ParentId}","episode"
]
delete_item_by_parent_song_obj = [ "{ParentId}","song"
]
delete_item_by_parent_artist_obj = [ "{ParentId}","artist"
]
delete_item_by_parent_album_obj = [ "{KodiId}","album"
]
delete_item_by_kodi = """ DELETE FROM jellyfin
WHERE kodi_id = ?
AND media_type = ?
"""
delete_item_by_wild = """ DELETE FROM jellyfin
WHERE jellyfin_id LIKE ?
"""
delete_view = """ DELETE FROM view
WHERE view_id = ?
"""
delete_parent_boxset_obj = [ None, "{Movie}"
]
delete_media_by_parent_id = """ DELETE FROM jellyfin
WHERE jellyfin_parent_id = ?
"""
delete_version = """ DELETE FROM version
"""
delete_item = """
DELETE FROM jellyfin
WHERE jellyfin_id = ?
"""
delete_item_obj = ["{Id}"]
delete_item_by_parent = """
DELETE FROM jellyfin
WHERE parent_id = ?
AND media_type = ?
"""
delete_item_by_parent_tvshow_obj = ["{ParentId}", "tvshow"]
delete_item_by_parent_season_obj = ["{ParentId}", "season"]
delete_item_by_parent_episode_obj = ["{ParentId}", "episode"]
delete_item_by_parent_song_obj = ["{ParentId}", "song"]
delete_item_by_parent_artist_obj = ["{ParentId}", "artist"]
delete_item_by_parent_album_obj = ["{KodiId}", "album"]
delete_item_by_kodi = """
DELETE FROM jellyfin
WHERE kodi_id = ?
AND media_type = ?
"""
delete_item_by_wild = """
DELETE FROM jellyfin
WHERE jellyfin_id LIKE ?
"""
delete_view = """
DELETE FROM view
WHERE view_id = ?
"""
delete_parent_boxset_obj = [None, "{Movie}"]
delete_media_by_parent_id = """
DELETE FROM jellyfin
WHERE jellyfin_parent_id = ?
"""
delete_version = """
DELETE FROM version
"""

View file

@ -12,7 +12,7 @@ from helper import window, addon_id
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92
@ -29,7 +29,6 @@ class ContextMenu(xbmcgui.WindowXMLDialog):
_options = []
selected_option = None
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
@ -48,7 +47,6 @@ class ContextMenu(xbmcgui.WindowXMLDialog):
if window('JellyfinUserImage'):
self.getControl(USER_IMAGE).setImage(window('JellyfinUserImage'))
height = 479 + (len(self._options) * 55)
LOG.info("options: %s", self._options)
self.list_ = self.getControl(LIST)

View file

@ -12,7 +12,7 @@ from helper import _, addon_id
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92
@ -31,7 +31,6 @@ class LoginManual(xbmcgui.WindowXMLDialog):
error = None
username = None
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
@ -118,7 +117,6 @@ class LoginManual(xbmcgui.WindowXMLDialog):
def _login(self, username, password):
mode = self.connect_manager.get_server_info(self.connect_manager.server_id)['LastConnectionMode']
server_data = self.connect_manager.get_server_info(self.connect_manager.server_id)
server = self.connect_manager.get_server_address(server_data, server_data['LastConnectionMode'])
result = self.connect_manager.login(server, username, password)

View file

@ -6,11 +6,10 @@ import logging
import xbmc
import xbmcgui
import xbmcaddon
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92

View file

@ -12,7 +12,7 @@ from jellyfin.core.connection_manager import CONNECTION_STATE
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92
@ -38,7 +38,6 @@ class ServerConnect(xbmcgui.WindowXMLDialog):
_connect_login = False
_manual_server = False
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)

View file

@ -13,7 +13,7 @@ from jellyfin.core.connection_manager import CONNECTION_STATE
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92
@ -34,7 +34,6 @@ class ServerManual(xbmcgui.WindowXMLDialog):
_server = None
error = None
def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)

View file

@ -9,7 +9,7 @@ import xbmcgui
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_BACK = 92
@ -27,7 +27,6 @@ class UsersConnect(xbmcgui.WindowXMLDialog):
_user = None
_manual_login = False
def __init__(self, *args, **kwargs):
self.kodi_version = int(xbmc.getInfoLabel('System.BuildVersion')[:2])

View file

@ -15,7 +15,7 @@ from jellyfin.core.exceptions import HTTPException
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
LIMIT = min(int(settings('limitIndex') or 50), 50)
#################################################################################################
@ -42,6 +42,7 @@ def _http(action, url, request={}, server_id=None):
request.update({'url': url, 'type': action})
return Jellyfin(server_id).http.request(request)
def _get(handler, params=None, server_id=None):
return _http("GET", get_jellyfinserver_url(handler), {'params': params}, server_id)

View file

@ -10,6 +10,10 @@ import xbmcvfs
from helper import loghandler
from jellyfin import Jellyfin
from .default import Events
from .service import Service
from .context import Context
#################################################################################################
Jellyfin.set_loghandler(loghandler.LogHandler, logging.DEBUG)
@ -18,7 +22,3 @@ loghandler.config()
LOG = logging.getLogger('JELLYFIN.entrypoint')
#################################################################################################
from default import Events
from service import Service
from context import Context

View file

@ -13,11 +13,10 @@ import database
from dialogs import context
from helper import _, settings, dialog
from downloader import TheVoid
from objects import Actions
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
XML_PATH = (xbmcaddon.Addon('plugin.video.jellyfin').getAddonInfo('path'), "default", "1080i")
OPTIONS = {
'Refresh': _(30410),

View file

@ -8,7 +8,6 @@ import sys
import urlparse
import urllib
import os
import sys
import xbmc
import xbmcvfs
@ -24,14 +23,13 @@ from helper import _, event, settings, window, dialog, api, JSONRPC
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
class Events(object):
def __init__(self):
''' Parse the parameters. Reroute to our service.py
@ -65,7 +63,7 @@ class Events(object):
jellyfin_id = params.get('id')
get_video_extras(jellyfin_id, jellyfin_path, server)
elif mode =='play':
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')
@ -180,7 +178,6 @@ def listing():
else:
directory(server['Name'], "plugin://plugin.video.jellyfin/?mode=browse&server=%s" % server['Id'], context=context)
directory(_(33194), "plugin://plugin.video.jellyfin/?mode=managelibs", True)
directory(_(33134), "plugin://plugin.video.jellyfin/?mode=addserver", False)
directory(_(33054), "plugin://plugin.video.jellyfin/?mode=adduser", False)
@ -194,6 +191,7 @@ def listing():
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)*]
@ -207,6 +205,7 @@ def directory(label, path, folder=True, artwork=None, fanart=None, context=None)
return li
def dir_listitem(label, path, artwork=None, fanart=None):
''' Gets the icon paths for default node listings
@ -218,6 +217,7 @@ def dir_listitem(label, path, artwork=None, fanart=None):
return li
def manage_libraries():
directory(_(33098), "plugin://plugin.video.jellyfin/?mode=refreshboxsets", False)
@ -230,6 +230,7 @@ def manage_libraries():
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.
@ -274,7 +275,6 @@ def browse(media, view_id=None, folder=None, server_id=None):
elif media == 'music':
content_type = "artists"
if folder == 'recentlyadded':
listing = TheVoid('RecentlyAdded', {'Id': view_id, 'ServerId': server_id}).get()
elif folder == 'genres':
@ -316,7 +316,6 @@ def browse(media, view_id=None, folder=None, server_id=None):
else:
listing = TheVoid('Browse', {'Id': folder or view_id, 'ServerId': server_id, 'Recursive': False}).get()
if listing:
actions = Actions(server_id)
@ -396,6 +395,7 @@ def browse(media, view_id=None, folder=None, server_id=None):
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 jellyfin views.
@ -421,6 +421,7 @@ def browse_subfolders(media, view_id, server_id=None):
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.
@ -445,6 +446,7 @@ def browse_letters(media, view_id, server_id=None):
xbmcplugin.setContent(int(sys.argv[1]), 'files')
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def get_folder_type(item, content_type=None):
media = item['Type']
@ -480,6 +482,7 @@ def get_media_type(media):
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.
@ -524,6 +527,7 @@ def get_fanart(item_id, path, server_id=None):
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
@ -565,6 +569,7 @@ def get_video_extras(item_id, path, server_id=None):
#xbmcplugin.endOfDirectory(int(sys.argv[1]))
"""
def get_next_episodes(item_id, limit):
''' Only for synced content.
@ -645,6 +650,7 @@ def get_next_episodes(item_id, limit):
xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def create_listitem(item):
''' Listitem based on jsonrpc items.
@ -656,7 +662,7 @@ def create_listitem(item):
metadata = {
'Title': title,
'duration': str(item['runtime']/60),
'duration': str(item['runtime'] / 60),
'Plot': item['plot'],
'Playcount': item['playcount']
}
@ -688,7 +694,7 @@ def create_listitem(item):
metadata['Premiered'] = item['firstaired']
if "rating" in item:
metadata['Rating'] = str(round(float(item['rating']),1))
metadata['Rating'] = str(round(float(item['rating']), 1))
if "director" in item:
metadata['Director'] = " / ".join(item['director'])
@ -711,10 +717,10 @@ def create_listitem(item):
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.setThumbnailImage(item['art'].get('thumb', ''))
li.setIconImage('DefaultTVShows.png')
li.setProperty('dbid', str(item['episodeid']))
li.setProperty('fanart_image', item['art'].get('tvshow.fanart',''))
li.setProperty('fanart_image', item['art'].get('tvshow.fanart', ''))
for key, value in item['streamdetails'].iteritems():
for stream in value:
@ -722,6 +728,7 @@ def create_listitem(item):
return li
def add_user():
''' Add or remove users from the default server session.
@ -756,6 +763,7 @@ def add_user():
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.
@ -786,7 +794,6 @@ def get_themes():
all_views = jellyfin_db.JellyfinDatabase(jellyfindb.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()
@ -829,6 +836,7 @@ def get_themes():
dialog("notification", heading="{jellyfin}", message=_(33153), icon="{jellyfin}", time=1000, sound=False)
def delete_item():
''' Delete keymap action.
@ -837,6 +845,7 @@ def delete_item():
context.Context(delete=True)
def backup():
''' Jellyfin backup.

View file

@ -2,12 +2,13 @@
#################################################################################################
import _strptime # Workaround for threads using datetime: _striptime is locked
import json
import logging
import sys
from datetime import datetime
# Workaround for threads using datetime: _striptime is locked
import _strptime # noqa:F401
import xbmc
import xbmcgui
@ -24,7 +25,7 @@ from database import Database, jellyfin_db, reset
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -38,7 +39,6 @@ class Service(xbmc.Monitor):
warn = True
settings = {'last_progress': datetime.today(), 'last_progress_report': datetime.today()}
def __init__(self):
window('jellyfin_should_stop', clear=True)
@ -352,7 +352,7 @@ class Service(xbmc.Monitor):
return
LOG.info("--<[ sleep ]")
xbmc.sleep(10000)# Allow network to wake up
xbmc.sleep(10000) # Allow network to wake up
self.monitor.sleep = False
window('jellyfin_should_stop', clear=True)

View file

@ -3,23 +3,19 @@
##################################################################################################
import datetime
import json
import logging
import os
import xbmc
import xbmcvfs
import downloader as server
import helper.xmls as xmls
from database import Database, get_sync, save_sync, jellyfin_db
from helper import _, settings, window, progress, dialog, LibraryException
from helper.utils import get_screensaver, set_screensaver
from views import Views
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -36,7 +32,6 @@ class FullSync(object):
running = False
screensaver = None
def __init__(self, library, server):
''' You can call all big syncing methods here.
@ -69,7 +64,6 @@ class FullSync(object):
return self
def libraries(self, library_id=None, update=False):
''' Map the syncing process and start the sync. Ensure only one sync is running.
@ -179,7 +173,6 @@ class FullSync(object):
return [libraries[x - 1] for x in selection]
def start(self):
''' Main sync process.
@ -278,7 +271,7 @@ class FullSync(object):
for index, movie in enumerate(items['Items']):
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount']))*100),
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount'])) * 100),
heading="%s: %s" % (_('addon_name'), library['Name']),
message=movie['Name'])
obj.movie(movie, library=library)
@ -318,11 +311,11 @@ class FullSync(object):
for index, show in enumerate(items['Items']):
percent = int((float(start_index + index) / float(items['TotalRecordCount']))*100)
percent = int((float(start_index + index) / float(items['TotalRecordCount'])) * 100)
message = show['Name']
dialog.update(percent, heading="%s: %s" % (_('addon_name'), library['Name']), message=message)
if obj.tvshow(show, library=library) != False:
if obj.tvshow(show, library=library) is not False:
for episodes in server.get_episode_by_show(show['Id']):
for episode in episodes['Items']:
@ -368,7 +361,7 @@ class FullSync(object):
for index, mvideo in enumerate(items['Items']):
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount']))*100),
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount'])) * 100),
heading="%s: %s" % (_('addon_name'), library['Name']),
message=mvideo['Name'])
obj.musicvideo(mvideo, library=library)
@ -408,7 +401,7 @@ class FullSync(object):
for index, artist in enumerate(items['Items']):
percent = int((float(start_index + index) / float(items['TotalRecordCount']))*100)
percent = int((float(start_index + index) / float(items['TotalRecordCount'])) * 100)
message = artist['Name']
dialog.update(percent, heading="%s: %s" % (_('addon_name'), library['Name']), message=message)
obj.artist(artist, library=library)
@ -431,7 +424,6 @@ class FullSync(object):
dialog.update(percent, message="%s/%s" % (message, song['Name']))
obj.song(song)
if self.update_library:
self.music_compare(library, obj, jellyfindb)
@ -470,7 +462,7 @@ class FullSync(object):
for index, boxset in enumerate(items['Items']):
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount']))*100),
dialog.update(int((float(start_index + index) / float(items['TotalRecordCount'])) * 100),
heading="%s: %s" % (_('addon_name'), _('boxsets')),
message=boxset['Name'])
obj.boxset(boxset)
@ -524,7 +516,7 @@ class FullSync(object):
for item in movies:
obj(item[0])
dialog.update(int((float(count) / float(len(items))*100)), heading="%s: %s" % (_('addon_name'), library[0]))
dialog.update(int((float(count) / float(len(items)) * 100)), heading="%s: %s" % (_('addon_name'), library[0]))
count += 1
obj = TVShows(self.server, jellyfindb, kodidb, direct_path).remove
@ -532,7 +524,7 @@ class FullSync(object):
for item in tvshows:
obj(item[0])
dialog.update(int((float(count) / float(len(items))*100)), heading="%s: %s" % (_('addon_name'), library[0]))
dialog.update(int((float(count) / float(len(items)) * 100)), heading="%s: %s" % (_('addon_name'), library[0]))
count += 1
else:
# from mcarlton: I'm not sure what triggers this.
@ -547,7 +539,7 @@ class FullSync(object):
for item in items:
obj(item[0])
dialog.update(int((float(count) / float(len(items))*100)), heading="%s: %s" % (_('addon_name'), library[0]))
dialog.update(int((float(count) / float(len(items)) * 100)), heading="%s: %s" % (_('addon_name'), library[0]))
count += 1
self.sync = get_sync()
@ -560,7 +552,6 @@ class FullSync(object):
save_sync(self.sync)
def __exit__(self, exc_type, exc_val, exc_tb):
''' Exiting sync

View file

@ -8,7 +8,7 @@ from . import settings
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################

View file

@ -2,9 +2,8 @@
#################################################################################################
class LibraryException(Exception):
# Jellyfin library sync exception
def __init__(self, status):
self.status = status

View file

@ -2,25 +2,24 @@
#################################################################################################
import json
import logging
import os
from uuid import uuid4
import collections
import xbmc
import xbmcvfs
import api
import database
import client
import collections
import requests
from . import _, settings, window, dialog
from downloader import TheVoid
from . import _, settings, window, dialog
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -52,8 +51,8 @@ def set_properties(item, method, server_id=None):
window('jellyfin_play.json', current)
class PlayUtils(object):
class PlayUtils(object):
def __init__(self, item, force_transcode=False, server_id=None, server=None, token=None):
@ -236,7 +235,7 @@ class PlayUtils(object):
def transcode(self, source, audio=None, subtitle=None):
if not 'TranscodingUrl' in source:
if 'TranscodingUrl' not in source:
raise Exception("use get_sources to get transcoding url")
self.info['Method'] = "Transcode"
@ -275,13 +274,19 @@ class PlayUtils(object):
self.info['Method'] = "DirectStream"
if self.item['Type'] == "Audio":
self.info['Path'] = ("%s/emby/Audio/%s/stream.%s?static=true&api_key=%s" %
(self.info['ServerAddress'], self.item['Id'],
self.info['Path'] = "%s/emby/Audio/%s/stream.%s?static=true&api_key=%s" % (
self.info['ServerAddress'],
self.item['Id'],
source.get('Container', "mp4").split(',')[0],
self.info['Token']))
self.info['Token']
)
else:
self.info['Path'] = ("%s/emby/Videos/%s/stream?static=true&MediaSourceId=%s&api_key=%s" %
(self.info['ServerAddress'], self.item['Id'], source['Id'], self.info['Token']))
self.info['Path'] = "%s/emby/Videos/%s/stream?static=true&MediaSourceId=%s&api_key=%s" % (
self.info['ServerAddress'],
self.item['Id'],
source['Id'],
self.info['Token']
)
return self.info['Path']
@ -495,7 +500,6 @@ class PlayUtils(object):
listitem.setSubtitles(subs)
self.item['PlaybackInfo']['Subtitles'] = mapping
@classmethod
def download_external_subs(cls, src, filename):
@ -628,7 +632,13 @@ class PlayUtils(object):
if stream['IsTextSubtitleStream'] and 'DeliveryUrl' in stream and stream['DeliveryUrl'].lower().startswith('/videos'):
url = "%s/emby%s" % (self.info['ServerAddress'], stream['DeliveryUrl'])
else:
url = ("%s/emby/Videos/%s/%s/Subtitles/%s/Stream.%s?api_key=%s" %
(self.info['ServerAddress'], self.item['Id'], source['Id'], index, stream['Codec'], self.info['Token']))
url = "%s/emby/Videos/%s/%s/Subtitles/%s/Stream.%s?api_key=%s" % (
self.info['ServerAddress'],
self.item['Id'],
source['Id'],
index,
stream['Codec'],
self.info['Token']
)
return url

View file

@ -2,19 +2,18 @@
##################################################################################################
import json
import logging
import os
import xbmc
import xbmcaddon
##################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
##################################################################################################
def _(string):
''' Get add-on string. Returns in unicode.

View file

@ -12,26 +12,30 @@ import urllib
from uuid import uuid4
from distutils.version import LooseVersion
from dateutil import tz, parser
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
from . import _
from dateutil import tz, parser
from .translate import _
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
def addon_id():
return "plugin.video.jellyfin"
def kodi_version():
return xbmc.getInfoLabel('System.BuildVersion')[:2]
def window(key, value=None, clear=False, window_id=10000):
''' Get or set window properties.
@ -65,6 +69,7 @@ def window(key, value=None, clear=False, window_id=10000):
return result
def settings(setting, value=None):
''' Get or add add-on settings.
@ -87,9 +92,11 @@ def settings(setting, value=None):
return result
def create_id():
return uuid4()
def compare_version(a, b):
''' -1 a is smaller
@ -107,6 +114,7 @@ def compare_version(a, b):
return 0
def find(dict, item):
''' Find value in dictionary.
@ -114,11 +122,12 @@ def find(dict, item):
if item in dict:
return dict[item]
for key,value in sorted(dict.iteritems(), key=lambda (k,v): (v,k)):
for key, value in sorted(dict.iteritems(), key=lambda (k, v): (v, k)):
if re.match(key, item, re.I):
return dict[key]
def event(method, data=None, sender=None, hexlify=False):
''' Data is a dictionary.
@ -134,13 +143,16 @@ def event(method, data=None, sender=None, hexlify=False):
xbmc.executebuiltin('NotifyAll(%s, %s, %s)' % (sender, method, data))
LOG.debug("---[ event: %s/%s ] %s", sender, method, data)
def dialog(dialog_type, *args, **kwargs):
d = xbmcgui.Dialog()
if "icon" in kwargs:
kwargs['icon'] = kwargs['icon'].replace("{jellyfin}",
"special://home/addons/plugin.video.jellyfin/resources/icon.png")
kwargs['icon'] = kwargs['icon'].replace(
"{jellyfin}",
"special://home/addons/plugin.video.jellyfin/resources/icon.png"
)
if "heading" in kwargs:
kwargs['heading'] = kwargs['heading'].replace("{jellyfin}", _('addon_name'))
@ -155,6 +167,7 @@ def dialog(dialog_type, *args, **kwargs):
}
return types[dialog_type](*args, **kwargs)
def should_stop():
''' Checkpoint during the sync process.
@ -171,6 +184,7 @@ def should_stop():
return False
def get_screensaver():
''' Get the current screensaver value.
@ -181,6 +195,7 @@ def get_screensaver():
except KeyError:
return ""
def set_screensaver(value):
''' Toggle the screensaver
@ -192,6 +207,7 @@ def set_screensaver(value):
result = JSONRPC('Settings.setSettingValue').execute(params)
LOG.info("---[ screensaver/%s ] %s", value, result)
class JSONRPC(object):
version = 1
@ -221,6 +237,7 @@ class JSONRPC(object):
self.params = params
return json.loads(xbmc.executeJSONRPC(self._query()))
def validate(path):
''' Verify if path is accessible.
@ -241,6 +258,7 @@ def validate(path):
return True
def values(item, keys):
''' Grab the values in the item for a list of keys {key},{key1}....
@ -248,6 +266,7 @@ def values(item, keys):
'''
return (item[key.replace('{', "").replace('}', "")] if type(key) == str and key.startswith('{') else key for key in keys)
def indent(elem, level=0):
''' Prettify xml docs.
@ -270,6 +289,7 @@ def indent(elem, level=0):
LOG.exception(error)
return
def write_xml(content, file):
with open(file, 'w') as infile:
@ -332,6 +352,7 @@ def unzip(path, dest, folder=None):
LOG.info("Unzipped %s", path)
def unzip_recursive(path, dirs, dest):
for directory in dirs:
@ -348,6 +369,7 @@ def unzip_recursive(path, dirs, dest):
for file in files:
unzip_file(os.path.join(dirs_dir, file.decode('utf-8')), os.path.join(dest_dir, file.decode('utf-8')))
def unzip_file(path, dest):
''' Unzip specific file. Path should start with zip://
@ -355,6 +377,7 @@ def unzip_file(path, dest):
xbmcvfs.copy(path, dest)
LOG.debug("unzip: %s to %s", path, dest)
def get_zip_directory(path, folder):
dirs, files = xbmcvfs.listdir(path)
@ -367,6 +390,7 @@ def get_zip_directory(path, folder):
if result:
return result
def copytree(path, dest):
''' Copy folder content from one to another.
@ -384,6 +408,7 @@ def copytree(path, dest):
LOG.info("Copied %s", path)
def copy_recursive(path, dirs, dest):
for directory in dirs:
@ -400,6 +425,7 @@ def copy_recursive(path, dirs, dest):
for file in files:
copy_file(os.path.join(dirs_dir, file.decode('utf-8')), os.path.join(dest_dir, file.decode('utf-8')))
def copy_file(path, dest):
''' Copy specific file.
@ -410,6 +436,7 @@ def copy_file(path, dest):
xbmcvfs.copy(path, dest)
LOG.debug("copy: %s to %s", path, dest)
def normalize_string(text):
''' For theme media, do not modify unless modified in TV Tunes.
@ -431,11 +458,13 @@ def normalize_string(text):
return text
def split_list(itemlist, size):
''' Split up list in pieces of size. Will generate a list of lists
'''
return [itemlist[i:i+size] for i in range(0, len(itemlist), size)]
return [itemlist[i:i + size] for i in range(0, len(itemlist), size)]
def convert_to_local(date):

View file

@ -6,15 +6,17 @@ import logging
import xbmcgui
from . import _, LibraryException
from utils import should_stop
from .utils import should_stop
from .exceptions import LibraryException
from .translate import _
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
def progress(message=None):
''' Will start and close the progress dialog.
@ -61,6 +63,7 @@ def catch(errors=(Exception,)):
return wrapper
return decorator
def silent_catch(errors=(Exception,)):
''' Wrapper to catch exceptions and ignore them
@ -76,6 +79,7 @@ def silent_catch(errors=(Exception,)):
return wrapper
return decorator
def stop(default=None):
''' Wrapper to catch exceptions and return using catch
@ -100,6 +104,7 @@ def stop(default=None):
return wrapper
return decorator
def jellyfin_item():
''' Wrapper to retrieve the jellyfin_db item.
@ -113,6 +118,7 @@ def jellyfin_item():
return wrapper
return decorator
def library_check():
''' Wrapper to retrieve the library

View file

@ -2,7 +2,6 @@
#################################################################################################
import json
import logging
import os
import xml.etree.ElementTree as etree
@ -13,10 +12,11 @@ from . import _, indent, write_xml, dialog, settings
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
def sources():
''' Create master lock compatible sources.
@ -77,6 +77,7 @@ def sources():
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), file)
def tvtunes_nfo(path, urls):
''' Create tvtunes.nfo
@ -96,6 +97,7 @@ def tvtunes_nfo(path, urls):
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), path)
def advanced_settings():
''' Track the existence of <cleanonupdate>true</cleanonupdate>

View file

@ -9,21 +9,25 @@ from helpers import has_attribute
#################################################################################################
class NullHandler(logging.Handler):
def emit(self, record):
print(self.format(record))
loghandler = NullHandler
LOG = logging.getLogger('Jellyfin')
#################################################################################################
def config(level=logging.INFO):
logger = logging.getLogger('Jellyfin')
logger.addHandler(Jellyfin.loghandler())
logger.setLevel(level)
def ensure_client():
def decorator(func):

View file

@ -12,10 +12,11 @@ from core.connection_manager import ConnectionManager, CONNECTION_STATE
#################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
#################################################################################################
def callback(message, data):
''' Callback function should received message, data

View file

@ -1 +0,0 @@

View file

@ -12,7 +12,7 @@ import logging
DEFAULT_HTTP_MAX_RETRIES = 3
DEFAULT_HTTP_TIMEOUT = 30
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
#################################################################################################

View file

@ -12,11 +12,11 @@ from distutils.version import LooseVersion
import urllib3
from credentials import Credentials
from http import HTTP
from http import HTTP # noqa: I201,I100
#################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
CONNECTION_STATE = {
'Unavailable': 0,
'ServerSelection': 1,
@ -31,6 +31,7 @@ CONNECTION_MODE = {
#################################################################################################
def get_server_address(server, mode):
modes = {
@ -178,7 +179,7 @@ class ConnectionManager(object):
LOG.info("beginning connection tests")
return self._test_next_connection_mode(tests, 0, server, options)
def get_server_address(self, server, mode): #TODO: De-duplicated (Duplicated from above when getting rid of shortcuts)
def get_server_address(self, server, mode): # TODO: De-duplicated (Duplicated from above when getting rid of shortcuts)
modes = {
CONNECTION_MODE['Local']: server.get('LocalAddress'),
@ -239,8 +240,10 @@ class ConnectionManager(object):
request.pop('dataType')
headers['X-Application'] = self._add_app_info()
headers['Content-type'] = request.get('contentType',
'application/x-www-form-urlencoded; charset=UTF-8')
headers['Content-type'] = request.get(
'contentType',
'application/x-www-form-urlencoded; charset=UTF-8'
)
def _connect_to_servers(self, servers, options):
@ -446,7 +449,7 @@ class ConnectionManager(object):
'Id': found_server['Id'],
'LocalAddress': server or found_server['Address'],
'Name': found_server['Name']
} #TODO
} # TODO
info['LastConnectionMode'] = CONNECTION_MODE['Manual'] if info.get('ManualAddress') else CONNECTION_MODE['Local']
servers.append(info)
@ -461,7 +464,7 @@ class ConnectionManager(object):
# Determine the port, if any
parts = info['Address'].split(':')
if len(parts) > 1:
port_string = parts[len(parts)-1]
port_string = parts[len(parts) - 1]
try:
address += ":%s" % int(port_string)
@ -496,7 +499,7 @@ class ConnectionManager(object):
def _after_connect_validated(self, server, credentials, system_info, connection_mode, verify_authentication, options):
if options.get('enableAutoLogin') == False:
if options.get('enableAutoLogin') is False:
self.config.data['auth.user_id'] = server.pop('UserId', None)
self.config.data['auth.token'] = server.pop('AccessToken', None)
@ -581,7 +584,8 @@ class ConnectionManager(object):
if server['Id'] == result['ServerId']:
found_server = server
break
else: return # No server found
else:
return # No server found
if options.get('updateDateLastAccessed') is not False:
found_server['DateLastAccessed'] = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')

View file

@ -2,18 +2,17 @@
#################################################################################################
import json
import logging
import os
import time
from datetime import datetime
#################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
#################################################################################################
class Credentials(object):
credentials = None

View file

@ -2,10 +2,9 @@
#################################################################################################
class HTTPException(Exception):
# Jellyfin HTTP exception
def __init__(self, status, message):
self.status = status
self.message = message

View file

@ -11,7 +11,7 @@ from exceptions import HTTPException
#################################################################################################
LOG = logging.getLogger('Jellyfin.'+__name__)
LOG = logging.getLogger('Jellyfin.' + __name__)
#################################################################################################

View file

@ -5,7 +5,6 @@
import json
import logging
import threading
import time
import xbmc
@ -13,7 +12,7 @@ from ..resources import websocket
##################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
##################################################################################################

View file

@ -7,9 +7,10 @@ from uuid import uuid4
#################################################################################################
LOG = logging.getLogger('JELLYFIN.'+__name__)
LOG = logging.getLogger('JELLYFIN.' + __name__)
#################################################################################################
def generate_client_id():
return str("%012X" % uuid4())

View file

@ -43,8 +43,6 @@ import base64
import threading
import time
import logging
import traceback
import sys
"""
websocket python client.
@ -89,12 +87,14 @@ class WebSocketConnectionClosedException(WebSocketException):
"""
pass
class WebSocketTimeoutException(WebSocketException):
"""
WebSocketTimeoutException will be raised at socket timeout during read/write data.
"""
pass
default_timeout = None
traceEnabled = False
@ -135,8 +135,10 @@ def _wrap_sni_socket(sock, sslopt, hostname):
if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE:
capath = ssl.get_default_verify_paths().capath
context.load_verify_locations(cafile=sslopt.get('ca_certs', None),
capath=sslopt.get('ca_cert_path', capath))
context.load_verify_locations(
cafile=sslopt.get('ca_certs', None),
capath=sslopt.get('ca_cert_path', capath)
)
return context.wrap_socket(
sock,
@ -217,9 +219,10 @@ def create_connection(url, timeout=None, **options):
websock.connect(url, **options)
return websock
_MAX_INTEGER = (1 << 32) -1
_MAX_INTEGER = (1 << 32) - 1
_AVAILABLE_KEY_CHARS = range(0x21, 0x2f + 1) + range(0x3a, 0x7e + 1)
_MAX_CHAR_BYTE = (1<<8) -1
_MAX_CHAR_BYTE = (1 << 8) - 1
# ref. Websocket gets an update, and it breaks stuff.
# http://axod.blogspot.com/2010/06/websocket-gets-update-and-it-breaks.html
@ -233,7 +236,7 @@ def _create_sec_websocket_key():
_HEADERS_TO_CHECK = {
"upgrade": "websocket",
"connection": "upgrade",
}
}
class ABNF(object):
@ -318,9 +321,7 @@ class ABNF(object):
if length >= ABNF.LENGTH_63:
raise ValueError("data is too long")
frame_header = chr(self.fin << 7
| self.rsv1 << 6 | self.rsv2 << 5 | self.rsv3 << 4
| self.opcode)
frame_header = chr(self.fin << 7 | self.rsv1 << 6 | self.rsv2 << 5 | self.rsv3 << 4 | self.opcode)
if length < ABNF.LENGTH_7:
frame_header += chr(self.mask << 7 | length)
elif length < ABNF.LENGTH_16:
@ -582,8 +583,7 @@ class WebSocket(object):
if traceEnabled:
logger.debug("send: " + repr(data))
while data:
l = self._send(data)
data = data[l:]
data = data[self._send(data):]
return length
def send_binary(self, payload):
@ -685,7 +685,6 @@ class WebSocket(object):
self._frame_mask = None
return ABNF(fin, rsv1, rsv2, rsv3, opcode, has_mask, payload)
def send_close(self, status=STATUS_NORMAL, reason=""):
"""
send close data to the server.
@ -709,7 +708,7 @@ class WebSocket(object):
try:
self.sock.shutdown(socket.SHUT_RDWR)
except:
except: # noqa: E722
pass
'''
@ -766,7 +765,6 @@ class WebSocket(object):
raise WebSocketConnectionClosedException()
return bytes
def _recv_strict(self, bufsize):
shortage = bufsize - sum(len(x) for x in self._recv_buffer)
while shortage > 0:
@ -781,7 +779,6 @@ class WebSocket(object):
self._recv_buffer = [unified[bufsize:]]
return unified[:bufsize]
def _recv_line(self):
line = []
while True:
@ -844,7 +841,7 @@ class WebSocketApp(object):
close websocket connection.
"""
self.keep_running = False
if(self.sock != None):
if self.sock is not None:
self.sock.close()
def _send_ping(self, interval):
@ -890,7 +887,7 @@ class WebSocketApp(object):
try:
data = self.sock.recv()
if data is None or self.keep_running == False:
if data is None or self.keep_running is False:
break
self._callback(self.on_message, data)

View file

@ -5,7 +5,6 @@
import logging
import Queue
import threading
import sys
from datetime import datetime, timedelta
import xbmc
@ -16,13 +15,13 @@ from database import Database, jellyfin_db, get_sync, save_sync
from full_sync import FullSync
from views import Views
from downloader import GetItemWorker
from helper import _, api, stop, settings, window, dialog, event, progress, LibraryException
from helper import _, api, stop, settings, window, dialog, event, LibraryException
from helper.utils import split_list, set_screensaver, get_screensaver
from jellyfin import Jellyfin
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
LIMIT = min(int(settings('limitIndex') or 50), 50)
DTHREADS = int(settings('limitThreads') or 3)
MEDIA = {
@ -41,7 +40,6 @@ MEDIA = {
##################################################################################################
class Library(threading.Thread):
started = False
@ -52,7 +50,6 @@ class Library(threading.Thread):
progress_updates = None
total_updates = 0
def __init__(self, monitor):
self.media = {'Movies': Movies, 'TVShows': TVShows, 'MusicVideos': MusicVideos, 'Music': Music}
@ -159,11 +156,11 @@ class Library(threading.Thread):
self.progress_updates = xbmcgui.DialogProgressBG()
self.progress_updates.create(_('addon_name'), _(33178))
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates))*100), message="%s: %s" % (_(33178), queue_size))
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates)) * 100), message="%s: %s" % (_(33178), queue_size))
elif queue_size:
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates))*100), message="%s: %s" % (_(33178), queue_size))
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates)) * 100), message="%s: %s" % (_(33178), queue_size))
else:
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates))*100), message=_(33178))
self.progress_updates.update(int((float(self.total_updates - queue_size) / float(self.total_updates)) * 100), message=_(33178))
if not settings('dbSyncScreensaver.bool') and self.screensaver is None:
@ -171,8 +168,7 @@ class Library(threading.Thread):
self.screensaver = get_screensaver()
set_screensaver(value="")
if (self.pending_refresh and not self.download_threads and not self.writer_threads['updated'] and
not self.writer_threads['userdata'] and not self.writer_threads['removed']):
if (self.pending_refresh and not self.download_threads and not self.writer_threads['updated'] and not self.writer_threads['userdata'] and not self.writer_threads['removed']):
self.pending_refresh = False
self.save_last_sync()
self.total_updates = 0
@ -313,7 +309,6 @@ class Library(threading.Thread):
LOG.info("-->[ q:notify/%s ]", id(new_thread))
self.notify_threads.append(new_thread)
def startup(self):
''' Run at startup.
@ -546,7 +541,6 @@ class Library(threading.Thread):
return True
def userdata(self, data):
''' Add item_id to userdata queue.
@ -654,6 +648,7 @@ class UpdatedWorker(threading.Thread):
LOG.info("--<[ q:updated/%s ]", id(self))
self.is_done = True
class UserDataWorker(threading.Thread):
is_done = False
@ -697,6 +692,7 @@ class UserDataWorker(threading.Thread):
LOG.info("--<[ q:userdata/%s ]", id(self))
self.is_done = True
class SortWorker(threading.Thread):
is_done = False
@ -742,6 +738,7 @@ class SortWorker(threading.Thread):
LOG.info("--<[ q:sort/%s ]", id(self))
self.is_done = True
class RemovedWorker(threading.Thread):
is_done = False
@ -789,6 +786,7 @@ class RemovedWorker(threading.Thread):
LOG.info("--<[ q:removed/%s ]", id(self))
self.is_done = True
class NotifyWorker(threading.Thread):
is_done = False

View file

@ -6,23 +6,21 @@ import binascii
import json
import logging
import threading
import sys
import xbmc
import xbmcgui
import connect
import downloader
import player
from client import get_device_id
from objects import Actions, PlaylistWorker, on_play, on_update, special_listener
from helper import _, settings, window, dialog, event, api, JSONRPC
from objects import PlaylistWorker, on_play, on_update, special_listener
from helper import _, settings, window, dialog, api, JSONRPC
from jellyfin import Jellyfin
from webservice import WebService
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -392,7 +390,7 @@ class Monitor(xbmc.Monitor):
elif command == 'DisplayMessage':
dialog("notification", heading=args['Header'], message=args['Text'],
icon="{jellyfin}", time=int(settings('displayMessage'))*1000)
icon="{jellyfin}", time=int(settings('displayMessage')) * 1000)
elif command == 'SendString':
JSONRPC('Input.SendText').execute({'text': args['String'], 'done': False})

View file

@ -1,5 +1,3 @@
version = "171076031"
from movies import Movies
from musicvideos import MusicVideos
from tvshows import TVShows

View file

@ -2,7 +2,6 @@
#################################################################################################
import json
import logging
import threading
import sys
@ -16,13 +15,13 @@ import xbmcaddon
import database
from downloader import TheVoid
from obj import Objects
from helper import _, playutils, api, window, settings, dialog, JSONRPC
from helper import _, playutils, api, window, settings, dialog
from dialogs import resume
from utils import get_play_action
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -79,7 +78,8 @@ class Actions(object):
index += 1
if force_play:
if len(sys.argv) > 1: xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, self.stack[0][1])
if len(sys.argv) > 1:
xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, self.stack[0][1])
xbmc.Player().play(kodi_playlist, windowed=False)
def set_playlist(self, item, listitem, db_id=None, transcode=False):
@ -177,7 +177,7 @@ class Actions(object):
playlist = self.get_playlist(item)
player = xbmc.Player()
#xbmc.executebuiltin("Playlist.Clear") # Clear playlist to remove the previous item from playlist position no.2
# xbmc.executebuiltin("Playlist.Clear") # Clear playlist to remove the previous item from playlist position no.2
if clear:
if player.isPlaying():
@ -316,8 +316,8 @@ class Actions(object):
else:
obj['Artwork']['Primary'] = obj['Artwork']['Primary'] \
or obj['Artwork']['Thumb'] \
or (obj['Artwork']['Backdrop'][0] \
if len(obj['Artwork']['Backdrop']) \
or (obj['Artwork']['Backdrop'][0]
if len(obj['Artwork']['Backdrop'])
else "special://home/addons/plugin.video.jellyfin/resources/fanart.png")
obj['Artwork']['Primary'] += "&KodiTrailer=true" \
if obj['Type'] == 'Trailer' else "&KodiCinemaMode=true"
@ -442,9 +442,9 @@ class Actions(object):
listitem.setProperty('IsPlayable', 'true')
listitem.setProperty('IsFolder', 'false')
if obj['Resume'] and seektime != False:
if obj['Resume'] and seektime is not False:
listitem.setProperty('resumetime', str(obj['Resume']))
listitem.setProperty('StartPercent', str(((obj['Resume']/obj['Runtime']) * 100) - 0.40))
listitem.setProperty('StartPercent', str(((obj['Resume'] / obj['Runtime']) * 100) - 0.40))
else:
listitem.setProperty('resumetime', '0')
@ -688,9 +688,7 @@ class Actions(object):
return False
if (not xbmc.getCondVisibility('Window.IsMedia') and
((item['Type'] == 'Audio' and not xbmc.getCondVisibility('Integer.IsGreater(Playlist.Length(music),1)')) or
not xbmc.getCondVisibility('Integer.IsGreater(Playlist.Length(video),1)'))):
if (not xbmc.getCondVisibility('Window.IsMedia') and ((item['Type'] == 'Audio' and not xbmc.getCondVisibility('Integer.IsGreater(Playlist.Length(music),1)')) or not xbmc.getCondVisibility('Integer.IsGreater(Playlist.Length(video),1)'))):
return True
@ -733,6 +731,7 @@ def on_update(data, server):
window('jellyfin.skip.%s' % item[0], clear=True)
def on_play(data, server):
''' Setup progress for jellyfin playback.
@ -781,6 +780,7 @@ def on_play(data, server):
item['PlaybackInfo'] = {'Path': file}
playutils.set_properties(item, 'DirectStream' if settings('useDirectPaths') == '0' else 'DirectPlay')
def special_listener():
''' Corner cases that needs to be listened to.
@ -790,8 +790,7 @@ def special_listener():
isPlaying = player.isPlaying()
count = int(window('jellyfin.external_count') or 0)
if (not isPlaying and xbmc.getCondVisibility('Window.IsVisible(DialogContextMenu.xml)') and
xbmc.getInfoLabel('Control.GetLabel(1002)') == xbmc.getLocalizedString(12021)):
if (not isPlaying and xbmc.getCondVisibility('Window.IsVisible(DialogContextMenu.xml)') and xbmc.getInfoLabel('Control.GetLabel(1002)') == xbmc.getLocalizedString(12021)):
control = int(xbmcgui.Window(10106).getFocusId())

View file

@ -12,12 +12,12 @@ import xbmcvfs
import queries as QU
import queries_texture as QUTEX
from helper import window, settings
from helper import settings
import requests
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -37,7 +37,6 @@ class Artwork(object):
'port': settings('webServerPort')
}
def update(self, image_url, kodi_id, media, image):
''' Update artwork in the video database.
@ -220,8 +219,6 @@ class GetArtworkWorker(threading.Thread):
break
"""
# -*- coding: utf-8 -*-
@ -381,4 +378,3 @@ class Artwork(object):
count += 1
"""

View file

@ -4,22 +4,19 @@
import logging
import xbmc
import artwork
import queries as QU
from helper import values
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
class Kodi(object):
def __init__(self):
self.artwork = artwork.Artwork(self.cursor)

View file

@ -9,14 +9,13 @@ import queries as QU
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
class Movies(Kodi):
def __init__(self, cursor):
self.cursor = cursor

View file

@ -9,7 +9,7 @@ from kodi import Kodi
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -212,7 +212,7 @@ class Music(Kodi):
''' Add genres, but delete current genres first.
Album_genres was removed in kodi 18
'''
if media == 'album' and self.version_id < 72 :
if media == 'album' and self.version_id < 72:
self.cursor.execute(QU.delete_genres_album, (kodi_id,))
for genre in genres:
@ -258,7 +258,7 @@ class Music(Kodi):
return self.cursor.fetchone()[0]
#current bug in Kodi 18 that will ask for a scan of music tags unless this is set without a lastscanned
# current bug in Kodi 18 that will ask for a scan of music tags unless this is set without a lastscanned
def update_versiontagscan(self):
if self.version_id < 72:
return

View file

@ -9,14 +9,13 @@ from kodi import Kodi
##################################################################################################
log = logging.getLogger("JELLYFIN."+__name__)
log = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
class MusicVideos(Kodi):
def __init__(self, cursor):
self.cursor = cursor

File diff suppressed because it is too large Load diff

View file

@ -1,238 +1,260 @@
create_artist = """ SELECT coalesce(max(idArtist), 1)
FROM artist
"""
create_album = """ SELECT coalesce(max(idAlbum), 0)
FROM album
"""
create_song = """ SELECT coalesce(max(idSong), 0)
FROM song
"""
create_genre = """ SELECT coalesce(max(idGenre), 0)
FROM genre
"""
create_artist = """
SELECT coalesce(max(idArtist), 1)
FROM artist
"""
create_album = """
SELECT coalesce(max(idAlbum), 0)
FROM album
"""
create_song = """
SELECT coalesce(max(idSong), 0)
FROM song
"""
create_genre = """
SELECT coalesce(max(idGenre), 0)
FROM genre
"""
get_artist = """ SELECT idArtist, strArtist
FROM artist
WHERE strMusicBrainzArtistID = ?
"""
get_artist_obj = [ "{ArtistId}","{Name}","{UniqueId}"
]
get_artist_by_name = """ SELECT idArtist
FROM artist
WHERE strArtist = ?
get_artist = """
SELECT idArtist, strArtist
FROM artist
WHERE strMusicBrainzArtistID = ?
"""
get_artist_obj = ["{ArtistId}", "{Name}", "{UniqueId}"]
get_artist_by_name = """
SELECT idArtist
FROM artist
WHERE strArtist = ?
COLLATE NOCASE
"""
get_artist_by_id = """ SELECT *
FROM artist
WHERE idArtist = ?
"""
get_artist_by_id_obj = [ "{ArtistId}"
]
get_album_by_id = """ SELECT *
FROM album
WHERE idAlbum = ?
"""
get_album_by_id_obj = [ "{AlbumId}"
]
get_song_by_id = """ SELECT *
FROM song
WHERE idSong = ?
"""
get_song_by_id_obj = [ "{SongId}"
]
get_album = """ SELECT idAlbum
FROM album
WHERE strMusicBrainzAlbumID = ?
"""
get_album_obj = [ "{AlbumId}","{Title}","{UniqueId}","{Artists}","album"
]
get_album_by_name = """ SELECT idAlbum, strArtists
FROM album
WHERE strAlbum = ?
"""
get_album_by_name72 = """ SELECT idAlbum, strArtistDisp
FROM album
WHERE strAlbum = ?
"""
get_album_artist = """ SELECT strArtists
FROM album
WHERE idAlbum = ?
"""
get_album_artist72 = """ SELECT strArtistDisp
FROM album
WHERE idAlbum = ?
"""
get_album_artist_obj = [ "{AlbumId}","{strAlbumArtists}"
]
get_genre = """ SELECT idGenre
FROM genre
WHERE strGenre = ?
"""
get_artist_by_id = """
SELECT *
FROM artist
WHERE idArtist = ?
"""
get_artist_by_id_obj = ["{ArtistId}"]
get_album_by_id = """
SELECT *
FROM album
WHERE idAlbum = ?
"""
get_album_by_id_obj = ["{AlbumId}"]
get_song_by_id = """
SELECT *
FROM song
WHERE idSong = ?
"""
get_song_by_id_obj = ["{SongId}"]
get_album = """
SELECT idAlbum
FROM album
WHERE strMusicBrainzAlbumID = ?
"""
get_album_obj = ["{AlbumId}", "{Title}", "{UniqueId}", "{Artists}", "album"]
get_album_by_name = """
SELECT idAlbum, strArtists
FROM album
WHERE strAlbum = ?
"""
get_album_by_name72 = """
SELECT idAlbum, strArtistDisp
FROM album
WHERE strAlbum = ?
"""
get_album_artist = """
SELECT strArtists
FROM album
WHERE idAlbum = ?
"""
get_album_artist72 = """
SELECT strArtistDisp
FROM album
WHERE idAlbum = ?
"""
get_album_artist_obj = ["{AlbumId}", "{strAlbumArtists}"]
get_genre = """
SELECT idGenre
FROM genre
WHERE strGenre = ?
COLLATE NOCASE
"""
get_total_episodes = """ SELECT totalCount
FROM tvshowcounts
WHERE idShow = ?
"""
"""
get_total_episodes = """
SELECT totalCount
FROM tvshowcounts
WHERE idShow = ?
"""
add_artist = """ INSERT INTO artist(idArtist, strArtist, strMusicBrainzArtistID)
VALUES (?, ?, ?)
"""
add_album = """ INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strReleaseType)
VALUES (?, ?, ?, ?)
"""
add_album72 = """ INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strReleaseType, bScrapedMBID)
VALUES (?, ?, ?, ?, 1)
"""
add_single = """ INSERT INTO album(idAlbum, strGenres, iYear, strReleaseType)
VALUES (?, ?, ?, ?)
"""
add_single_obj = [ "{AlbumId}","{Genre}","{Year}","single"
]
add_song = """ INSERT INTO song(idSong, idAlbum, idPath, strArtists, strGenres, strTitle, iTrack,
add_artist = """
INSERT INTO artist(idArtist, strArtist, strMusicBrainzArtistID)
VALUES (?, ?, ?)
"""
add_album = """
INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strReleaseType)
VALUES (?, ?, ?, ?)
"""
add_album72 = """
INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strReleaseType, bScrapedMBID)
VALUES (?, ?, ?, ?, 1)
"""
add_single = """
INSERT INTO album(idAlbum, strGenres, iYear, strReleaseType)
VALUES (?, ?, ?, ?)
"""
add_single_obj = ["{AlbumId}", "{Genre}", "{Year}", "single"]
add_song = """
INSERT INTO song(idSong, idAlbum, idPath, strArtists, strGenres, strTitle, iTrack,
iDuration, iYear, strFileName, strMusicBrainzTrackID, iTimesPlayed, lastplayed,
rating, comment, dateAdded)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_song72 = """ INSERT INTO song(idSong, idAlbum, idPath, strArtistDisp, strGenres, strTitle, iTrack,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_song72 = """
INSERT INTO song(idSong, idAlbum, idPath, strArtistDisp, strGenres, strTitle, iTrack,
iDuration, iYear, strFileName, strMusicBrainzTrackID, iTimesPlayed, lastplayed,
rating, comment, dateAdded)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_song_obj = [ "{SongId}","{AlbumId}","{PathId}","{Artists}","{Genre}","{Title}","{Index}",
"{Runtime}","{Year}","{Filename}","{UniqueId}","{PlayCount}","{DatePlayed}","{Rating}",
"{Comment}","{DateAdded}"
]
add_genre = """ INSERT INTO genre(idGenre, strGenre)
VALUES (?, ?)
"""
add_genres_obj = [ "{AlbumId}","{Genres}","album"
]
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
add_song_obj = ["{SongId}", "{AlbumId}", "{PathId}", "{Artists}", "{Genre}", "{Title}", "{Index}",
"{Runtime}", "{Year}", "{Filename}", "{UniqueId}", "{PlayCount}", "{DatePlayed}", "{Rating}",
"{Comment}", "{DateAdded}"]
add_genre = """
INSERT INTO genre(idGenre, strGenre)
VALUES (?, ?)
"""
add_genres_obj = ["{AlbumId}", "{Genres}", "album"]
update_path = """ UPDATE path
SET strPath = ?
WHERE idPath = ?
"""
update_path_obj = [ "{Path}","{PathId}"
]
update_role = """ INSERT OR REPLACE INTO role(idRole, strRole)
VALUES (?, ?)
"""
update_role_obj = [ 1,"Composer"
]
update_artist_name = """ UPDATE artist
SET strArtist = ?
WHERE idArtist = ?
"""
update_artist_name_obj = [ "{Name}","{ArtistId}"
]
update_artist = """ UPDATE artist
SET strGenres = ?, strBiography = ?, strImage = ?, strFanart = ?, lastScraped = ?
WHERE idArtist = ?
"""
update_link = """ INSERT OR REPLACE INTO album_artist(idArtist, idAlbum, strArtist)
VALUES (?, ?, ?)
"""
update_link_obj = [ "{ArtistId}","{AlbumId}","{Name}"
]
update_discography = """ INSERT OR REPLACE INTO discography(idArtist, strAlbum, strYear)
VALUES (?, ?, ?)
"""
update_discography_obj = [ "{ArtistId}","{Title}","{Year}"
]
update_album = """ UPDATE album
SET strArtists = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?,
update_path = """
UPDATE path
SET strPath = ?
WHERE idPath = ?
"""
update_path_obj = ["{Path}", "{PathId}"]
update_role = """
INSERT OR REPLACE INTO role(idRole, strRole)
VALUES (?, ?)
"""
update_role_obj = [1, "Composer"]
update_artist_name = """
UPDATE artist
SET strArtist = ?
WHERE idArtist = ?
"""
update_artist_name_obj = ["{Name}", "{ArtistId}"]
update_artist = """
UPDATE artist
SET strGenres = ?, strBiography = ?, strImage = ?, strFanart = ?, lastScraped = ?
WHERE idArtist = ?
"""
update_link = """
INSERT OR REPLACE INTO album_artist(idArtist, idAlbum, strArtist)
VALUES (?, ?, ?)
"""
update_link_obj = ["{ArtistId}", "{AlbumId}", "{Name}"]
update_discography = """
INSERT OR REPLACE INTO discography(idArtist, strAlbum, strYear)
VALUES (?, ?, ?)
"""
update_discography_obj = ["{ArtistId}", "{Title}", "{Year}"]
update_album = """
UPDATE album
SET strArtists = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?,
iUserrating = ?, lastScraped = ?, strReleaseType = ?
WHERE idAlbum = ?
"""
update_album72 = """ UPDATE album
SET strArtistDisp = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?,
WHERE idAlbum = ?
"""
update_album72 = """
UPDATE album
SET strArtistDisp = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?,
iUserrating = ?, lastScraped = ?, bScrapedMBID = 1, strReleaseType = ?
WHERE idAlbum = ?
"""
update_album_obj = [ "{Artists}","{Year}","{Genre}","{Bio}","{Thumb}","{Rating}","{LastScraped}",
"album","{AlbumId}"
]
update_album_artist = """ UPDATE album
SET strArtists = ?
WHERE idAlbum = ?
"""
update_album_artist72 = """ UPDATE album
SET strArtistDisp = ?
WHERE idAlbum = ?
"""
update_song = """ UPDATE song
SET idAlbum = ?, strArtists = ?, strGenres = ?, strTitle = ?, iTrack = ?,
WHERE idAlbum = ?
"""
update_album_obj = ["{Artists}", "{Year}", "{Genre}", "{Bio}", "{Thumb}", "{Rating}", "{LastScraped}", "album", "{AlbumId}"]
update_album_artist = """
UPDATE album
SET strArtists = ?
WHERE idAlbum = ?
"""
update_album_artist72 = """
UPDATE album
SET strArtistDisp = ?
WHERE idAlbum = ?
"""
update_song = """
UPDATE song
SET idAlbum = ?, strArtists = ?, strGenres = ?, strTitle = ?, iTrack = ?,
iDuration = ?, iYear = ?, strFilename = ?, iTimesPlayed = ?, lastplayed = ?,
rating = ?, comment = ?, dateAdded = ?
WHERE idSong = ?
"""
update_song72 = """ UPDATE song
SET idAlbum = ?, strArtistDisp = ?, strGenres = ?, strTitle = ?, iTrack = ?,
WHERE idSong = ?
"""
update_song72 = """
UPDATE song
SET idAlbum = ?, strArtistDisp = ?, strGenres = ?, strTitle = ?, iTrack = ?,
iDuration = ?, iYear = ?, strFilename = ?, iTimesPlayed = ?, lastplayed = ?,
rating = ?, comment = ?, dateAdded = ?
WHERE idSong = ?
"""
update_song_obj = [ "{AlbumId}","{Artists}","{Genre}","{Title}","{Index}","{Runtime}","{Year}",
"{Filename}","{PlayCount}","{DatePlayed}","{Rating}","{Comment}",
"{DateAdded}","{SongId}"
]
update_song_artist = """ INSERT OR REPLACE INTO song_artist(idArtist, idSong, idRole, iOrder, strArtist)
VALUES (?, ?, ?, ?, ?)
"""
update_song_artist_obj = [ "{ArtistId}","{SongId}",1,"{Index}","{Name}"
]
update_song_album = """ INSERT OR REPLACE INTO albuminfosong(idAlbumInfoSong, idAlbumInfo, iTrack,
WHERE idSong = ?
"""
update_song_obj = ["{AlbumId}", "{Artists}", "{Genre}", "{Title}", "{Index}", "{Runtime}", "{Year}",
"{Filename}", "{PlayCount}", "{DatePlayed}", "{Rating}", "{Comment}",
"{DateAdded}", "{SongId}"]
update_song_artist = """
INSERT OR REPLACE INTO song_artist(idArtist, idSong, idRole, iOrder, strArtist)
VALUES (?, ?, ?, ?, ?)
"""
update_song_artist_obj = ["{ArtistId}", "{SongId}", 1, "{Index}", "{Name}"]
update_song_album = """
INSERT OR REPLACE INTO albuminfosong(idAlbumInfoSong, idAlbumInfo, iTrack,
strTitle, iDuration)
VALUES (?, ?, ?, ?, ?)
"""
update_song_album_obj = [ "{SongId}","{AlbumId}","{Index}","{Title}","{Runtime}"
]
update_song_rating = """ UPDATE song
SET iTimesPlayed = ?, lastplayed = ?, rating = ?
WHERE idSong = ?
"""
update_song_rating_obj = [ "{PlayCount}","{DatePlayed}","{Rating}","{KodiId}"
]
update_genre_album = """ INSERT OR REPLACE INTO album_genre(idGenre, idAlbum)
VALUES (?, ?)
"""
update_genre_song = """ INSERT OR REPLACE INTO song_genre(idGenre, idSong)
VALUES (?, ?)
"""
update_genre_song_obj = [ "{SongId}","{Genres}","song"
]
VALUES (?, ?, ?, ?, ?)
"""
update_song_album_obj = ["{SongId}", "{AlbumId}", "{Index}", "{Title}", "{Runtime}"]
update_song_rating = """
UPDATE song
SET iTimesPlayed = ?, lastplayed = ?, rating = ?
WHERE idSong = ?
"""
update_song_rating_obj = ["{PlayCount}", "{DatePlayed}", "{Rating}", "{KodiId}"]
update_genre_album = """
INSERT OR REPLACE INTO album_genre(idGenre, idAlbum)
VALUES (?, ?)
"""
update_genre_song = """
INSERT OR REPLACE INTO song_genre(idGenre, idSong)
VALUES (?, ?)
"""
update_genre_song_obj = ["{SongId}", "{Genres}", "song"]
delete_genres_album = """ DELETE FROM album_genre
WHERE idAlbum = ?
"""
delete_genres_song = """ DELETE FROM song_genre
WHERE idSong = ?
"""
delete_artist = """ DELETE FROM artist
WHERE idArtist = ?
"""
delete_album = """ DELETE FROM album
WHERE idAlbum = ?
"""
delete_song = """ DELETE FROM song
WHERE idSong = ?
"""
get_version = """ SELECT idVersion
FROM version
"""
update_versiontag = """ INSERT OR REPLACE INTO versiontagscan(idVersion, iNeedsScan)
VALUES (?, 0)
"""
get_versiontagcount = """ SELECT COUNT(*)
FROM versiontagscan
"""
delete_genres_album = """
DELETE FROM album_genre
WHERE idAlbum = ?
"""
delete_genres_song = """
DELETE FROM song_genre
WHERE idSong = ?
"""
delete_artist = """
DELETE FROM artist
WHERE idArtist = ?
"""
delete_album = """
DELETE FROM album
WHERE idAlbum = ?
"""
delete_song = """
DELETE FROM song
WHERE idSong = ?
"""
get_version = """
SELECT idVersion
FROM version
"""
update_versiontag = """
INSERT OR REPLACE INTO versiontagscan(idVersion, iNeedsScan)
VALUES (?, 0)
"""
get_versiontagcount = """
SELECT COUNT (*)
FROM versiontagscan
"""

View file

@ -1,11 +1,12 @@
get_cache = """ SELECT cachedurl
FROM texture
WHERE url = ?
"""
get_cache = """
SELECT cachedurl
FROM texture
WHERE url = ?
"""
delete_cache = """ DELETE FROM texture
WHERE url = ?
"""
delete_cache = """
DELETE FROM texture
WHERE url = ?
"""

View file

@ -9,14 +9,13 @@ from kodi import Kodi
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
class TVShows(Kodi):
def __init__(self, cursor):
self.cursor = cursor

View file

@ -2,7 +2,6 @@
##################################################################################################
import json
import logging
import urllib
@ -10,11 +9,11 @@ import downloader as server
from obj import Objects
from kodi import Movies as KodiDb, queries as QU
from database import jellyfin_db, queries as QUEM
from helper import api, catch, stop, validate, jellyfin_item, library_check, values, settings, Local
from helper import api, stop, validate, jellyfin_item, library_check, values, settings, Local
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -52,8 +51,7 @@ class Movies(KodiDb):
obj['MovieId'] = e_item[0]
obj['FileId'] = e_item[1]
obj['PathId'] = e_item[2]
except TypeError as error:
except TypeError:
update = False
LOG.debug("MovieId %s not found", obj['Id'])
obj['MovieId'] = self.create_entry()
@ -103,13 +101,11 @@ class Movies(KodiDb):
obj['Tags'] = tags
if update:
self.movie_update(obj)
else:
self.movie_add(obj)
self.update_path(*values(obj, QU.update_path_movie_obj))
self.update_file(*values(obj, QU.update_file_obj))
self.add_tags(*values(obj, QU.add_tags_movie_obj))
@ -192,7 +188,6 @@ class Movies(KodiDb):
}
obj['Filename'] = "%s?%s" % (obj['Path'], urllib.urlencode(params))
@stop()
@jellyfin_item()
def boxset(self, item, e_item):
@ -213,8 +208,7 @@ class Movies(KodiDb):
try:
obj['SetId'] = e_item[0]
self.update_boxset(*values(obj, QU.update_set_obj))
except TypeError as error:
except TypeError:
LOG.debug("SetId %s not found", obj['Id'])
obj['SetId'] = self.add_boxset(*values(obj, QU.add_set_obj))

View file

@ -2,19 +2,17 @@
##################################################################################################
import json
import datetime
import logging
import urllib
from obj import Objects
from kodi import Music as KodiDb, queries_music as QU
from database import jellyfin_db, queries as QUEM
from helper import api, catch, stop, validate, jellyfin_item, values, library_check, settings, Local
from helper import api, stop, validate, jellyfin_item, values, library_check, Local
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -50,8 +48,7 @@ class Music(KodiDb):
try:
obj['ArtistId'] = e_item[0]
except TypeError as error:
except TypeError:
update = False
obj['ArtistId'] = None
LOG.debug("ArtistId %s not found", obj['Id'])
@ -77,13 +74,11 @@ class Music(KodiDb):
if obj['Backdrops']:
obj['Backdrops'] = "<fanart>%s</fanart>" % obj['Backdrops'][0]
if update:
self.artist_update(obj)
else:
self.artist_add(obj)
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
self.artwork.add(obj['Artwork'], obj['ArtistId'], "artist")
self.item_ids.append(obj['Id'])
@ -106,7 +101,6 @@ class Music(KodiDb):
self.jellyfin_db.update_reference(*values(obj, QUEM.update_reference_obj))
LOG.info("UPDATE artist [%s] %s: %s", obj['ArtistId'], obj['Name'], obj['Id'])
@stop()
@jellyfin_item()
def album(self, item, e_item):
@ -121,8 +115,7 @@ class Music(KodiDb):
try:
obj['AlbumId'] = e_item[0]
except TypeError as error:
except TypeError:
update = False
obj['AlbumId'] = None
LOG.debug("AlbumId %s not found", obj['Id'])
@ -144,13 +137,11 @@ class Music(KodiDb):
if obj['Thumb']:
obj['Thumb'] = "<thumb>%s</thumb>" % obj['Thumb']
if update:
self.album_update(obj)
else:
self.album_add(obj)
self.artist_link(obj)
self.artist_discography(obj)
self.update_album(*values(obj, QU.update_album_obj))
@ -217,7 +208,6 @@ class Music(KodiDb):
self.link(*values(temp_obj, QU.update_link_obj))
self.item_ids.append(temp_obj['Id'])
@stop()
@jellyfin_item()
def song(self, item, e_item):
@ -234,8 +224,7 @@ class Music(KodiDb):
obj['SongId'] = e_item[0]
obj['PathId'] = e_item[2]
obj['AlbumId'] = e_item[3]
except TypeError as error:
except TypeError:
update = False
obj['SongId'] = self.create_entry_song()
LOG.debug("SongId %s not found", obj['Id'])
@ -269,13 +258,11 @@ class Music(KodiDb):
if obj['Disc'] != 1:
obj['Index'] = obj['Disc'] * 2 ** 16 + obj['Index']
if update:
self.song_update(obj)
else:
self.song_add(obj)
self.link_song_album(*values(obj, QU.update_song_album_obj))
self.add_role(*values(obj, QU.update_role_obj)) # defaultt role
self.song_artist_link(obj)
@ -415,7 +402,6 @@ class Music(KodiDb):
obj['AlbumId'] = self.create_entry_album()
self.add_single(*values(obj, QU.add_single_obj))
@stop()
@jellyfin_item()
def userdata(self, item, e_item):

View file

@ -10,11 +10,11 @@ import urllib
from obj import Objects
from kodi import MusicVideos as KodiDb, queries as QU
from database import jellyfin_db, queries as QUEM
from helper import api, catch, stop, validate, library_check, jellyfin_item, values, Local
from helper import api, stop, validate, library_check, jellyfin_item, values, Local
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -55,8 +55,7 @@ class MusicVideos(KodiDb):
obj['MvideoId'] = e_item[0]
obj['FileId'] = e_item[1]
obj['PathId'] = e_item[2]
except TypeError as error:
except TypeError:
update = False
LOG.debug("MvideoId for %s not found", obj['Id'])
obj['MvideoId'] = self.create_entry()
@ -114,13 +113,11 @@ class MusicVideos(KodiDb):
obj['Tags'] = tags
if update:
self.musicvideo_update(obj)
else:
self.musicvideo_add(obj)
self.update_path(*values(obj, QU.update_path_mvideo_obj))
self.update_file(*values(obj, QU.update_file_obj))
self.add_tags(*values(obj, QU.add_tags_mvideo_obj))
@ -176,7 +173,6 @@ class MusicVideos(KodiDb):
}
obj['Filename'] = "%s?%s" % (obj['Path'], urllib.urlencode(params))
@stop()
@jellyfin_item()
def userdata(self, item, e_item):

View file

@ -8,7 +8,7 @@ import os
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################

View file

@ -2,7 +2,6 @@
##################################################################################################
import json
import logging
import sqlite3
import urllib
@ -12,11 +11,11 @@ from obj import Objects
from kodi import TVShows as KodiDb, queries as QU
import downloader as server
from database import jellyfin_db, queries as QUEM
from helper import api, catch, stop, validate, jellyfin_item, library_check, settings, values, Local
from helper import api, stop, validate, jellyfin_item, library_check, settings, values, Local
##################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
##################################################################################################
@ -65,8 +64,7 @@ class TVShows(KodiDb):
try:
obj['ShowId'] = e_item[0]
obj['PathId'] = e_item[2]
except TypeError as error:
except TypeError:
update = False
LOG.debug("ShowId %s not found", obj['Id'])
obj['ShowId'] = self.create_entry()
@ -76,7 +74,6 @@ class TVShows(KodiDb):
update = False
LOG.info("ShowId %s missing from kodi. repairing the entry.", obj['ShowId'])
obj['Path'] = API.get_file_path(obj['Path'])
obj['LibraryId'] = library['Id']
obj['LibraryName'] = library['Name']
@ -107,13 +104,11 @@ class TVShows(KodiDb):
obj['Tags'] = tags
if update:
self.tvshow_update(obj)
else:
self.tvshow_add(obj)
self.link(*values(obj, QU.update_tvshow_link_obj))
self.update_path(*values(obj, QU.update_path_tvshow_obj))
self.add_tags(*values(obj, QU.add_tags_tvshow_obj))
@ -209,7 +204,6 @@ class TVShows(KodiDb):
obj['TopLevel'] = "plugin://plugin.video.jellyfin/"
obj['Path'] = "%s%s/" % (obj['TopLevel'], obj['Id'])
@stop()
def season(self, item, show_id=None):
@ -244,7 +238,6 @@ class TVShows(KodiDb):
self.artwork.add(obj['Artwork'], obj['SeasonId'], "season")
LOG.info("UPDATE season [%s/%s] %s: %s", obj['ShowId'], obj['SeasonId'], obj['Title'] or obj['Index'], obj['Id'])
@stop()
@jellyfin_item()
def episode(self, item, e_item):
@ -275,8 +268,7 @@ class TVShows(KodiDb):
obj['EpisodeId'] = e_item[0]
obj['FileId'] = e_item[1]
obj['PathId'] = e_item[2]
except TypeError as error:
except TypeError:
update = False
LOG.debug("EpisodeId %s not found", obj['Id'])
obj['EpisodeId'] = self.create_entry_episode()
@ -286,7 +278,6 @@ class TVShows(KodiDb):
update = False
LOG.info("EpisodeId %s missing from kodi. repairing the entry.", obj['EpisodeId'])
obj['Path'] = API.get_file_path(obj['Path'])
obj['Index'] = obj['Index'] or -1
obj['Writers'] = " / ".join(obj['Writers'] or [])
@ -329,13 +320,11 @@ class TVShows(KodiDb):
obj['SeasonId'] = self.get_season(*values(obj, QU.get_season_episode_obj))
if update:
self.episode_update(obj)
else:
self.episode_add(obj)
self.update_path(*values(obj, QU.update_path_episode_obj))
self.update_file(*values(obj, QU.update_file_obj))
self.add_people(*values(obj, QU.add_people_episode_obj))
@ -370,8 +359,7 @@ class TVShows(KodiDb):
try:
self.add_episode(*values(obj, QU.add_episode_obj))
except sqlite3.IntegrityError as error:
except sqlite3.IntegrityError:
LOG.error("IntegrityError for %s", obj)
obj['EpisodeId'] = self.create_entry_episode()
@ -440,7 +428,6 @@ class TVShows(KodiDb):
return True
@stop()
@jellyfin_item()
def userdata(self, item, e_item):

View file

@ -8,7 +8,7 @@ from helper import JSONRPC
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################

View file

@ -2,7 +2,6 @@
#################################################################################################
import json
import logging
import os
@ -15,7 +14,7 @@ from jellyfin import Jellyfin
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
@ -338,7 +337,6 @@ class Player(xbmc.Player):
return
result = JSONRPC('Application.GetProperties').execute({'properties': ["volume", "muted"]})
result = result.get('result', {})
item['Volume'] = result.get('volume')
@ -415,7 +413,6 @@ class Player(xbmc.Player):
LOG.info("<[ transcode/%s ]", item['Id'])
item['Server'].jellyfin.close_transcode(item['DeviceId'])
path = xbmc.translatePath("special://profile/addon_data/plugin.video.jellyfin/temp/").decode('utf-8')
if xbmcvfs.exists(path):

View file

@ -4,13 +4,11 @@
import logging
import xbmc
from helper import _, settings, dialog, JSONRPC, compare_version
from helper import _, settings, dialog, JSONRPC
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################

View file

@ -11,15 +11,13 @@ import xml.etree.ElementTree as etree
import xbmc
import xbmcvfs
import downloader as server
from database import Database, jellyfin_db, get_sync, save_sync
from objects.kodi import kodi
from helper import _, api, indent, write_xml, window, event
from jellyfin import Jellyfin
#################################################################################################
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
NODES = {
'tvshows': [
('all', None),
@ -70,7 +68,7 @@ DYNNODES = {
('FirstLetter', _(33171)),
('Genres', _(135)),
('Random', _(30229)),
#('Recommended', _(30230))
# ('Recommended', _(30230))
],
'musicvideos': [
('all', None),
@ -136,6 +134,7 @@ def verify_kodi_defaults():
if not xbmcvfs.exists(playlist_path):
xbmcvfs.mkdirs(playlist_path)
class Views(object):
sync = None
@ -421,7 +420,6 @@ class Views(object):
etree.SubElement(xml, 'match')
etree.SubElement(xml, 'content')
label = xml.find('label')
label.text = str(name) if type(name) == int else name
@ -642,7 +640,7 @@ class Views(object):
if rule.attrib['field'] == 'inprogress':
break
else:
etree.SubElement(root, 'rule', {'field': "inprogress", 'operator':"true"})
etree.SubElement(root, 'rule', {'field': "inprogress", 'operator': "true"})
content = root.find('content')
content.text = "episodes"
@ -661,7 +659,6 @@ class Views(object):
else:
etree.SubElement(root, 'content').text = "episodes"
def order_media_folders(self, folders):
''' Returns a list of sorted media folders based on the Jellyfin views.
@ -909,16 +906,16 @@ class Views(object):
total = int(window((name or 'Jellyfin.nodes') + '.total') or 0)
props = [
"index","id","path","artwork","title","content","type"
"inprogress.content","inprogress.title",
"inprogress.content","inprogress.path",
"nextepisodes.title","nextepisodes.content",
"nextepisodes.path","unwatched.title",
"unwatched.content","unwatched.path",
"recent.title","recent.content","recent.path",
"recentepisodes.title","recentepisodes.content",
"recentepisodes.path","inprogressepisodes.title",
"inprogressepisodes.content","inprogressepisodes.path"
"index", "id", "path", "artwork", "title", "content", "type"
"inprogress.content", "inprogress.title",
"inprogress.content", "inprogress.path",
"nextepisodes.title", "nextepisodes.content",
"nextepisodes.path", "unwatched.title",
"unwatched.content", "unwatched.path",
"recent.title", "recent.content", "recent.path",
"recentepisodes.title", "recentepisodes.content",
"recentepisodes.path", "inprogressepisodes.title",
"inprogressepisodes.content", "inprogressepisodes.path"
]
for i in range(total):
for prop in props:

View file

@ -13,10 +13,11 @@ import xbmc
#################################################################################################
PORT = 57578
LOG = logging.getLogger("JELLYFIN."+__name__)
LOG = logging.getLogger("JELLYFIN." + __name__)
#################################################################################################
class WebService(threading.Thread):
''' Run a webservice to trigger playback.
@ -127,7 +128,7 @@ class requestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
% (params.get('Id'), params.get('KodiId'), params.get('Name'), params.get('transcode') or False))
self.send_response(200)
self.send_header('Content-type','text/html')
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(path)
@ -142,4 +143,3 @@ class requestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
self.send_error(500, "Exception occurred: %s" % error)
return

View file

@ -19,8 +19,8 @@ sys.path.insert(0, __base__)
#################################################################################################
from entrypoint import Service
from helper import settings
from entrypoint import Service # noqa: F402
from helper import settings # noqa: F402
#################################################################################################

View file

@ -2,3 +2,7 @@
max-line-length = 9999
import-order-style = pep8
exclude = ./.git,./.vscode,./libraries
extend-ignore =
I202
per-file-ignores =
*/__init__.py: F401