Skip to content
This repository was archived by the owner on Nov 27, 2024. It is now read-only.

Commit 97cbf11

Browse files
committed
lots of minor changes,
1 parent ef10080 commit 97cbf11

File tree

7 files changed

+55
-95
lines changed

7 files changed

+55
-95
lines changed

docs/api/utils.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ Utils
33
A collection of useful functions.
44

55
.. automodule:: codequick.utils
6-
:members:
6+
:members: keyboard, parse_qs, urljoin_partial, strip_tags, ensure_unicode

script.module.codequick/lib/codequick/listing.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
# Package imports
1616
from codequick.script import Script
1717
from codequick.support import auto_sort, build_path, logger_id, dispatcher
18-
from codequick.utils import ensure_unicode, ensure_native_str, unicode_type, long_type
18+
from codequick.utils import ensure_unicode, ensure_native_str, unicode_type, PY3
1919

20-
__all__ = ["Listitem", "Art", "Info", "Stream", "Context", "Property", "Params"]
20+
__all__ = ["Listitem"]
2121

2222
# Logger specific to this module
2323
logger = logging.getLogger("%s.listitem" % logger_id)
@@ -40,6 +40,7 @@
4040

4141
# Listing sort methods & sort mappings.
4242
# Skips infolables that have no sortmethod and type is string. As by default they will be string anyway
43+
# noinspection PyUnresolvedReferences
4344
infolable_map = {"artist": (None, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE),
4445
"studio": (ensure_native_str, xbmcplugin.SORT_METHOD_STUDIO_IGNORE_THE),
4546
"title": (ensure_native_str, xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE),
@@ -55,7 +56,7 @@
5556
"country": (ensure_native_str, xbmcplugin.SORT_METHOD_COUNTRY),
5657
"genre": (None, xbmcplugin.SORT_METHOD_GENRE),
5758
"date": (ensure_native_str, xbmcplugin.SORT_METHOD_DATE),
58-
"size": (long_type, xbmcplugin.SORT_METHOD_SIZE),
59+
"size": (int if PY3 else long, xbmcplugin.SORT_METHOD_SIZE),
5960
"sortepisode": (int, None),
6061
"sortseason": (int, None),
6162
"userrating": (int, None),
@@ -94,7 +95,10 @@ def __getitem__(self, key):
9495
return value.decode("utf8") if isinstance(value, bytes) else value
9596

9697
def __setitem__(self, key, value):
97-
self.raw_dict[key] = value
98+
if isinstance(value, bytes):
99+
self.raw_dict[key] = value.decode("utf8")
100+
else:
101+
self.raw_dict[key] = value
98102

99103
def __delitem__(self, key): # type: (str) -> None
100104
del self.raw_dict[key]
@@ -175,11 +179,14 @@ def global_thumb(self, image):
175179
# So there is no neeed to use ensure_native_str
176180
self.raw_dict["thumb"] = global_image.format(image)
177181

178-
def _close(self):
182+
def _close(self, isfolder):
179183
if fanart and "fanart" not in self.raw_dict: # pragma: no branch
180184
self.raw_dict["fanart"] = fanart
181185
if "thumb" not in self.raw_dict: # pragma: no branch
182186
self.raw_dict["thumb"] = icon
187+
if "icon" not in self.raw_dict: # pragma: no branch
188+
self.raw_dict["icon"] = "DefaultFolder.png" if isfolder else "DefaultVideo.png"
189+
183190
self._listitem.setArt(self.raw_dict)
184191

185192

@@ -300,7 +307,12 @@ def _duration(duration):
300307
return duration
301308

302309
def _close(self, content_type):
303-
self._listitem.setInfo(content_type, self.raw_dict)
310+
raw_dict = self.raw_dict
311+
# Add label as plot if no plot is found
312+
if "plot" not in raw_dict: # pragma: no branch
313+
raw_dict["plot"] = raw_dict["title"]
314+
315+
self._listitem.setInfo(content_type, raw_dict)
304316

305317

306318
class Property(Params):
@@ -527,7 +539,7 @@ def __init__(self, content_type="video"):
527539

528540
self.params = Params()
529541
"""
530-
Dictionary like object for parameters that will be passed to the "callback" object.
542+
Dictionary like object for parameters that will be passed to the "callback" function.
531543
532544
:example:
533545
>>> item = Listitem()
@@ -556,7 +568,8 @@ def label(self): # type: () -> str
556568
>>> item = Listitem()
557569
>>> item.label = "Video Title"
558570
"""
559-
return ensure_unicode(self.listitem.getLabel())
571+
label = self.listitem.getLabel()
572+
return label.decode("utf8") if isinstance(label, bytes) else label
560573

561574
@label.setter
562575
def label(self, label): # type: (str) -> None
@@ -596,15 +609,7 @@ def _close(self):
596609
path = callback
597610
isfolder = False
598611

599-
if isfolder:
600-
# Set Kodi icon image if not already set
601-
if "icon" not in self.art.raw_dict: # pragma: no branch
602-
self.art.raw_dict["icon"] = "DefaultFolder.png"
603-
else:
604-
# Set Kodi icon image if not already set
605-
if "icon" not in self.art.raw_dict: # pragma: no branch
606-
self.art.raw_dict["icon"] = "DefaultVideo.png"
607-
612+
if not isfolder:
608613
# Add mediatype if not already set
609614
if "mediatype" not in self.info.raw_dict and self._content_type in ("video", "music"): # pragma: no branch
610615
self.info.raw_dict["mediatype"] = self._content_type
@@ -616,21 +621,16 @@ def _close(self):
616621
# Close video related datasets
617622
self.stream._close()
618623

619-
label = self.label
620624
# Set label to UNKNOWN if unset
621-
if not label: # pragma: no branch
622-
self.label = label = u"UNKNOWN"
623-
624-
# Add label as plot if no plot is found
625-
if "plot" not in self.info: # pragma: no branch
626-
self.info["plot"] = label
625+
if not self.label: # pragma: no branch
626+
self.label = u"UNKNOWN"
627627

628628
# Close common datasets
629629
self.listitem.setPath(path)
630630
self.property._close()
631631
self.context._close()
632632
self.info._close(self._content_type)
633-
self.art._close()
633+
self.art._close(isfolder)
634634

635635
# Return a tuple compatible with 'xbmcplugin.addDirectoryItems'
636636
return path, self.listitem, isfolder

script.module.codequick/lib/codequick/support.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import xbmc
1717

1818
# Package imports
19-
from codequick.utils import parse_qs, ensure_native_str, urlparse
19+
from codequick.utils import parse_qs, ensure_native_str, urlparse, PY3
2020

2121
script_data = xbmcaddon.Addon("script.module.codequick")
2222
addon_data = xbmcaddon.Addon()
@@ -127,11 +127,10 @@ def args_to_kwargs(self, args, kwargs): # type: (tuple, dict) -> None
127127

128128
def arg_names(self): # type: () -> list
129129
"""Return a list of argument names, positional and keyword arguments."""
130-
try:
131-
# noinspection PyUnresolvedReferences
130+
if PY3:
132131
return inspect.getfullargspec(self.function).args
133-
except AttributeError:
134-
# "inspect.getargspec" is deprecated in python 3
132+
else:
133+
# noinspection PyDeprecation
135134
return inspect.getargspec(self.function).args
136135

137136
def unittest_caller(self, *args, **kwargs):
@@ -340,7 +339,8 @@ def build_path(callback=None, args=None, query=None, **extra_query):
340339

341340
# Encode the query parameters using json
342341
if query:
343-
query = "_pickle_=" + ensure_native_str(binascii.hexlify(pickle.dumps(query, protocol=pickle.HIGHEST_PROTOCOL)))
342+
pickled = binascii.hexlify(pickle.dumps(query, protocol=pickle.HIGHEST_PROTOCOL))
343+
query = "_pickle_=" + pickled.decode("ascii") if PY3 else pickled
344344

345345
# Build kodi url with new path and query parameters
346346
return urlparse.urlunsplit(("plugin", plugin_id, route.path, query, ""))

script.module.codequick/lib/codequick/utils.py

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,11 @@
1414
# noinspection PyUnresolvedReferences
1515
import urlparse
1616

17-
try:
18-
# noinspection PyUnresolvedReferences
19-
long_type = long
20-
except NameError:
21-
long_type = int
22-
2317
PY3 = sys.version_info[0] >= 3
2418

2519
# Unicode Type object, unicode on python2 or str on python3
2620
unicode_type = type(u"")
2721

28-
__all__ = ["keyboard", "parse_qs", "urljoin_partial", "strip_tags", "ensure_bytes",
29-
"ensure_native_str", "ensure_unicode", "unicode_type", "long_type"]
30-
3122

3223
def keyboard(heading, default="", hidden=False):
3324
"""
@@ -98,9 +89,9 @@ def parse_qs(qs, keep_blank_values=False, strict_parsing=False):
9889
raise ValueError("encountered duplicate param field name: '%s'" % key)
9990
else:
10091
for bkey, value in parsed:
101-
ukey = unicode_type(bkey, encoding="utf8")
92+
ukey = bkey.decode("utf8")
10293
if ukey not in params:
103-
params[ukey] = unicode_type(value, encoding="utf8")
94+
params[ukey] = value.decode("utf8")
10495
else:
10596
# Only add keys that are not already added, multiple values are not supported
10697
raise ValueError("encountered duplicate param field name: '%s'" % bkey)
@@ -163,20 +154,6 @@ def strip_tags(html):
163154
return re.sub("<[^<]+?>", "", html)
164155

165156

166-
def ensure_bytes(data, encoding="utf8"):
167-
"""
168-
Ensures that the given string is returned as type ``bytes``.
169-
170-
:type data: str or bytes
171-
:param data: String to convert if needed.
172-
:param str encoding: [opt] The encoding to use.
173-
174-
:returns: The given string as type ``bytes``
175-
:rtype: bytes
176-
"""
177-
return data if isinstance(data, bytes) else unicode_type(data).encode(encoding)
178-
179-
180157
def ensure_native_str(data, encoding="utf8"):
181158
"""
182159
Ensures that the given string is returned as a native str type, ``bytes`` on Python 2, ``unicode`` on Python 3.
@@ -186,6 +163,8 @@ def ensure_native_str(data, encoding="utf8"):
186163
:returns: The given string as a native ``str`` type.
187164
:rtype: str
188165
"""
166+
# This is the fastest way
167+
# that I can find to do this
189168
if isinstance(data, str):
190169
return data
191170
elif isinstance(data, unicode_type):
@@ -209,7 +188,4 @@ def ensure_unicode(data, encoding="utf8"):
209188
:returns: The given string as type ``unicode``.
210189
:rtype: str
211190
"""
212-
if isinstance(data, bytes):
213-
return data.decode(encoding)
214-
else:
215-
return unicode_type(data)
191+
return data.decode(encoding) if isinstance(data, bytes) else unicode_type(data)

tests/test_listing.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
from codequick import listing, route, resolver
44
from codequick.support import dispatcher
5-
from codequick.utils import unicode_type, long_type
5+
from codequick.utils import unicode_type
66
import xbmcgui
77
import xbmc
8+
import sys
9+
10+
PY3 = sys.version_info >= (3, 0)
811

912

1013
class TestGlobalLocalization(unittest.TestCase):
@@ -69,15 +72,18 @@ def test_close_without_extras(self):
6972
listing.fanart = "fanart"
7073
self.assertNotIn("thumb", self.base)
7174
self.assertNotIn("fanart", self.base)
72-
self.base._close()
75+
self.assertNotIn("icon", self.base)
76+
self.base._close(False)
7377
self.assertIn("thumb", self.base)
7478
self.assertIn("fanart", self.base)
79+
self.assertIn("icon", self.base)
7580

7681
def test_close_with_extras(self):
7782
listing.fanart = "fanart"
7883
self.base["fanart"] = ""
7984
self.base["thumb"] = ""
80-
self.base._close()
85+
self.base["icon"] = ""
86+
self.base._close(False)
8187
self.assertIn("thumb", self.base)
8288
self.assertIn("fanart", self.base)
8389

@@ -111,9 +117,15 @@ def test_duration_invalid(self):
111117
self.assertIsInstance(self.base["duration"], int)
112118
self.assertEqual(self.base["duration"], 330)
113119

114-
def test_size(self):
120+
@unittest.skipIf(PY3, "Size is an long in python2")
121+
def test_size_py2(self):
122+
self.base["size"] = "256816"
123+
self.assertIsInstance(self.base["size"], int)
124+
125+
@unittest.skipUnless(PY3, "Size is an int in python3")
126+
def test_size_py3(self):
115127
self.base["size"] = "256816"
116-
self.assertIsInstance(self.base["size"], long_type)
128+
self.assertIsInstance(self.base["size"], int)
117129

118130
def test_size_invalid(self):
119131
with self.assertRaises(TypeError):
@@ -142,6 +154,7 @@ def test_date(self):
142154
self.assertEqual(self.base["year"], "2017")
143155

144156
def test_close(self):
157+
self.base["plot"] = "plot"
145158
self.base._close("video")
146159

147160

tests/test_resolver.py

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -200,22 +200,3 @@ def test_extract_source_warning(self):
200200
YDStreamExtractor.mode = 4 # raise warning
201201
ret = self.resolver.extract_source("url")
202202
self.assertEqual(ret, "video.mkv")
203-
204-
def test_extract_youtube_url(self):
205-
ret = self.resolver.extract_youtube("https://www.watchmojo.com/video/id/20838/")
206-
self.assertEqual(ret, "plugin://plugin.video.youtube/play/?video_id=P3PvFiCibts")
207-
208-
def test_extract_youtube_source(self):
209-
source = urlquick.get("https://www.watchmojo.com/video/id/20838/").text
210-
ret = self.resolver.extract_youtube(source)
211-
self.assertEqual(ret, "plugin://plugin.video.youtube/play/?video_id=P3PvFiCibts")
212-
213-
def test_extract_youtube_node(self):
214-
html = urlquick.get("https://www.watchmojo.com/video/id/20838/")
215-
video_elem = html.parse("div", attrs={"id": "question"})
216-
ret = self.resolver.extract_youtube(video_elem)
217-
self.assertEqual(ret, "plugin://plugin.video.youtube/play/?video_id=P3PvFiCibts")
218-
219-
def test_extract_youtube_no_video(self):
220-
ret = self.resolver.extract_youtube("https://www.youtube.com/")
221-
self.assertIsNone(ret)

tests/test_utils.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,6 @@ def test_ensure_unicode_with_unicode(self):
1818
self.assertIsInstance(ret, utils.unicode_type)
1919
self.assertEqual(ret, u"teststring")
2020

21-
def test_ensure_bytes_with_bytes(self):
22-
ret = utils.ensure_bytes(b"teststring")
23-
self.assertIsInstance(ret, bytes)
24-
self.assertEqual(ret, b"teststring")
25-
26-
def test_ensure_bytes_with_unicode(self):
27-
ret = utils.ensure_bytes(u"teststring")
28-
self.assertIsInstance(ret, bytes)
29-
self.assertEqual(ret, b"teststring")
30-
3121
def test_ensure_native_str_with_bytes(self):
3222
ret = utils.ensure_native_str(b"teststring")
3323
self.assertIsInstance(ret, str)

0 commit comments

Comments
 (0)