Remove six: string coercion

This commit is contained in:
Odd Stråbø 2024-06-11 04:46:20 +00:00
parent 0e5c5e4c07
commit 57ed8bdedd
8 changed files with 17 additions and 34 deletions

View file

@ -11,7 +11,6 @@ import sys
import re import re
from kodi_six import xbmc, xbmcvfs from kodi_six import xbmc, xbmcvfs
from six import text_type
from . import jellyfin_db from . import jellyfin_db
from ..helper import translate, settings, window, dialog from ..helper import translate, settings, window, dialog
@ -362,7 +361,7 @@ def save_sync(sync):
with open(os.path.join(ADDON_DATA, "sync.json"), "wb") as outfile: with open(os.path.join(ADDON_DATA, "sync.json"), "wb") as outfile:
data = json.dumps(sync, sort_keys=True, indent=4, ensure_ascii=False) data = json.dumps(sync, sort_keys=True, indent=4, ensure_ascii=False)
if isinstance(data, text_type): if isinstance(data, str):
data = data.encode("utf-8") data = data.encode("utf-8")
outfile.write(data) outfile.write(data)
@ -411,7 +410,7 @@ def save_credentials(credentials):
try: try:
with open(os.path.join(ADDON_DATA, "data.json"), "wb") as outfile: with open(os.path.join(ADDON_DATA, "data.json"), "wb") as outfile:
data = json.dumps(credentials, sort_keys=True, indent=4, ensure_ascii=False) data = json.dumps(credentials, sort_keys=True, indent=4, ensure_ascii=False)
if isinstance(data, text_type): if isinstance(data, str):
data = data.encode("utf-8") data = data.encode("utf-8")
outfile.write(data) outfile.write(data)
except Exception: except Exception:

View file

@ -6,7 +6,6 @@ from __future__ import division, absolute_import, print_function, unicode_litera
import os import os
from kodi_six import xbmcgui, xbmcaddon 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 from ..helper import LazyLogger
@ -69,7 +68,7 @@ class ContextMenu(xbmcgui.WindowXMLDialog):
): ):
option = self.list_.getSelectedItem() option = self.list_.getSelectedItem()
self.selected_option = ensure_text(option.getLabel()) self.selected_option = option.getLabel()
LOG.info("option selected: %s", self.selected_option) LOG.info("option selected: %s", self.selected_option)
self.close() self.close()

View file

@ -7,11 +7,10 @@ import os
import logging import logging
import traceback import traceback
from six import ensure_text
from kodi_six import xbmc, xbmcaddon from kodi_six import xbmc, xbmcaddon
from .. import database from .. import database
from . import get_filesystem_encoding, settings, kodi_version from . import settings, kodi_version
from .utils import translate_path from .utils import translate_path
################################################################################################## ##################################################################################################
@ -92,9 +91,6 @@ class MyFormatter(logging.Formatter):
logging.Formatter.__init__(self, fmt) logging.Formatter.__init__(self, fmt)
def format(self, record): def format(self, record):
if record.pathname:
record.pathname = ensure_text(record.pathname, get_filesystem_encoding())
self._gen_rel_path(record) self._gen_rel_path(record)
# Call the original formatter class to do the grunt work # Call the original formatter class to do the grunt work
@ -107,8 +103,6 @@ class MyFormatter(logging.Formatter):
res = [] res = []
for o in traceback.format_exception(*exc_info): for o in traceback.format_exception(*exc_info):
o = ensure_text(o, get_filesystem_encoding())
if o.startswith(' File "'): if o.startswith(' File "'):
# If this split can't handle your file names, you should seriously consider renaming your files. # If this split can't handle your file names, you should seriously consider renaming your files.
fn = o.split(' File "', 2)[1].split('", line ', 1)[0] fn = o.split(' File "', 2)[1].split('", line ', 1)[0]

View file

@ -13,7 +13,6 @@ from uuid import uuid4
from urllib.parse import quote_plus from urllib.parse import quote_plus
from dateutil import tz, parser from dateutil import tz, parser
from six import text_type, string_types, ensure_text, ensure_binary
from kodi_six import xbmc, xbmcaddon, xbmcgui, xbmcvfs from kodi_six import xbmc, xbmcaddon, xbmcgui, xbmcvfs
@ -120,7 +119,7 @@ def event(method, data=None, sender=None, hexlify=False):
sender = sender or "plugin.video.jellyfin" sender = sender or "plugin.video.jellyfin"
if hexlify: if hexlify:
data = ensure_text(binascii.hexlify(ensure_binary(json.dumps(data)))) data = str(binascii.hexlify(json.dumps(data).encode()))
data = '"[%s]"' % json.dumps(data).replace('"', '\\"') data = '"[%s]"' % json.dumps(data).replace('"', '\\"')
@ -273,7 +272,7 @@ def values(item, keys):
return ( return (
( (
item[key.replace("{", "").replace("}", "")] item[key.replace("{", "").replace("}", "")]
if isinstance(key, text_type) and key.startswith("{") if isinstance(key, str) and key.startswith("{")
else key else key
) )
for key in keys for key in keys
@ -423,9 +422,7 @@ def normalize_string(text):
text = text.strip() text = text.strip()
text = text.rstrip(".") text = text.rstrip(".")
text = unicodedata.normalize("NFKD", text_type(text, "utf-8")).encode( text = unicodedata.normalize("NFKD", str(text, "utf-8")).encode("ascii", "ignore")
"ascii", "ignore"
)
return text return text
@ -438,7 +435,7 @@ def split_list(itemlist, size):
def convert_to_local(date, timezone=tz.tzlocal()): def convert_to_local(date, timezone=tz.tzlocal()):
"""Convert the local datetime to local.""" """Convert the local datetime to local."""
try: try:
date = parser.parse(date) if isinstance(date, string_types) else date date = parser.parse(date) if isinstance(date, str) else date
date = date.replace(tzinfo=tz.tzutc()) date = date.replace(tzinfo=tz.tzutc())
date = date.astimezone(timezone) date = date.astimezone(timezone)
# Bad metadata defaults to date 1-1-1. Catch it and don't throw errors # Bad metadata defaults to date 1-1-1. Catch it and don't throw errors

View file

@ -4,7 +4,6 @@ from __future__ import division, absolute_import, print_function, unicode_litera
import json import json
import requests import requests
from six import ensure_str
from ..helper.exceptions import HTTPException from ..helper.exceptions import HTTPException
from ..helper.utils import settings from ..helper.utils import settings
@ -416,7 +415,7 @@ class API(object):
"User-Agent": self.config.data["http.user_agent"] "User-Agent": self.config.data["http.user_agent"]
or "%s/%s" or "%s/%s"
% (self.config.data["app.name"], self.config.data["app.version"]), % (self.config.data["app.name"], self.config.data["app.version"]),
"x-emby-authorization": ensure_str(auth, "utf-8"), "x-emby-authorization": auth,
} }
def send_request( def send_request(

View file

@ -6,7 +6,6 @@ from __future__ import division, absolute_import, print_function, unicode_litera
import time import time
import requests import requests
from six import string_types, ensure_str
from ..helper.utils import JsonDebugPrinter from ..helper.utils import JsonDebugPrinter
from ..helper import LazyLogger from ..helper import LazyLogger
@ -218,7 +217,7 @@ class HTTP(object):
if isinstance(value, dict): if isinstance(value, dict):
self._process_params(value) self._process_params(value)
if isinstance(value, string_types): if isinstance(value, str):
params[key] = self._replace_user_info(value) params[key] = self._replace_user_info(value)
def _get_header(self, data): def _get_header(self, data):
@ -257,14 +256,14 @@ class HTTP(object):
) )
auth += "Version=%s" % self.config.data.get("app.version", "0.0.0") auth += "Version=%s" % self.config.data.get("app.version", "0.0.0")
data["headers"].update({"x-emby-authorization": ensure_str(auth, "utf-8")}) data["headers"].update({"x-emby-authorization": auth})
if self.config.data.get("auth.token") and self.config.data.get("auth.user_id"): if self.config.data.get("auth.token") and self.config.data.get("auth.user_id"):
auth += ", UserId=%s" % self.config.data.get("auth.user_id") auth += ", UserId=%s" % self.config.data.get("auth.user_id")
data["headers"].update( data["headers"].update(
{ {
"x-emby-authorization": ensure_str(auth, "utf-8"), "x-emby-authorization": auth,
"X-MediaBrowser-Token": self.config.data.get("auth.token"), "X-MediaBrowser-Token": self.config.data.get("auth.token"),
} }
) )

View file

@ -1,14 +1,12 @@
from collections import namedtuple from collections import namedtuple
from collections.abc import Iterable, Mapping, MutableMapping from collections.abc import Iterable, Mapping, MutableMapping
from six import string_types
def clean_none_dict_values(obj): def clean_none_dict_values(obj):
""" """
Recursively remove keys with a value of None Recursively remove keys with a value of None
""" """
if not isinstance(obj, Iterable) or isinstance(obj, string_types): if not isinstance(obj, Iterable) or isinstance(obj, str):
return obj return obj
queue = [obj] queue = [obj]
@ -24,7 +22,7 @@ def clean_none_dict_values(obj):
if value is None and mutable: if value is None and mutable:
remove.append(key) remove.append(key)
elif isinstance(value, string_types): elif isinstance(value, str):
continue continue
elif isinstance(value, Iterable): elif isinstance(value, Iterable):
@ -37,7 +35,7 @@ def clean_none_dict_values(obj):
elif isinstance(item, Iterable): elif isinstance(item, Iterable):
for value in item: for value in item:
if value is None or isinstance(value, string_types): if value is None or isinstance(value, str):
continue continue
elif isinstance(value, Iterable): elif isinstance(value, Iterable):
queue.append(value) queue.append(value)

View file

@ -6,9 +6,7 @@ from __future__ import division, absolute_import, print_function, unicode_litera
import json import json
import os import os
from six import ensure_text from ..helper import LazyLogger
from ..helper import LazyLogger, get_filesystem_encoding
################################################################################################## ##################################################################################################
@ -29,7 +27,7 @@ class Objects(object):
def mapping(self): def mapping(self):
"""Load objects mapping.""" """Load objects mapping."""
file_dir = os.path.dirname(ensure_text(__file__, get_filesystem_encoding())) file_dir = os.path.dirname(__file__)
with open(os.path.join(file_dir, "obj_map.json")) as infile: with open(os.path.join(file_dir, "obj_map.json")) as infile:
self.objects = json.load(infile) self.objects = json.load(infile)