Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type annotations and mypy #821

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ def create_addon_xml(config: dict, source: str, py_version: str) -> None:

# Populate dependencies in template
dependencies = config['dependencies'].get(py_version)
requires_el = root.find('requires')
assert isinstance(requires_el, ET.Element), "Unable to find requires element in template"

for dep in dependencies:
ET.SubElement(root.find('requires'), 'import', attrib=dep)
ET.SubElement(requires_el, 'import', attrib=dep)

# Populate version string
addon_version = config.get('version')
Expand Down Expand Up @@ -110,7 +113,6 @@ def folder_filter(folder_name: str) -> bool:
return True



if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Build flags:')
parser.add_argument(
Expand Down
6 changes: 3 additions & 3 deletions jellyfin_kodi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from kodi_six import xbmc, xbmcaddon, xbmcvfs

from .helper import translate, window, settings, addon_id, dialog, LazyLogger
from .helper import translate, window, settings, ADDON_ID, dialog, LazyLogger
from .helper.utils import create_id, translate_path

##################################################################################################
Expand All @@ -21,11 +21,11 @@

''' Used for logging.
'''
return xbmcaddon.Addon(addon_id()).getAddonInfo('name').upper()
return xbmcaddon.Addon(ADDON_ID).getAddonInfo('name').upper()

Check warning on line 24 in jellyfin_kodi/client.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/client.py#L24

Added line #L24 was not covered by tests


def get_version():
return xbmcaddon.Addon(addon_id()).getAddonInfo('version')
return xbmcaddon.Addon(ADDON_ID).getAddonInfo('version')

Check warning on line 28 in jellyfin_kodi/client.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/client.py#L28

Added line #L28 was not covered by tests


def get_platform():
Expand Down
16 changes: 8 additions & 8 deletions jellyfin_kodi/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
from . import client
from .database import get_credentials, save_credentials
from .dialogs import ServerConnect, UsersConnect, LoginManual, ServerManual
from .helper import settings, addon_id, event, api, window, LazyLogger
from .helper import settings, ADDON_ID, event, api, window, LazyLogger
from .jellyfin import Jellyfin
from .jellyfin.connection_manager import CONNECTION_STATE
from .helper.exceptions import HTTPException

##################################################################################################

LOG = LazyLogger(__name__)
XML_PATH = (xbmcaddon.Addon(addon_id()).getAddonInfo('path'), "default", "1080i")
XML_PATH = (xbmcaddon.Addon(ADDON_ID).getAddonInfo('path'), "default", "1080i")

##################################################################################################

Expand Down Expand Up @@ -129,7 +129,7 @@
except RuntimeError as error:

LOG.exception(error)
xbmc.executebuiltin('Addon.OpenSettings(%s)' % addon_id())
xbmc.executebuiltin('Addon.OpenSettings(%s)' % ADDON_ID)

Check warning on line 132 in jellyfin_kodi/connect.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/connect.py#L132

Added line #L132 was not covered by tests

raise Exception('User sign in interrupted')

Expand All @@ -144,17 +144,17 @@

''' Save user info.
'''
self.user = client.jellyfin.get_user()
settings('username', self.user['Name'])
user = client.jellyfin.get_user()
settings('username', user['Name'])

Check warning on line 148 in jellyfin_kodi/connect.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/connect.py#L147-L148

Added lines #L147 - L148 were not covered by tests

if 'PrimaryImageTag' in self.user:
if 'PrimaryImageTag' in user:
server_address = client.auth.get_server_info(client.auth.server_id)['address']
window('JellyfinUserImage', api.API(self.user, server_address).get_user_artwork(self.user['Id']))
window('JellyfinUserImage', api.API(user, server_address).get_user_artwork(user['Id']))

Check warning on line 152 in jellyfin_kodi/connect.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/connect.py#L152

Added line #L152 was not covered by tests

def select_servers(self, state=None):

state = state or self.connect_manager.connect({'enableAutoLogin': False})
user = {}
user = {} # TODO: Fixme: content of this dict is used below, but can never contain anything

Check warning on line 157 in jellyfin_kodi/connect.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/connect.py#L157

Added line #L157 was not covered by tests

dialog = ServerConnect("script-jellyfin-connect-server.xml", *XML_PATH)
dialog.set_args(
Expand Down
7 changes: 4 additions & 3 deletions jellyfin_kodi/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sqlite3
import sys
import re
from typing import Any, Dict

from kodi_six import xbmc, xbmcvfs
from six import text_type
Expand Down Expand Up @@ -36,7 +37,7 @@ class Database(object):
'''
timeout = 120
discovered = False
discovered_file = None
discovered_file: str = None

def __init__(self, db_file=None, commit_close=True):

Expand Down Expand Up @@ -318,7 +319,7 @@ def reset_artwork():
LOG.info("[ reset artwork ]")


def get_sync():
def get_sync() -> dict:
if (3, 0) <= sys.version_info < (3, 6):
LOG.error("Python versions 3.0-3.5 are NOT supported.")

Expand All @@ -342,7 +343,7 @@ def get_sync():
return sync


def save_sync(sync):
def save_sync(sync: Dict[str, Any]):

if not xbmcvfs.exists(ADDON_DATA):
xbmcvfs.mkdirs(ADDON_DATA)
Expand Down
8 changes: 6 additions & 2 deletions jellyfin_kodi/database/jellyfin_db.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals

from sqlite3 import Cursor

#################################################################################################

from . import queries as QU
Expand All @@ -14,9 +17,10 @@
##################################################################################################


class JellyfinDatabase():
class JellyfinDatabase:
cursor: Cursor

def __init__(self, cursor):
def __init__(self, cursor: Cursor) -> None:
self.cursor = cursor
cursor.row_factory = sqlite_namedtuple_factory

Expand Down
9 changes: 5 additions & 4 deletions jellyfin_kodi/dialogs/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
##################################################################################################

import os
from typing import List, cast

from kodi_six import xbmcgui, xbmcaddon
from six import ensure_text

from ..helper import window, addon_id
from ..helper import window, ADDON_ID
from ..helper import LazyLogger

##################################################################################################
Expand All @@ -27,7 +28,7 @@

class ContextMenu(xbmcgui.WindowXMLDialog):

_options = []
_options: List[str] = []
selected_option = None

def __init__(self, *args, **kwargs):
Expand All @@ -51,7 +52,7 @@
self.getControl(USER_IMAGE).setImage(window('JellyfinUserImage'))

LOG.info("options: %s", self._options)
self.list_ = self.getControl(LIST)
self.list_ = cast(xbmcgui.ControlList, self.getControl(LIST))

Check warning on line 55 in jellyfin_kodi/dialogs/context.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/dialogs/context.py#L55

Added line #L55 was not covered by tests

for option in self._options:
self.list_.addItem(self._add_listitem(option))
Expand All @@ -73,7 +74,7 @@

def _add_editcontrol(self, x, y, height, width, password=0):

media = os.path.join(xbmcaddon.Addon(addon_id()).getAddonInfo('path'), 'resources', 'skins', 'default', 'media')
media = os.path.join(xbmcaddon.Addon(ADDON_ID).getAddonInfo('path'), 'resources', 'skins', 'default', 'media')

Check warning on line 77 in jellyfin_kodi/dialogs/context.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/dialogs/context.py#L77

Added line #L77 was not covered by tests
control = xbmcgui.ControlImage(0, 0, 0, 0,
filename=os.path.join(media, "white.png"),
aspectRatio=0,
Expand Down
4 changes: 3 additions & 1 deletion jellyfin_kodi/dialogs/resume.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals

from typing import Optional

##################################################################################################

from kodi_six import xbmc, xbmcgui
Expand All @@ -22,7 +24,7 @@
class ResumeDialog(xbmcgui.WindowXMLDialog):

_resume_point = None
selected_option = None
selected_option: Optional[int] = None

def __init__(self, *args, **kwargs):
xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
Expand Down
4 changes: 3 additions & 1 deletion jellyfin_kodi/dialogs/serverconnect.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals

from typing import Any, Dict, List

##################################################################################################

from six import iteritems
Expand Down Expand Up @@ -32,7 +34,7 @@
class ServerConnect(xbmcgui.WindowXMLDialog):

user_image = None
servers = []
servers: List[Dict[str, Any]] = []

_selected_server = None
_connect_login = False
Expand Down
4 changes: 2 additions & 2 deletions jellyfin_kodi/entrypoint/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@

actions = Actions(server_id, api_client)
list_li = []
listing = listing if type(listing) == list else listing.get('Items', [])
listing = listing if isinstance(listing, list) else listing.get('Items', [])

Check warning on line 348 in jellyfin_kodi/entrypoint/default.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/entrypoint/default.py#L348

Added line #L348 was not covered by tests

for item in listing:

Expand Down Expand Up @@ -885,7 +885,7 @@
if xbmcvfs.exists(backup + '/'):
if not dialog("yesno", "{jellyfin}", translate(33090)):

return backup()
return backup

Check warning on line 888 in jellyfin_kodi/entrypoint/default.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/entrypoint/default.py#L888

Added line #L888 was not covered by tests

delete_folder(backup)

Expand Down
20 changes: 11 additions & 9 deletions jellyfin_kodi/entrypoint/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import sys
from datetime import datetime
from typing import Any, Dict

# Workaround for threads using datetime: _striptime is locked
import _strptime # noqa:F401
Expand Down Expand Up @@ -37,7 +38,7 @@
monitor = None
play_event = None
warn = True
settings = {'last_progress': datetime.today(), 'last_progress_report': datetime.today()}
settings: Dict[str, Any] = {'last_progress': datetime.today(), 'last_progress_report': datetime.today()}

def __init__(self):

Expand Down Expand Up @@ -264,17 +265,17 @@
window('jellyfin_should_stop.bool', True)
self.running = False

elif method in ('SyncLibrarySelection', 'RepairLibrarySelection', 'AddLibrarySelection', 'RemoveLibrarySelection'):
elif self.library_thread is not None and method in ('SyncLibrarySelection', 'RepairLibrarySelection', 'AddLibrarySelection', 'RemoveLibrarySelection'):
self.library_thread.select_libraries(method)

elif method == 'SyncLibrary':
elif self.library_thread is not None and method == 'SyncLibrary':
if not data.get('Id'):
return

self.library_thread.add_library(data['Id'], data.get('Update', False))
xbmc.executebuiltin("Container.Refresh")

elif method == 'RepairLibrary':
elif self.library_thread is not None and method == 'RepairLibrary':
if not data.get('Id'):
return

Expand All @@ -288,7 +289,7 @@
self.library_thread.add_library(data['Id'])
xbmc.executebuiltin("Container.Refresh")

elif method == 'RemoveLibrary':
elif self.library_thread is not None and method == 'RemoveLibrary':
libraries = data['Id'].split(',')

for lib in libraries:
Expand All @@ -309,10 +310,11 @@
self.library_thread = None

Jellyfin.close_all()
self.monitor.server = []
self.monitor.sleep = True
if self.monitor is not None:
self.monitor.server = []
self.monitor.sleep = True

Check warning on line 315 in jellyfin_kodi/entrypoint/service.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/entrypoint/service.py#L314-L315

Added lines #L314 - L315 were not covered by tests

elif method == 'System.OnWake':
elif self.monitor is not None and method == 'System.OnWake':

if not self.monitor.sleep:
LOG.warning("System.OnSleep was never called, skip System.OnWake")
Expand Down Expand Up @@ -365,7 +367,7 @@
self.settings['enable_context_transcode'] = settings('enableContextTranscode.bool')
LOG.info("New context transcode setting: %s", self.settings['enable_context_transcode'])

if settings('useDirectPaths') != self.settings['mode'] and self.library_thread.started:
if self.library_thread is not None and settings('useDirectPaths') != self.settings['mode'] and self.library_thread.started:

self.settings['mode'] = settings('useDirectPaths')
LOG.info("New playback mode setting: %s", self.settings['mode'])
Expand Down
5 changes: 3 additions & 2 deletions jellyfin_kodi/full_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from contextlib import contextmanager
import datetime
from typing import Any, Dict

from kodi_six import xbmc

Expand All @@ -29,8 +30,8 @@ class FullSync(object):
sync.libraries()
'''
# Borg - multiple instances, shared state
_shared_state = {}
sync = None
_shared_state: Dict[str, Any] = {}
sync = get_sync()
running = False
screensaver = None

Expand Down
2 changes: 1 addition & 1 deletion jellyfin_kodi/helper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from .translate import translate

from .utils import addon_id
from .utils import ADDON_ID
from .utils import window
from .utils import settings
from .utils import kodi_version
Expand Down
4 changes: 3 additions & 1 deletion jellyfin_kodi/helper/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals

from typing import Any, Dict, List

##################################################################################################

from . import settings, LazyLogger
Expand Down Expand Up @@ -42,7 +44,7 @@
return self.item['Name']

def get_actors(self):
cast = []
cast: List[Dict[str, Any]] = []

Check warning on line 47 in jellyfin_kodi/helper/api.py

View check run for this annotation

Codecov / codecov/patch

jellyfin_kodi/helper/api.py#L47

Added line #L47 was not covered by tests

if 'People' in self.item:
self.get_people_artwork(self.item['People'])
Expand Down
3 changes: 2 additions & 1 deletion jellyfin_kodi/helper/loghandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
import logging
import traceback
from typing import Dict, List

from six import ensure_text
from kodi_six import xbmc, xbmcaddon
Expand Down Expand Up @@ -36,7 +37,7 @@ def __init__(self):
logging.StreamHandler.__init__(self)
self.setFormatter(MyFormatter())

self.sensitive = {'Token': [], 'Server': []}
self.sensitive: Dict[str, List[str]] = {'Token': [], 'Server': []}

for server in database.get_credentials()['Servers']:

Expand Down
2 changes: 1 addition & 1 deletion jellyfin_kodi/helper/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def translate(string):

''' Get add-on string. Returns in unicode.
'''
if type(string) != int:
if not isinstance(string, int):
string = STRINGS[string]

result = xbmcaddon.Addon('plugin.video.jellyfin').getLocalizedString(string)
Expand Down
Loading
Loading