Get rid of utils.try_encode and utils.try_decode

This commit is contained in:
croneter 2020-12-19 08:27:34 +01:00
parent d306f36869
commit 6904494e31
7 changed files with 27 additions and 78 deletions

View file

@ -91,7 +91,7 @@ class ContextMenu(object):
options.append(OPTIONS['Addon']) options.append(OPTIONS['Addon'])
context_menu = context.ContextMenu( context_menu = context.ContextMenu(
"script-plex-context.xml", "script-plex-context.xml",
utils.try_encode(v.ADDON_PATH), v.ADDON_PATH,
"default", "default",
"1080i") "1080i")
context_menu.set_options(options) context_menu.set_options(options)

View file

@ -284,7 +284,7 @@ def get_video_files(plex_id, params):
app.init(entrypoint=True) app.init(entrypoint=True)
item = PF.GetPlexMetadata(plex_id) item = PF.GetPlexMetadata(plex_id)
try: try:
path = utils.try_decode(item[0][0][0].attrib['file']) path = item[0][0][0].attrib['file']
except (TypeError, IndexError, AttributeError, KeyError): except (TypeError, IndexError, AttributeError, KeyError):
LOG.error('Could not get file path for item %s', plex_id) LOG.error('Could not get file path for item %s', plex_id)
return xbmcplugin.endOfDirectory(int(sys.argv[1])) return xbmcplugin.endOfDirectory(int(sys.argv[1]))
@ -300,15 +300,14 @@ def get_video_files(plex_id, params):
if path_ops.exists(path): if path_ops.exists(path):
for root, dirs, files in path_ops.walk(path): for root, dirs, files in path_ops.walk(path):
for directory in dirs: for directory in dirs:
item_path = utils.try_encode(path_ops.path.join(root, item_path = path_ops.path.join(root, directory)
directory))
listitem = ListItem(item_path, path=item_path) listitem = ListItem(item_path, path=item_path)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
url=item_path, url=item_path,
listitem=listitem, listitem=listitem,
isFolder=True) isFolder=True)
for file in files: for file in files:
item_path = utils.try_encode(path_ops.path.join(root, file)) item_path = path_ops.path.join(root, file)
listitem = ListItem(item_path, path=item_path) listitem = ListItem(item_path, path=item_path)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
url=file, url=file,
@ -353,18 +352,17 @@ def extra_fanart(plex_id, plex_path):
backdrops = api.artwork()['Backdrop'] backdrops = api.artwork()['Backdrop']
for count, backdrop in enumerate(backdrops): for count, backdrop in enumerate(backdrops):
# Same ordering as in artwork # Same ordering as in artwork
art_file = utils.try_encode(path_ops.path.join( art_file = path_ops.path.join(fanart_dir, "fanart%.3d.jpg" % count)
fanart_dir, "fanart%.3d.jpg" % count))
listitem = ListItem("%.3d" % count, path=art_file) listitem = ListItem("%.3d" % count, path=art_file)
xbmcplugin.addDirectoryItem( xbmcplugin.addDirectoryItem(
handle=int(sys.argv[1]), handle=int(sys.argv[1]),
url=art_file, url=art_file,
listitem=listitem) listitem=listitem)
path_ops.copyfile(backdrop, utils.try_decode(art_file)) path_ops.copyfile(backdrop, art_file)
else: else:
LOG.info("Found cached backdrop.") LOG.info("Found cached backdrop.")
# Use existing cached images # Use existing cached images
fanart_dir = utils.try_decode(fanart_dir) fanart_dir = fanart_dir
for root, _, files in path_ops.walk(fanart_dir): for root, _, files in path_ops.walk(fanart_dir):
root = utils.decode_path(root) root = utils.decode_path(root)
for file in files: for file in files:

View file

@ -528,13 +528,13 @@ def process_indirect(key, offset, resolve=True):
return return
item.file = playurl item.file = playurl
listitem.setPath(utils.try_encode(playurl)) listitem.setPath(playurl)
playqueue.items.append(item) playqueue.items.append(item)
if resolve is True: if resolve is True:
transfer.send(listitem) transfer.send(listitem)
else: else:
thread = Thread(target=app.APP.player.play, thread = Thread(target=app.APP.player.play,
args={'item': utils.try_encode(playurl), args={'item': playurl,
'listitem': listitem}) 'listitem': listitem})
thread.setDaemon(True) thread.setDaemon(True)
LOG.debug('Done initializing PKC playback, starting Kodi player') LOG.debug('Done initializing PKC playback, starting Kodi player')

View file

@ -303,11 +303,11 @@ def _plex_gdm():
} }
for line in response['data'].split('\n'): for line in response['data'].split('\n'):
if 'Content-Type:' in line: if 'Content-Type:' in line:
pms['product'] = utils.try_decode(line.split(':')[1].strip()) pms['product'] = line.split(':')[1].strip()
elif 'Host:' in line: elif 'Host:' in line:
pms['baseURL'] = line.split(':')[1].strip() pms['baseURL'] = line.split(':')[1].strip()
elif 'Name:' in line: elif 'Name:' in line:
pms['name'] = utils.try_decode(line.split(':')[1].strip()) pms['name'] = line.split(':')[1].strip()
elif 'Port:' in line: elif 'Port:' in line:
pms['port'] = line.split(':')[1].strip() pms['port'] = line.split(':')[1].strip()
elif 'Resource-Identifier:' in line: elif 'Resource-Identifier:' in line:

View file

@ -100,13 +100,12 @@ def window(prop, value=None, clear=False, windowid=10000):
win = xbmcgui.Window(windowid) win = xbmcgui.Window(windowid)
else: else:
win = WINDOW win = WINDOW
if clear: if clear:
win.clearProperty(prop) win.clearProperty(prop)
elif value is not None: elif value is not None:
win.setProperty(try_encode(prop), try_encode(value)) win.setProperty(prop, value)
else: else:
return try_decode(win.getProperty(prop)) return win.getProperty(prop)
def settings(setting, value=None): def settings(setting, value=None):
@ -120,10 +119,10 @@ def settings(setting, value=None):
addon = xbmcaddon.Addon(id='plugin.video.plexkodiconnect') addon = xbmcaddon.Addon(id='plugin.video.plexkodiconnect')
if value is not None: if value is not None:
# Takes string or unicode by default! # Takes string or unicode by default!
addon.setSetting(try_encode(setting), try_encode(value)) addon.setSetting(setting, value)
else: else:
# Should return unicode by default, but just in case # Should return unicode by default, but just in case
return try_decode(addon.getSetting(setting)) return addon.getSetting(setting)
def lang(stringid): def lang(stringid):
@ -424,38 +423,6 @@ def unquote(s):
return urllib.parse.unquote(s) return urllib.parse.unquote(s)
def try_encode(input_str, encoding='utf-8'):
"""
Will try to encode input_str (in unicode) to encoding. This possibly
fails with e.g. Android TV's Python, which does not accept arguments for
string.encode()
"""
if isinstance(input_str, str):
# already encoded
return input_str
try:
input_str = input_str.encode(encoding, "ignore")
except TypeError:
input_str = input_str.encode()
return input_str
def try_decode(string, encoding='utf-8'):
"""
Will try to decode string (encoded) using encoding. This possibly
fails with e.g. Android TV's Python, which does not accept arguments for
string.encode()
"""
if isinstance(string, str):
# already decoded
return string
try:
string = string.decode(encoding, "ignore")
except TypeError:
string = string.decode()
return string
def slugify(text): def slugify(text):
""" """
Normalizes text (in unicode or string) to e.g. enable safe filenames. Normalizes text (in unicode or string) to e.g. enable safe filenames.

View file

@ -14,22 +14,6 @@ from . import path_ops
# For any file operations with KODI function, use encoded strings! # For any file operations with KODI function, use encoded strings!
def try_decode(string, encoding='utf-8'):
"""
Will try to decode string (encoded) using encoding. This possibly
fails with e.g. Android TV's Python, which does not accept arguments for
string.encode()
"""
if isinstance(string, str):
# already decoded
return string
try:
string = string.decode(encoding, "ignore")
except TypeError:
string = string.decode()
return string
# Percent of playback progress for watching item as partially watched. Anything # Percent of playback progress for watching item as partially watched. Anything
# more and item will NOT be marked as partially, but fully watched # more and item will NOT be marked as partially, but fully watched
MARK_PLAYED_AT = 0.9 MARK_PLAYED_AT = 0.9
@ -41,14 +25,14 @@ _ADDON = Addon()
ADDON_NAME = 'PlexKodiConnect' ADDON_NAME = 'PlexKodiConnect'
ADDON_ID = 'plugin.video.plexkodiconnect' ADDON_ID = 'plugin.video.plexkodiconnect'
ADDON_VERSION = _ADDON.getAddonInfo('version') ADDON_VERSION = _ADDON.getAddonInfo('version')
ADDON_PATH = try_decode(_ADDON.getAddonInfo('path')) ADDON_PATH = _ADDON.getAddonInfo('path')
ADDON_FOLDER = try_decode(xbmcvfs.translatePath('special://home')) ADDON_FOLDER = xbmcvfs.translatePath('special://home')
ADDON_PROFILE = try_decode(xbmcvfs.translatePath(_ADDON.getAddonInfo('profile'))) ADDON_PROFILE = xbmcvfs.translatePath(_ADDON.getAddonInfo('profile'))
KODILANGUAGE = xbmc.getLanguage(xbmc.ISO_639_1) KODILANGUAGE = xbmc.getLanguage(xbmc.ISO_639_1)
KODIVERSION = int(xbmc.getInfoLabel("System.BuildVersion")[:2]) KODIVERSION = int(xbmc.getInfoLabel("System.BuildVersion")[:2])
KODILONGVERSION = xbmc.getInfoLabel('System.BuildVersion') KODILONGVERSION = xbmc.getInfoLabel('System.BuildVersion')
KODI_PROFILE = try_decode(xbmcvfs.translatePath("special://profile")) KODI_PROFILE = xbmcvfs.translatePath("special://profile")
if xbmc.getCondVisibility('system.platform.osx'): if xbmc.getCondVisibility('system.platform.osx'):
DEVICE = "MacOSX" DEVICE = "MacOSX"
@ -78,9 +62,9 @@ except IOError:
# See https://github.com/psf/requests/issues/4434 # See https://github.com/psf/requests/issues/4434
MODEL = 'Unknown' MODEL = 'Unknown'
DEVICENAME = try_decode(_ADDON.getSetting('deviceName')) DEVICENAME = _ADDON.getSetting('deviceName')
if not DEVICENAME: if not DEVICENAME:
DEVICENAME = try_decode(xbmc.getInfoLabel('System.FriendlyName')) DEVICENAME = xbmc.getInfoLabel('System.FriendlyName')
_ADDON.setSetting('deviceName', DEVICENAME) _ADDON.setSetting('deviceName', DEVICENAME)
DEVICENAME = DEVICENAME.replace(":", "") DEVICENAME = DEVICENAME.replace(":", "")
DEVICENAME = DEVICENAME.replace("/", "-") DEVICENAME = DEVICENAME.replace("/", "-")
@ -121,11 +105,11 @@ DB_MUSIC_VERSION = None
DB_MUSIC_PATH = None DB_MUSIC_PATH = None
DB_TEXTURE_VERSION = None DB_TEXTURE_VERSION = None
DB_TEXTURE_PATH = None DB_TEXTURE_PATH = None
DB_PLEX_PATH = try_decode(xbmcvfs.translatePath("special://database/plex.db")) DB_PLEX_PATH = xbmcvfs.translatePath("special://database/plex.db")
DB_PLEX_COPY_PATH = try_decode(xbmcvfs.translatePath("special://database/plex-copy.db")) DB_PLEX_COPY_PATH = xbmcvfs.translatePath("special://database/plex-copy.db")
EXTERNAL_SUBTITLE_TEMP_PATH = try_decode(xbmcvfs.translatePath( EXTERNAL_SUBTITLE_TEMP_PATH = xbmcvfs.translatePath(
"special://profile/addon_data/%s/temp/" % ADDON_ID)) "special://profile/addon_data/%s/temp/" % ADDON_ID)
# Multiply Plex time by this factor to receive Kodi time # Multiply Plex time by this factor to receive Kodi time
@ -699,7 +683,7 @@ def database_paths():
if KODIVERSION not in (19, ): if KODIVERSION not in (19, ):
raise RuntimeError('Kodiversion %s not supported by PKC' % KODIVERSION) raise RuntimeError('Kodiversion %s not supported by PKC' % KODIVERSION)
database_path = try_decode(xbmcvfs.translatePath('special://database')) database_path = xbmcvfs.translatePath('special://database')
thismodule = sys.modules[__name__] thismodule = sys.modules[__name__]
types = (('MyVideos%s.db', SUPPORTED_VIDEO_DB, types = (('MyVideos%s.db', SUPPORTED_VIDEO_DB,
'DB_VIDEO_VERSION', 'DB_VIDEO_PATH'), 'DB_VIDEO_VERSION', 'DB_VIDEO_PATH'),

View file

@ -309,7 +309,7 @@ class ABNF(object):
opcode: operation code. please see OPCODE_XXX. opcode: operation code. please see OPCODE_XXX.
""" """
if opcode == ABNF.OPCODE_TEXT and isinstance(data, str): if opcode == ABNF.OPCODE_TEXT and isinstance(data, str):
data = utils.try_encode(data) data = data.encode()
# mask must be set if send data from client # mask must be set if send data from client
return ABNF(1, 0, 0, 0, opcode, 1, data) return ABNF(1, 0, 0, 0, opcode, 1, data)