Skip to content

Commit 8c32ea5

Browse files
committed
Minor changes
fix style fix tests add exponential back-off to login
1 parent 4cdbc19 commit 8c32ea5

6 files changed

Lines changed: 59 additions & 47 deletions

File tree

pythonbits/__main__.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,6 @@ def n_to_p(x): return "--" + x.replace('_', '-')
103103
set_field['title_arg'] = args.title
104104
get_field = args.fields + args.fields_ex
105105

106-
if sys.version_info[0] == 2: # PY2. Please die already.
107-
for k, v in set_field.items():
108-
set_field[k] = v.decode('utf8')
109-
110106
return Category, set_field, get_field
111107

112108

pythonbits/bb.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from . import templating as bb
2424
from .submission import (Submission, form_field, finalize,
2525
SubmissionAttributeError)
26-
from .tracker import Tracker, TrackerException
26+
from .tracker import Tracker
2727
from .scene import is_scene_crc, query_scene_fname
2828

2929

@@ -249,7 +249,6 @@ def _render_tv_specifier(self):
249249
return TvSpecifier(title, guess['season'],
250250
guess.get('episode', None))
251251

252-
253252
@form_field('tags')
254253
def _render_tags(self):
255254
# todo: get episode-specific actors (from imdb?)
@@ -269,7 +268,8 @@ def _render_mediainfo_path(self):
269268
contained_files = []
270269
for dp, dns, fns in os.walk(self['path']):
271270
contained_files += [os.path.join(dp, fn) for fn in fns
272-
if os.path.getsize(os.path.join(dp, fn)) > 10 * 2**20]
271+
if (os.path.getsize(os.path.join(dp, fn))
272+
> 10 * 2**20)]
273273
if len(contained_files) == 1:
274274
return contained_files[0]
275275

@@ -359,16 +359,14 @@ def _render_source(self):
359359
# TC, SDTV, DVD5, DVD9, HD-DVD
360360

361361
# todo: replace with guess from self['guess']
362-
if ('bluray' in self['path'].lower() or
363-
'blu-ray' in self['path'].lower()):
364-
return 'BluRay'
365-
# todo: 3d
366-
elif ('web-dl' in self['path'].lower() or
367-
'webdl' in self['path'].lower()):
362+
regpath = self['path'].lower().strip('-')
363+
if 'bluray' in regpath:
364+
return 'BluRay' # todo: 3d
365+
elif 'webdl' in regpath:
368366
return 'WEB-DL'
369-
elif 'webrip' in self['path'].lower():
367+
elif 'webrip' in regpath:
370368
return 'WebRip'
371-
elif 'hdtv' in self['path'].lower():
369+
elif 'hdtv' in regpath:
372370
return 'HDTV'
373371
# elif 'dvdscr' in self['path'].lower():
374372
# markers['source'] = 'DVDSCR'
@@ -393,14 +391,15 @@ def _render_container(self):
393391
elif general['format'] == 'BDAV':
394392
return 'm2ts'
395393
else:
396-
raise Exception("Unknown or unsupported container: %r" % (general.format,))
394+
raise RuntimeError("Unknown or unsupported container '{}'".format(
395+
general.format))
397396

398397
def _render_video_codec(self):
399398
video_track = self['tracks']['video']
400399
# norm_bitrate = (float(bit_rate) /
401400
# (video_track.width*video_track.height))
402401
if (video_track['codec_id'] in ('V_MPEG4/ISO/AVC', 'AVC', 'avc1') or
403-
video_track['format'] == 'AVC'):
402+
video_track['format'] == 'AVC'):
404403
if 'x264' in video_track.get('writing_library', ''):
405404
return 'x264'
406405
else:
@@ -419,14 +418,15 @@ def _render_video_codec(self):
419418
elif video_track['format'] == 'MPEG Video':
420419
return 'MPEG-2'
421420
else:
422-
raise Exception("Unknown or unsupported video codec: %r, %r" %
423-
(video_track.get('codec_id', '[NO CODEC]'),
424-
video_track.get('writing_library', '[NO LIBRARY]')))
421+
msg = "Unknown or unsupported video codec '{}' ({})".format(
422+
video_track.get('codec_id'),
423+
video_track.get('writing_library'))
424+
raise RuntimeError(msg)
425425

426426
def _render_audio_codec(self):
427427
audio_track = self['tracks']['audio'][0] # main audio track
428428
if (audio_track.get('codec_id_hint') == 'MP3' or
429-
audio_track['codec_id'] in ('MPA1L3', '55')):
429+
audio_track['codec_id'] in ('MPA1L3', '55')):
430430
return 'MP3'
431431
elif audio_track['codec_id'].lower().startswith('mp4a'):
432432
return 'AAC'
@@ -439,19 +439,21 @@ def _render_audio_codec(self):
439439

440440
if audio_track['codec_id'].startswith('A_'):
441441
audio_track['codec_id'] = audio_track['codec_id'][2:]
442-
audio_codecs = ('AC3', 'EAC3', 'DTS', 'FLAC', 'AAC', 'MP3', 'TRUEHD', 'PCM')
442+
audio_codecs = ('AC3', 'EAC3', 'DTS', 'FLAC', 'AAC', 'MP3', 'TRUEHD',
443+
'PCM')
443444
for c in audio_codecs:
444445
if audio_track['codec_id'].startswith(c):
445446
c = c.replace('EAC3', 'AC-3') \
446447
.replace('AC3', 'AC-3') \
447448
.replace('TRUEHD', 'True-HD')
448449
return c
449450

450-
raise Exception("Unknown or unsupported audio codec: %r" %
451-
(audio_track['codec_id'],))
451+
raise ValueError("Unknown or unsupported audio codec '{}'".format(
452+
audio_track['codec_id']))
452453

453454
def _render_resolution(self):
454-
resolutions = ('2160p', '1080p', '720p', '1080i', '720i', '480p', '480i', 'SD')
455+
resolutions = ('2160p', '1080p', '720p', '1080i', '720i',
456+
'480p', '480i', 'SD')
455457

456458
# todo: replace with regex?
457459
# todo: compare result with mediainfo
@@ -594,7 +596,7 @@ def imdb_link(r):
594596
[b]Writer(s)[/b]: {writers}
595597
[b]Content rating[/b]: {contentrating}""").format(
596598
title=s['episode_title'],
597-
links=", ".join(bb.link(*l) for l in links),
599+
links=", ".join(bb.link(*l) for l in links), # noqa: E741
598600
air_date=s['air_date'],
599601
network=s['network'],
600602
rating=rating_bb,
@@ -713,7 +715,7 @@ def imdb_link(r):
713715
[b]Director(s)[/b]: {directors}
714716
[b]Writer(s)[/b]: {writers}
715717
[b]Cast[/b]: {cast}""").format(
716-
links=", ".join(bb.link(*l) for l in links),
718+
links=", ".join(bb.link(*l) for l in links), # noqa: E741
717719
name=summary['name'],
718720
mpaa=summary['mpaa'],
719721
rating=bb.format_rating(summary['rating'][0],

pythonbits/submission.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,6 @@ def confirm_finalization(self, fields):
276276

277277
new_value = rlinput("New (empty to cancel): ", val)
278278

279-
if sys.version_info[0] == 2: # PY2 compatibility
280-
new_value = new_value.decode('utf8')
281-
282279
if new_value:
283280
if isinstance(val, bool):
284281
string_true = {'true', 'True', 'y', 'yes'}

pythonbits/tracker.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import requests
33
import contextlib
44
import re
5+
import time
56

67
from . import __version__ as version, __title__ as title
78
from .config import config
@@ -23,6 +24,8 @@ class Tracker():
2324
headers = {'User-Agent': '{}/{}'.format(title, version)}
2425

2526
def _login(self, session, _tries=0):
27+
maxtries = 10
28+
2629
domain = config.get('Tracker', 'domain')
2730
login_url = "https://{}/login.php".format(domain)
2831
payload = {'username': config.get('Tracker', 'username'),
@@ -37,21 +40,29 @@ def _login(self, session, _tries=0):
3740
if 'id="loginform"' in resp.text:
3841
raise TrackerException("Login failed")
3942
elif 'You are banned' in resp.text:
40-
raise TrackerException("Login failed (login attempts exceeded)")
43+
raise TrackerException(
44+
"Login failed (login attempts exceeded)")
4145
else:
4246
# We encountered the login bug that sends you to "/" (which
4347
# doesn't contain the login form) without logging you in
44-
if _tries < 10:
45-
log.debug('Encountered login bug; trying again')
48+
# todo: convert this to a retry decorator
49+
if _tries < maxtries:
50+
backoff = min(10**_tries/1000, 16.)
51+
log.debug('Encountered login bug; trying again after '
52+
'{}s back-off'.format(backoff))
53+
time.sleep(backoff)
4654
self._login(session, _tries=_tries+1)
4755
else:
48-
log.debug('Encountered login bug; giving up after 10 login attempts')
56+
log.debug('Encountered login bug; '
57+
'giving up after '
58+
'{} login attempts'.format(_tries))
4959
raise TrackerException("Login failed")
5060
elif 'logout.php' in resp.text:
5161
# Login successful, find and remember logout URL
5262
match = re.search(r"logout\.php\?auth=[0-9a-f]{32}", resp.text)
5363
if match:
54-
self._logout_url = "https://{}/{}".format(domain, match.group(0))
64+
self._logout_url = "https://{}/{}".format(
65+
domain, match.group(0))
5566
else:
5667
raise TrackerException("Couldn't find logout URL")
5768
else:
@@ -90,17 +101,19 @@ def upload(self, **kwargs):
90101
resp.raise_for_status()
91102

92103
# TODO: Catch this somehow:
93-
# <p style="color: red;text-align:center;">You must enter at least one tag. Maximum length is 200 characters.</p>
104+
# <p style="color: red;text-align:center;">You must enter at least
105+
# one tag. Maximum length is 200 characters.</p>
94106

95107
if resp.history:
96108
# todo: check if url is good, might have been logged out
97109
# (unlikely)
98110
return resp.url
99111
else:
100112
log.error('Response: %s' % resp)
101-
err_match = re.search(r''.join((r'(No torrent file uploaded.*?)',
102-
re.escape(r'</p>'))),
103-
resp.text)
113+
err_match = re.search(r''.join(
114+
(r'(No torrent file uploaded.*?)',
115+
re.escape(r'</p>'))),
116+
resp.text)
104117
if err_match:
105118
log.error('Error: %s' % err_match.group(1))
106119
else:

pythonbits/tvdb.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,18 @@ def get_rating(banner):
2222

2323
try:
2424
season_banners = self.show['_banners']['season']
25-
best_banner = best_banner([banner for banner in season_banners['raw']
26-
if banner['subKey'] == str(season_number)])
27-
return season_banners[best_banner['resolution']][best_banner['id']]['_bannerpath']
25+
best_banner = best_banner(
26+
[banner for banner in season_banners['raw']
27+
if banner['subKey'] == str(season_number)])
28+
return (season_banners[best_banner['resolution']]
29+
[best_banner['id']]['_bannerpath'])
2830
except (IndexError, KeyError):
2931
for key in ('poster', 'series', 'fanart'):
3032
try:
3133
series_banners = self.show['_banners'][key]
3234
best_banner = best_banner(series_banners['raw'])
33-
return series_banners[best_banner['resolution']][best_banner['id']]['_bannerpath']
35+
return (series_banners[best_banner['resolution']]
36+
[best_banner['id']]['_bannerpath'])
3437
except (IndexError, KeyError):
3538
pass
3639
raise Exception('Unable to find cover')
@@ -61,8 +64,8 @@ def add_show_titles(self, summary):
6164
summary['title'] = imdb_sum['title']
6265
# dict of international titles
6366
summary['titles'] = imdb_sum['titles']
64-
# "XWW" is IMDb's international title, but unlike TVDB, it doesn't include the
65-
# year if there are multiple shows with the same name.
67+
# "XWW" is IMDb's international title, but unlike TVDB, it doesn't
68+
# include the year if there are multiple shows with the same name.
6669
if 'XWW' in summary['titles']:
6770
summary['titles']['XWW'] = tvdb_title
6871

@@ -110,7 +113,8 @@ def summary(self):
110113
'votes': self.episode['siteRatingCount'],
111114
'episodesummary': self.episode['overview'],
112115
'language': self.episode['language'],
113-
'url': 'https://thetvdb.com/series/{}'.format(self.show['slug']),
116+
'url': 'https://thetvdb.com/series/{}'.format(
117+
self.show['slug']),
114118
'cover': self.banner(self.episode['seasonnumber'])})
115119
self.add_show_titles(summary)
116120
return summary

tests/test_dummy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def test_tv_specifier(title, path, specifier):
4141

4242
def test_proper():
4343
tracks = {'general': "",
44-
'video': "",
44+
'video': dict(),
4545
'audio': "",
4646
'text': ["sub", "title"]}
4747

0 commit comments

Comments
 (0)