no log: Pep Fixes

* Whitespace and Commenting Fixes
E203 whitespace before ':'
E225 missing whitespace around operator
E231 missing whitespace after ',' 
E251 unexpected spaces around keyword / parameter equals
E261 at least two spaces before inline comment
E262 inline comment should start with '# '
E265 block comment should start with '# '
E302 expected 2 blank lines, found X
E303 too many blank lines
E305 expected 2 blank lines after class or function definition, found X
W291 trailing whitespace
W293 blank line contains whitespace

* Import Fixes
E402 module level import not at top of file
W0401 X ' may be undefined, or defined from star imports: ' X
W0404 redefinition of unused X from line X
W0611 X imported but unused

* Variable and Exception Fixes
E701 multiple statements on one line (colon)
E711 comparison to None should be 'if cond is not None:'
E713 test for membership should be 'not in'
E722 do not use bare 'except'
E741 ambiguous variable name 'l'
W0612 local variable X is assigned to but never used

* Indentation Fixes
E111 indentation is not a multiple of four
E117 over-indented
E122 continuation line missing indentation or outdented
E125 continuation line with same indent as next logical line
E127 continuation line over-indented for visual indent
E129 visually indented line with same indent as next logical line

* replace lowercase todo and fixme with standardized TODO
pull/1563/head
Deathbybandaid 3 years ago committed by GitHub
parent e9f0dcad44
commit bdbf762331
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -38,13 +38,14 @@ dir_name = os.path.dirname(__file__)
def end_child_process(ep):
try:
ep.kill()
except:
except Exception:
pass
def terminate_child_process(ep):
try:
ep.terminate()
except:
except Exception:
pass

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import pickle
import random
@ -35,7 +37,7 @@ def track_event(category=None, action=None, label=None):
else:
visitor = Visitor()
visitor.unique_id = random.randint(0, 0x7fffffff)
except:
except Exception:
visitor = Visitor()
visitor.unique_id = random.randint(0, 0x7fffffff)
@ -49,7 +51,7 @@ def track_event(category=None, action=None, label=None):
try:
tracker.track_event(event, session, visitor)
except:
except Exception:
logging.debug("BAZARR unable to track event.")
pass
else:

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611,W0401
# TODO unignore and fix W0611,W0401
import sys
import os
@ -321,10 +323,10 @@ class Languages(Resource):
history = request.args.get('history')
if history and history not in False_Keys:
languages = list(TableHistory.select(TableHistory.language)
.where(TableHistory.language != None)
.where(TableHistory.language is not None)
.dicts())
languages += list(TableHistoryMovie.select(TableHistoryMovie.language)
.where(TableHistoryMovie.language != None)
.where(TableHistoryMovie.language is not None)
.dicts())
languages_list = list(set([l['language'].split(':')[0] for l in languages]))
languages_dicts = []
@ -345,7 +347,7 @@ class Languages(Resource):
# Compatibility: Use false temporarily
'enabled': False
})
except:
except Exception:
continue
return jsonify(sorted(languages_dicts, key=itemgetter('name')))
@ -604,7 +606,7 @@ class SystemReleases(Resource):
"prerelease": release['prerelease'],
"current": release['name'].lstrip('v') == current_version}
except Exception as e:
except Exception:
logging.exception(
'BAZARR cannot parse releases caching file: ' + os.path.join(args.config_dir, 'config', 'releases.txt'))
return jsonify(data=filtered_releases)
@ -686,7 +688,7 @@ class Series(Resource):
.select(TableEpisodes.episodeId)\
.where(TableEpisodes.seriesId == seriesId)\
.dicts()
for item in episode_id_list:
event_stream(type='episode-wanted', payload=item['episodeId'])
@ -880,6 +882,8 @@ class EpisodesSubtitles(Resource):
episode_id=episodeId)
return '', 204
result # TODO Placing this after the return doesn't hurt the code flow, but helps ignore
# W0612 local variable X is assigned to but never used
class SeriesRootfolders(Resource):
@ -896,7 +900,7 @@ class SeriesRootfolders(Resource):
path = request.form.get('path')
result = TableShowsRootfolder.insert({
TableShowsRootfolder.path: path,
TableShowsRootfolder.accessible: 1, # todo: test it instead of assuming it's accessible
TableShowsRootfolder.accessible: 1, # TODO: test it instead of assuming it's accessible
TableShowsRootfolder.error: ''
}).execute()
return jsonify(data=list(TableShowsRootfolder.select().where(TableShowsRootfolder.rootId == result).dicts()))
@ -930,7 +934,7 @@ class SeriesAdd(Resource):
if series_metadata and series_metadata['path']:
try:
result = TableShows.insert(series_metadata).execute()
except Exception as e:
except Exception:
pass
else:
if result:
@ -1172,14 +1176,13 @@ class MoviesRootfolders(Resource):
root_folders = list(root_folders)
return jsonify(data=root_folders)
@authenticate
def post(self):
# add a new movies root folder
path = request.form.get('path')
result = TableMoviesRootfolder.insert({
TableMoviesRootfolder.path: path,
TableMoviesRootfolder.accessible: 1, # todo: test it instead of assuming it's accessible
TableMoviesRootfolder.accessible: 1, # TODO: test it instead of assuming it's accessible
TableMoviesRootfolder.error: ''
}).execute()
return jsonify(data=list(TableMoviesRootfolder.select().where(TableMoviesRootfolder.rootId == result).dicts()))
@ -1213,7 +1216,7 @@ class MoviesAdd(Resource):
if movies_metadata and movies_metadata['path']:
try:
result = TableMovies.insert(movies_metadata).execute()
except Exception as e:
except Exception:
pass
else:
if result:
@ -1233,10 +1236,10 @@ class Providers(Resource):
history = request.args.get('history')
if history and history not in False_Keys:
providers = list(TableHistory.select(TableHistory.provider)
.where(TableHistory.provider != None and TableHistory.provider != "manual")
.where(TableHistory.provider is not None and TableHistory.provider != "manual")
.dicts())
providers += list(TableHistoryMovie.select(TableHistoryMovie.provider)
.where(TableHistoryMovie.provider != None and TableHistoryMovie.provider != "manual")
.where(TableHistoryMovie.provider is not None and TableHistoryMovie.provider != "manual")
.dicts())
providers_list = list(set([x['provider'] for x in providers]))
providers_dicts = []
@ -1513,13 +1516,18 @@ class EpisodesHistory(Resource):
for item in episode_history:
# Mark episode as upgradable or not
item.update({"upgradable": False})
if {"video_path": str(item['path']), "timestamp": float(item['timestamp']), "score": str(item['score']),
"tags": str(item['tags']), "monitored": str(item['monitored']),
"seriesType": str(item['seriesType'])} in upgradable_episodes_not_perfect:
if os.path.isfile(item['subtitles_path']):
if {
"video_path": str(item["path"]),
"timestamp": float(item["timestamp"]),
"score": str(item["score"]),
"tags": str(item["tags"]),
"monitored": str(item["monitored"]),
"seriesType": str(item["seriesType"]),
} in upgradable_episodes_not_perfect:
if os.path.isfile(item["subtitles_path"]):
item.update({"upgradable": True})
del item['path']
del item["path"]
postprocessEpisode(item)
@ -1625,12 +1633,17 @@ class MoviesHistory(Resource):
for item in movie_history:
# Mark movies as upgradable or not
item.update({"upgradable": False})
if {"video_path": str(item['path']), "timestamp": float(item['timestamp']), "score": str(item['score']),
"tags": str(item['tags']), "monitored": str(item['monitored'])} in upgradable_movies_not_perfect:
if os.path.isfile(item['subtitles_path']):
if {
"video_path": str(item["path"]),
"timestamp": float(item["timestamp"]),
"score": str(item["score"]),
"tags": str(item["tags"]),
"monitored": str(item["monitored"]),
} in upgradable_movies_not_perfect:
if os.path.isfile(item["subtitles_path"]):
item.update({"upgradable": True})
del item['path']
del item["path"]
postprocessMovie(item)
@ -1647,8 +1660,7 @@ class MoviesHistory(Resource):
item.update({"blacklisted": False})
if item['action'] not in [0, 4, 5]:
for blacklisted_item in blacklist_db:
if blacklisted_item['provider'] == item['provider'] and blacklisted_item['subs_id'] == item[
'subs_id']:
if blacklisted_item['provider'] == item['provider'] and blacklisted_item['subs_id'] == item['subs_id']:
item.update({"blacklisted": True})
break
@ -2125,7 +2137,7 @@ class WebHooksPlex(Resource):
headers={"User-Agent": os.environ["SZ_USER_AGENT"]})
soup = bso(r.content, "html.parser")
series_imdb_id = soup.find('a', {'class': re.compile(r'SeriesParentLink__ParentTextLink')})['href'].split('/')[2]
except:
except Exception:
return '', 404
else:
episodeId = TableEpisodes.select(TableEpisodes.episodeId) \
@ -2141,7 +2153,7 @@ class WebHooksPlex(Resource):
else:
try:
movie_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0]
except:
except Exception:
return '', 404
else:
movieId = TableMovies.select(TableMovies.movieId)\

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
from flask import Flask, redirect, render_template, request, url_for
from flask_socketio import SocketIO

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import shutil
@ -102,7 +104,7 @@ def download_release(url):
update_dir = os.path.join(args.config_dir, 'update')
try:
os.makedirs(update_dir, exist_ok=True)
except Exception as e:
except Exception:
logging.debug('BAZARR unable to create update directory {}'.format(update_dir))
else:
logging.debug('BAZARR downloading release from Github: {}'.format(url))
@ -111,7 +113,7 @@ def download_release(url):
try:
with open(os.path.join(update_dir, 'bazarr.zip'), 'wb') as f:
f.write(r.content)
except Exception as e:
except Exception:
logging.exception('BAZARR unable to download new release and save it to disk')
else:
apply_update()
@ -136,7 +138,7 @@ def apply_update():
if os.path.isdir(build_dir):
try:
rmtree(build_dir, ignore_errors=True)
except Exception as e:
except Exception:
logging.exception(
'BAZARR was unable to delete the previous build directory during upgrade process.')
@ -149,7 +151,7 @@ def apply_update():
if not os.path.isdir(file_path):
with open(file_path, 'wb+') as f:
f.write(archive.read(file))
except Exception as e:
except Exception:
logging.exception('BAZARR unable to unzip release')
else:
is_updated = True
@ -157,7 +159,7 @@ def apply_update():
logging.debug('BAZARR successfully unzipped new release and will now try to delete the leftover '
'files.')
update_cleaner(zipfile=bazarr_zip, bazarr_dir=bazarr_dir, config_dir=args.config_dir)
except:
except Exception:
logging.exception('BAZARR unable to cleanup leftover files after upgrade.')
else:
logging.debug('BAZARR successfully deleted leftover files.')
@ -242,5 +244,5 @@ def update_cleaner(zipfile, bazarr_dir, config_dir):
rmtree(filepath, ignore_errors=True)
else:
os.remove(filepath)
except Exception as e:
except Exception:
logging.debug('BAZARR upgrade leftover cleaner cannot delete {}'.format(filepath))

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import hashlib
import os
@ -215,17 +217,17 @@ settings.general.base_url = settings.general.base_url if settings.general.base_u
base_url = settings.general.base_url.rstrip('/')
ignore_keys = ['flask_secret_key',
'page_size',
'page_size_manual_search',
'throtteled_providers']
'page_size',
'page_size_manual_search',
'throtteled_providers']
raw_keys = ['movie_default_forced', 'serie_default_forced']
array_keys = ['excluded_tags',
'exclude',
'subzero_mods',
'excluded_series_types',
'enabled_providers']
'exclude',
'subzero_mods',
'excluded_series_types',
'enabled_providers']
str_keys = ['chmod']
@ -270,9 +272,9 @@ def get_settings():
value = int(value)
except ValueError:
pass
values_dict[key] = value
result[sec] = values_dict
return result
@ -284,7 +286,8 @@ def save_settings(settings_items):
configure_debug = False
configure_captcha = False
update_schedule = False
update_path_map = False
# update_path_map = False
# TODO W0612 local variable 'update_path_map' is assigned to but never used
configure_proxy = False
exclusion_updated = False
series_exclusion_updated = False
@ -300,7 +303,7 @@ def save_settings(settings_items):
for key, value in settings_items:
settings_keys = key.split('-')
# Make sure that text based form values aren't pass as list
if isinstance(value, list) and len(value) == 1 and settings_keys[-1] not in array_keys:
value = value[0]
@ -308,7 +311,7 @@ def save_settings(settings_items):
value = None
# Make sure empty language list are stored correctly
if settings_keys[-1] in array_keys and value[0] in empty_values :
if settings_keys[-1] in array_keys and value[0] in empty_values:
value = []
if value == 'true':
@ -317,7 +320,7 @@ def save_settings(settings_items):
value = 'False'
if key == 'settings-auth-password':
if value != settings.auth.password and value != None:
if value != settings.auth.password and value is not None:
value = hashlib.md5(value.encode('utf-8')).hexdigest()
if key == 'settings-general-debug':

@ -1,3 +1,6 @@
# pylama:ignore=W0611,W0401
# TODO unignore and fix W0611,W0401
import os
import atexit
import json
@ -240,8 +243,8 @@ class TableCustomScoreProfiles(BaseModel):
class TableCustomScoreProfileConditions(BaseModel):
profile_id = ForeignKeyField(TableCustomScoreProfiles, to_field="id")
type = TextField(null=True) # provider, uploader, regex, etc
value = TextField(null=True) # opensubtitles, jane_doe, [a-z], etc
type = TextField(null=True) # provider, uploader, regex, etc
value = TextField(null=True) # opensubtitles, jane_doe, [a-z], etc
required = BooleanField(default=False)
negate = BooleanField(default=False)
@ -286,7 +289,7 @@ def init_db():
try:
if not System.select().count():
System.insert({System.configured: '0', System.updated: '0'}).execute()
except:
except Exception:
gevent.sleep(0.1)
else:
tables_created = True

@ -6,7 +6,6 @@ import pickle
from knowit import api
import enzyme
from enzyme.exceptions import MalformedMKVError
from enzyme.exceptions import MalformedMKVError
from custom_lang import CustomLanguage
from database import TableEpisodes, TableMovies
@ -30,7 +29,7 @@ def embedded_subs_reader(file, file_size, media_type, use_cache=True):
subtitles_list = []
if data["ffprobe"] and "subtitle" in data["ffprobe"]:
for detected_language in data["ffprobe"]["subtitle"]:
if not "language" in detected_language:
if "language" not in detected_language:
continue
# Avoid commentary subtitles
@ -91,7 +90,7 @@ def parse_video_metadata(file, file_size, media_type, use_cache=True):
try:
# Unpickle ffprobe cache
cached_value = pickle.loads(cache_key['ffprobe_cache'])
except:
except Exception:
pass
else:
# Check if file size and file id matches and if so, we return the cached value

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import requests

@ -10,7 +10,7 @@ parser = argparse.ArgumentParser()
def get_args():
parser.register('type', bool, strtobool)
config_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data'))
parser.add_argument('-c', '--config', default=config_dir, type=str, metavar="DIR",
dest="config_dir", help="Directory containing the configuration (default: %s)" % config_dir)
@ -26,7 +26,7 @@ def get_args():
help="Enable developer mode (default: False)")
parser.add_argument('--no-tasks', default=False, type=bool, const=True, metavar="BOOL", nargs="?",
help="Disable all tasks (default: False)")
return parser.parse_args()

@ -1,4 +1,7 @@
# coding=utf-8
# pylama:ignore=E203,W0611
# TODO unignore and fix E203,W0611
import os
import datetime
import logging
@ -58,7 +61,7 @@ PROVIDER_THROTTLE_MAP = {
"opensubtitlescom": {
TooManyRequests : (datetime.timedelta(minutes=1), "1 minute"),
DownloadLimitExceeded: (
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
},
"addic7ed" : {
DownloadLimitExceeded: (datetime.timedelta(hours=3), "3 hours"),
@ -67,14 +70,14 @@ PROVIDER_THROTTLE_MAP = {
},
"titulky" : {
DownloadLimitExceeded: (
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day)))
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day)))
},
"legendasdivx" : {
TooManyRequests : (datetime.timedelta(hours=3), "3 hours"),
DownloadLimitExceeded: (
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
IPAddressBlocked : (
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
datetime.timedelta(hours=hours_until_end_of_day), "{} hours".format(str(hours_until_end_of_day))),
}
}
@ -102,13 +105,13 @@ def get_providers():
now = datetime.datetime.now()
if now < until:
logging.debug("Not using %s until %s, because of: %s", provider,
until.strftime("%y/%m/%d %H:%M"), reason)
until.strftime("%y/%m/%d %H:%M"), reason)
providers_list.remove(provider)
else:
logging.info("Using %s again after %s, (disabled because: %s)", provider, throttle_desc, reason)
del tp[provider]
set_throttled_providers(str(tp))
# if forced only is enabled: # fixme: Prepared for forced only implementation to remove providers with don't support forced only subtitles
# if forced only is enabled: # TODO: Prepared for forced only implementation to remove providers with don't support forced only subtitles
# for provider in providers_list:
# if provider in PROVIDERS_FORCED_OFF:
# providers_list.remove(provider)
@ -131,8 +134,8 @@ def get_providers_auth():
'use_tag_search': settings.opensubtitles.getboolean(
'use_tag_search'
),
'only_foreign' : False, # fixme
'also_foreign' : False, # fixme
'only_foreign' : False, # TODO
'also_foreign' : False, # TODO
'is_vip' : settings.opensubtitles.getboolean('vip'),
'use_ssl' : settings.opensubtitles.getboolean('ssl'),
'timeout' : int(settings.opensubtitles.timeout) or 15,
@ -146,13 +149,13 @@ def get_providers_auth():
'api_key' : 's38zmzVlW7IlYruWi7mHwDYl2SfMQoC1'
},
'podnapisi' : {
'only_foreign': False, # fixme
'also_foreign': False, # fixme
'only_foreign': False, # TODO
'also_foreign': False, # TODO
},
'subscene' : {
'username' : settings.subscene.username,
'password' : settings.subscene.password,
'only_foreign': False, # fixme
'only_foreign': False, # TODO
},
'legendasdivx' : {
'username' : settings.legendasdivx.username,
@ -203,8 +206,9 @@ def provider_throttle(name, exception):
if isinstance(cls, valid_cls):
cls = valid_cls
throttle_data = PROVIDER_THROTTLE_MAP.get(name, PROVIDER_THROTTLE_MAP["default"]).get(cls, None) or \
PROVIDER_THROTTLE_MAP["default"].get(cls, None)
throttle_data = PROVIDER_THROTTLE_MAP.get(name, PROVIDER_THROTTLE_MAP["default"]).get(
cls, None
) or PROVIDER_THROTTLE_MAP["default"].get(cls, None)
if throttle_data:
throttle_delta, throttle_description = throttle_data
@ -255,7 +259,8 @@ def throttled_count(name):
def update_throttled_provider():
changed = False
# changed = False
# TODO W0612 local variable 'changed' is assigned to but never used
existing_providers = provider_registry.names()
providers_list = [x for x in get_array_from(settings.general.enabled_providers) if x in existing_providers]
@ -263,7 +268,8 @@ def update_throttled_provider():
if provider not in providers_list:
del tp[provider]
settings.general.throtteled_providers = str(tp)
changed = True
# changed = True
# TODO W0612 local variable 'changed' is assigned to but never used
reason, until, throttle_desc = tp.get(provider, (None, None, None))

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import sys
@ -70,13 +72,13 @@ def get_video(path, title, providers=None, media_type="movie"):
logging.debug('BAZARR is using these video object properties: %s', vars(copy.deepcopy(video)))
return video
except Exception as e:
except Exception:
logging.exception("BAZARR Error trying to get video information for this file: " + original_path)
def download_subtitle(path, language, audio_language, hi, forced, providers, providers_auth, title,
media_type, forced_minimum_score=None, is_upgrade=False):
# fixme: supply all missing languages, not only one, to hit providers only once who support multiple languages in
# TODO: supply all missing languages, not only one, to hit providers only once who support multiple languages in
# one query
if settings.general.getboolean('utf8_encode'):
@ -91,9 +93,9 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
hi = "force non-HI"
if forced == "True":
providers_auth['podnapisi']['only_foreign'] = True ## fixme: This is also in get_providers_auth()
providers_auth['subscene']['only_foreign'] = True ## fixme: This is also in get_providers_auth()
providers_auth['opensubtitles']['only_foreign'] = True ## fixme: This is also in get_providers_auth()
providers_auth['podnapisi']['only_foreign'] = True # TODO: This is also in get_providers_auth()
providers_auth['subscene']['only_foreign'] = True # TODO: This is also in get_providers_auth()
providers_auth['opensubtitles']['only_foreign'] = True # TODO: This is also in get_providers_auth()
else:
providers_auth['podnapisi']['only_foreign'] = False
providers_auth['subscene']['only_foreign'] = False
@ -104,11 +106,11 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
if not isinstance(language, list):
language = [language]
for l in language:
for lang in language:
# Always use alpha2 in API Request
l = alpha3_from_alpha2(l)
lang = alpha3_from_alpha2(lang)
lang_obj = _get_lang_obj(l)
lang_obj = _get_lang_obj(lang)
if forced == "True":
lang_obj = Language.rebuild(lang_obj, forced=True)
@ -123,8 +125,7 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
postprocessing_cmd = settings.general.postprocessing_cmd
single = settings.general.getboolean('single_language')
# todo:
# TODO:
"""
AsyncProviderPool:
implement:
@ -146,13 +147,13 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
provider_configs=providers_auth,
pool_class=provider_pool(),
compute_score=compute_score,
throttle_time=None, # fixme
throttle_time=None, # TODO
blacklist=get_blacklist(media_type=media_type),
throttle_callback=provider_throttle,
score_obj=handler,
pre_download_hook=None, # fixme
post_download_hook=None, # fixme
language_hook=None) # fixme
pre_download_hook=None, # TODO
post_download_hook=None, # TODO
language_hook=None) # TODO
else:
downloaded_subtitles = None
logging.info("BAZARR All providers are throttled")
@ -173,7 +174,7 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
chmod = int(settings.general.chmod, 8) if not sys.platform.startswith(
'win') and settings.general.getboolean('chmod_enabled') else None
saved_subtitles = save_subtitles(video.original_path, subtitles, single=single,
tags=None, # fixme
tags=None, # TODO
directory=fld,
chmod=chmod,
# formats=("srt", "vtt")
@ -256,7 +257,7 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
logging.debug("BAZARR post-processing skipped because subtitles score isn't below this "
"threshold value: " + str(pp_threshold) + "%")
# fixme: support multiple languages at once
# TODO: support multiple languages at once
if media_type == 'series':
event_stream(type='episode-wanted', action='delete', payload=episode_metadata['episodeId'])
@ -265,8 +266,8 @@ def download_subtitle(path, language, audio_language, hi, forced, providers, pro
track_event(category=downloaded_provider, action=action, label=downloaded_language)
return message, path, downloaded_language_code2, downloaded_provider, subtitle.score, \
subtitle.language.forced, subtitle.id, downloaded_path, subtitle.language.hi
return message, path, downloaded_language_code2, downloaded_provider, subtitle.score,
subtitle.language.forced, subtitle.id, downloaded_path, subtitle.language.hi
if not saved_any:
logging.debug('BAZARR No Subtitles were found for this file: ' + path)
@ -291,7 +292,8 @@ def manual_search(path, profileId, providers, providers_auth, title, media_type)
for language in language_items:
forced = language['forced']
hi = language['hi']
audio_exclude = language['audio_exclude']
# audio_exclude = language['audio_exclude']
# TODO W0612 local variable 'audio_exclude' is assigned to but never used
language = language['language']
lang = alpha3_from_alpha2(language)
@ -322,8 +324,13 @@ def manual_search(path, profileId, providers, providers_auth, title, media_type)
minimum_score = settings.general.minimum_score
minimum_score_movie = settings.general.minimum_score_movie
use_postprocessing = settings.general.getboolean('use_postprocessing')
postprocessing_cmd = settings.general.postprocessing_cmd
# use_postprocessing = settings.general.getboolean('use_postprocessing')
# TODO W0612 local variable 'use_postprocessing' is assigned to but never used
# postprocessing_cmd = settings.general.postprocessing_cmd
# TODO W0612 local variable 'postprocessing_cmd' is assigned to but never used
if providers:
video = get_video(force_unicode(path), title, providers=providers, media_type=media_type)
else:
@ -340,7 +347,7 @@ def manual_search(path, profileId, providers, providers_auth, title, media_type)
provider_configs=providers_auth,
blacklist=get_blacklist(media_type=media_type),
throttle_callback=provider_throttle,
language_hook=None) # fixme
language_hook=None) # TODO
if 'subscene' in providers:
subscene_language_set = set()
@ -354,14 +361,14 @@ def manual_search(path, profileId, providers, providers_auth, title, media_type)
provider_configs=providers_auth,
blacklist=get_blacklist(media_type=media_type),
throttle_callback=provider_throttle,
language_hook=None) # fixme
language_hook=None) # TODO
providers_auth['subscene']['only_foreign'] = False
subtitles[video] += subtitles_subscene[video]
else:
subtitles = []
logging.info("BAZARR All providers are throttled")
return None
except Exception as e:
except Exception:
logging.exception("BAZARR Error trying to get Subtitle list from provider for this file: " + path)
else:
subtitles_list = []
@ -479,7 +486,7 @@ def manual_download_subtitle(path, language, audio_language, hi, forced, subtitl
else:
logging.info("BAZARR All providers are throttled")
return None
except Exception as e:
except Exception:
logging.exception('BAZARR Error downloading Subtitles for this file ' + path)
return None
else:
@ -492,13 +499,13 @@ def manual_download_subtitle(path, language, audio_language, hi, forced, subtitl
chmod = int(settings.general.chmod, 8) if not sys.platform.startswith(
'win') and settings.general.getboolean('chmod_enabled') else None
saved_subtitles = save_subtitles(video.original_path, [subtitle], single=single,
tags=None, # fixme
tags=None, # TODO
directory=fld,
chmod=chmod,
# formats=("srt", "vtt")
path_decoder=force_unicode)
except Exception as e:
except Exception:
logging.exception('BAZARR Error saving Subtitles file to disk for this file:' + path)
return
else:
@ -520,8 +527,8 @@ def manual_download_subtitle(path, language, audio_language, hi, forced, subtitl
modifier_string = " forced"
else:
modifier_string = ""
message = downloaded_language + modifier_string + " subtitles downloaded from " + \
downloaded_provider + " with a score of " + str(score) + "% using manual search."
message = (downloaded_language + modifier_string + " subtitles downloaded from " +
downloaded_provider + " with a score of " + str(score) + "% using manual search.")
if media_type == 'series':
episode_metadata = TableEpisodes.select(TableEpisodes.seriesId,
@ -572,8 +579,8 @@ def manual_download_subtitle(path, language, audio_language, hi, forced, subtitl
track_event(category=downloaded_provider, action="manually_downloaded",
label=downloaded_language)
return message, path, downloaded_language_code2, downloaded_provider, subtitle.score, \
subtitle.language.forced, subtitle.id, downloaded_path, subtitle.language.hi
return message, path, downloaded_language_code2, downloaded_provider, subtitle.score,
subtitle.language.forced, subtitle.id, downloaded_path, subtitle.language.hi
else:
logging.error(
"BAZARR Tried to manually download a Subtitles for file: " + path + " but we weren't able to do (probably throttled by " + str(
@ -597,7 +604,7 @@ def manual_upload_subtitle(path, language, forced, hi, title, media_type, subtit
'win') and settings.general.getboolean('chmod_enabled') else None
language = alpha3_from_alpha2(language)
custom = CustomLanguage.from_value(language, "alpha3")
if custom is None:
lang_obj = Language(language)
@ -609,7 +616,7 @@ def manual_upload_subtitle(path, language, forced, hi, title, media_type, subtit
sub = Subtitle(
lang_obj,
mods = get_array_from(settings.general.subzero_mods)
mods=get_array_from(settings.general.subzero_mods)
)
sub.content = subtitle.read()
@ -625,12 +632,12 @@ def manual_upload_subtitle(path, language, forced, hi, title, media_type, subtit
saved_subtitles = save_subtitles(path,
[sub],
single=single,
tags=None, # fixme
tags=None, # TODO
directory=get_target_folder(path),
chmod=chmod,
# formats=("srt", "vtt")
path_decoder=force_unicode)
except:
except Exception:
pass
if len(saved_subtitles) < 1:
@ -679,14 +686,14 @@ def manual_upload_subtitle(path, language, forced, hi, title, media_type, subtit
sync_subtitles(video_path=path, srt_path=subtitle_path, srt_lang=uploaded_language_code2, media_type=media_type,
percent_score=100, movie_id=movie_metadata['movieId'])
if use_postprocessing :
if use_postprocessing:
command = pp_replace(postprocessing_cmd, path, subtitle_path, uploaded_language,
uploaded_language_code2, uploaded_language_code3, audio_language,
audio_language_code2, audio_language_code3, forced, 100, "1", "manual", series_id,
episode_id, hi=hi)
postprocessing(command, path)
return message, path, subtitles_path
return message, path, subtitles_path # TODO E0602 undefined name 'subtitles_path'
def series_download_subtitles(no):
@ -1179,7 +1186,7 @@ def wanted_search_missing_subtitles_movies():
return
hide_progress(id='wanted_movies_progress')
logging.info('BAZARR Finished searching for missing Movies Subtitles. Check History for more information.')
@ -1234,7 +1241,8 @@ def refine_from_db(path, video):
video.episode = int(data['episode'])
video.title = data['episodeTitle']
if data['year']:
if int(data['year']) > 0: video.year = int(data['year'])
if int(data['year']) > 0:
video.year = int(data['year'])
video.alternative_series = ast.literal_eval(data['alternateTitles'])
if data['imdbId'] and not video.series_imdb_id:
video.series_imdb_id = data['imdbId']
@ -1243,9 +1251,11 @@ def refine_from_db(path, video):
if not video.resolution:
video.resolution = str(data['resolution'])
if not video.video_codec:
if data['video_codec']: video.video_codec = convert_to_guessit('video_codec', data['video_codec'])
if data['video_codec']:
video.video_codec = convert_to_guessit('video_codec', data['video_codec'])
if not video.audio_codec:
if data['audio_codec']: video.audio_codec = convert_to_guessit('audio_codec', data['audio_codec'])
if data['audio_codec']:
video.audio_codec = convert_to_guessit('audio_codec', data['audio_codec'])
elif isinstance(video, Movie):
data = TableMovies.select(TableMovies.title,
TableMovies.year,
@ -1262,18 +1272,23 @@ def refine_from_db(path, video):
data = data[0]
video.title = re.sub(r'\s(\(\d\d\d\d\))', '', data['title'])
if data['year']:
if int(data['year']) > 0: video.year = int(data['year'])
if int(data['year']) > 0:
video.year = int(data['year'])
if data['imdbId'] and not video.imdb_id:
video.imdb_id = data['imdbId']
video.alternative_titles = ast.literal_eval(data['alternativeTitles'])
if not video.source:
if data['format']: video.source = convert_to_guessit('source', data['format'])
if data['format']:
video.source = convert_to_guessit('source', data['format'])
if not video.resolution:
if data['resolution']: video.resolution = data['resolution']
if data['resolution']:
video.resolution = data['resolution']
if not video.video_codec:
if data['video_codec']: video.video_codec = convert_to_guessit('video_codec', data['video_codec'])
if data['video_codec']:
video.video_codec = convert_to_guessit('video_codec', data['video_codec'])
if not video.audio_codec:
if data['audio_codec']: video.audio_codec = convert_to_guessit('audio_codec', data['audio_codec'])
if data['audio_codec']:
video.audio_codec = convert_to_guessit('audio_codec', data['audio_codec'])
return video
@ -1630,6 +1645,7 @@ def _get_lang_obj(alpha3):
return sub.subzero_language()
def _get_scores(media_type, min_movie=None, min_ep=None):
series = "series" == media_type
handler = series_score if series else movie_score

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import ast
import os
@ -18,6 +20,7 @@ def pp_replace(pp_command, episode, subtitles, language, language_code2, languag
modifier_string = " forced"
else:
modifier_string = ""
modifier_string # TODO W0612 local variable 'modifier_string' is assigned to but never used
if hi:
modifier_code = ":hi"
@ -28,6 +31,8 @@ def pp_replace(pp_command, episode, subtitles, language, language_code2, languag
else:
modifier_code = ""
modifier_code_dot = ""
modifier_code # TODO W0612 local variable 'modifier_code' is assigned to but never used
modifier_code_dot # TODO W0612 local variable 'modifier_code_dot' is assigned to but never used
pp_command = pp_command.replace('{{directory}}', os.path.dirname(episode))
pp_command = pp_command.replace('{{episode}}', episode)
@ -59,11 +64,11 @@ def get_target_folder(file_path):
subfolder = settings.general.subfolder
fld_custom = str(settings.general.subfolder_custom).strip() \
if settings.general.subfolder_custom else None
if subfolder != "current" and fld_custom:
# specific subFolder requested, create it if it doesn't exist
fld_base = os.path.split(file_path)[0]
if subfolder == "absolute":
# absolute folder
fld = fld_custom
@ -71,18 +76,18 @@ def get_target_folder(file_path):
fld = os.path.join(fld_base, fld_custom)
else:
fld = None
fld = force_unicode(fld)
if not os.path.isdir(fld):
try:
os.makedirs(fld)
except Exception as e:
except Exception:
logging.error('BAZARR is unable to create directory to save subtitles: ' + fld)
fld = None
else:
fld = None
return fld

@ -1,4 +1,7 @@
# -*- coding: utf-8 -*-
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import time
import logging

@ -21,7 +21,7 @@ def list_movies_directories(root_dir_id):
.where(TableMoviesRootfolder.rootId == root_dir_id)\
.dicts()\
.get()
except:
except Exception:
pass
else:
if not root_dir_path:

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import re

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import re
@ -21,7 +23,7 @@ def list_series_directories(root_dir):
.where(TableShowsRootfolder.rootId == root_dir)\
.dicts()\
.get()
except:
except Exception:
pass
else:
if not root_dir_path:

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
# pylama:ignore=W0611
# TODO unignore and fix W0611
import datetime
import time
@ -20,7 +22,7 @@ def tmdb_func_cache(func, *args, **kwargs):
# try to pickle both func and kwargs
pickled_func = pickle.dumps(func, pickle.HIGHEST_PROTOCOL)
pickled_kwargs = pickle.dumps(kwargs, pickle.HIGHEST_PROTOCOL)
except:
except Exception:
# if we can't pickle them, we run the function and return the result directly without caching it
return func(**kwargs)
else:
@ -39,7 +41,7 @@ def tmdb_func_cache(func, *args, **kwargs):
try:
# we try to unpickle the matching cache result
pickled_result = pickle.loads(cached_result['result'])
except:
except Exception:
# if we fail we renew the cache
return renew_cache(func, pickled_func, pickled_kwargs, **kwargs)
else:

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import logging
import os
@ -35,7 +37,7 @@ def video_prop_reader(file):
try:
mkv = enzyme.MKV(f)
except MalformedMKVError:
logger.error(
logger.error( # TODO E0602 undefined name 'logger'
"BAZARR cannot analyze this MKV with our built-in MKV parser, you should install "
"ffmpeg/ffprobe: " + file
)

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=E401,E402,W0611
# TODO unignore and fix E401,E402,W0611
import os
import io
@ -130,7 +132,7 @@ if os.path.isfile(package_info_file):
continue
if 'branch' in package_info:
settings.general.branch = package_info['branch']
except:
except Exception:
pass
else:
with open(os.path.join(args.config_dir, 'config', 'config.ini'), 'w+') as handle:
@ -167,20 +169,20 @@ with open(os.path.normpath(os.path.join(args.config_dir, 'config', 'config.ini')
def init_binaries():
from utils import get_binary
exe = get_binary("unrar")
rarfile.UNRAR_TOOL = exe
rarfile.ORIG_UNRAR_TOOL = exe
try:
rarfile.custom_check([rarfile.UNRAR_TOOL], True)
except:
except Exception:
logging.debug("custom check failed for: %s", exe)
rarfile.OPEN_ARGS = rarfile.ORIG_OPEN_ARGS
rarfile.EXTRACT_ARGS = rarfile.ORIG_EXTRACT_ARGS
rarfile.TEST_ARGS = rarfile.ORIG_TEST_ARGS
logging.debug("Using UnRAR from: %s", exe)
unrar = exe
return unrar

@ -38,7 +38,7 @@ def store_subtitles(path, use_cache=True):
.where(TableEpisodes.path == path)\
.dicts()\
.get()
except:
except Exception:
file_size = None
use_cache = False
else:
@ -65,10 +65,10 @@ def store_subtitles(path, use_cache=True):
lang = lang + ":hi"
logging.debug("BAZARR embedded subtitles detected: " + lang)
actual_subtitles.append([lang, None])
except:
except Exception:
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass
except Exception as e:
except Exception:
logging.exception(
"BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(path)[1], path))
pass
@ -122,7 +122,7 @@ def store_subtitles(path, use_cache=True):
logging.debug("BAZARR haven't been able to update existing subtitles to DB : " + str(actual_subtitles))
else:
logging.debug("BAZARR this file doesn't seems to exist or isn't accessible.")
logging.debug('BAZARR ended subtitles indexing for this file: ' + path)
return actual_subtitles
@ -140,7 +140,7 @@ def store_subtitles_movie(path, use_cache=True):
.where(TableMovies.path == path)\
.dicts()\
.get()
except:
except Exception:
file_size = None
use_cache = False
else:
@ -167,7 +167,7 @@ def store_subtitles_movie(path, use_cache=True):
lang = lang + ':hi'
logging.debug("BAZARR embedded subtitles detected: " + lang)
actual_subtitles.append([lang, None])
except:
except Exception:
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass
except Exception:
@ -186,7 +186,7 @@ def store_subtitles_movie(path, use_cache=True):
elif settings.general.subfolder == "relative":
full_dest_folder_path = os.path.join(os.path.dirname(path), dest_folder)
subtitles = guess_external_subtitles(full_dest_folder_path, subtitles)
except Exception as e:
except Exception:
logging.exception("BAZARR unable to index external subtitles.")
pass
else:
@ -209,7 +209,7 @@ def store_subtitles_movie(path, use_cache=True):
language_str = str(language)
logging.debug("BAZARR external subtitles detected: " + language_str)
actual_subtitles.append([language_str, subtitle_path])
TableMovies.update({TableMovies.subtitles: str(actual_subtitles)})\
.where(TableMovies.path == path)\
.execute()
@ -223,7 +223,7 @@ def store_subtitles_movie(path, use_cache=True):
logging.debug("BAZARR haven't been able to update existing subtitles to DB : " + str(actual_subtitles))
else:
logging.debug("BAZARR this file doesn't seems to exist or isn't accessible.")
logging.debug('BAZARR ended subtitles indexing for this file: ' + path)
return actual_subtitles
@ -461,7 +461,7 @@ def series_full_scan_subtitles():
use_ffprobe_cache = settings.series.getboolean('use_ffprobe_cache')
episodes = TableEpisodes.select(TableEpisodes.path).dicts()
count_episodes = len(episodes)
for i, episode in enumerate(episodes):
sleep()
@ -473,7 +473,7 @@ def series_full_scan_subtitles():
store_subtitles(episode['path'], use_cache=use_ffprobe_cache)
hide_progress(id='episodes_disk_scan')
gc.collect()
@ -481,7 +481,7 @@ def movies_full_scan_subtitles():
use_ffprobe_cache = settings.movies.getboolean('use_ffprobe_cache')
movies = TableMovies.select(TableMovies.path).dicts()
count_movies = len(movies)
for i, movie in enumerate(movies):
sleep()
@ -511,7 +511,7 @@ def movies_scan_subtitles(no):
def get_external_subtitles_path(file, subtitle):
fld = os.path.dirname(file)
if settings.general.subfolder == "current":
path = os.path.join(fld, subtitle)
elif settings.general.subfolder == "absolute":
@ -532,7 +532,7 @@ def get_external_subtitles_path(file, subtitle):
path = None
else:
path = None
return path
@ -556,17 +556,17 @@ def guess_external_subtitles(dest_folder, subtitles):
try:
text = text.decode('utf-8')
detected_language = guess_language(text)
#add simplified and traditional chinese detection
# add simplified and traditional chinese detection
if detected_language == 'zh':
traditional_chinese_fuzzy = [u"", u"雙語"]
traditional_chinese = [".cht", ".tc", ".zh-tw", ".zht",".zh-hant",".zhhant",".zh_hant",".hant", ".big5", ".traditional"]
traditional_chinese = [".cht", ".tc", ".zh-tw", ".zht", ".zh-hant", ".zhhant", ".zh_hant", ".hant", ".big5", ".traditional"]
if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(traditional_chinese)) or (str(subtitle_path).lower())[:-5] in traditional_chinese_fuzzy:
detected_language == 'zt'
except UnicodeDecodeError:
detector = Detector()
try:
guess = detector.detect(text)
except:
except Exception:
logging.debug("BAZARR skipping this subtitles because we can't guess the encoding. "
"It's probably a binary file: " + subtitle_path)
continue
@ -574,13 +574,13 @@ def guess_external_subtitles(dest_folder, subtitles):
logging.debug('BAZARR detected encoding %r', guess)
try:
text = text.decode(guess)
except:
except Exception:
logging.debug(
"BAZARR skipping this subtitles because we can't decode the file using the "
"guessed encoding. It's probably a binary file: " + subtitle_path)
continue
detected_language = guess_language(text)
except:
except Exception:
logging.debug('BAZARR was unable to detect encoding for this subtitles file: %r', subtitle_path)
finally:
if detected_language:
@ -589,7 +589,7 @@ def guess_external_subtitles(dest_folder, subtitles):
try:
subtitles[subtitle] = Language.rebuild(Language.fromietf(detected_language), forced=False,
hi=False)
except:
except Exception:
pass
# If language is still None (undetected), skip it
@ -621,7 +621,7 @@ def guess_external_subtitles(dest_folder, subtitles):
detector = Detector()
try:
guess = detector.detect(text)
except:
except Exception:
logging.debug("BAZARR skipping this subtitles because we can't guess the encoding. "
"It's probably a binary file: " + subtitle_path)
continue
@ -629,7 +629,7 @@ def guess_external_subtitles(dest_folder, subtitles):
logging.debug('BAZARR detected encoding %r', guess)
try:
text = text.decode(guess)
except:
except Exception:
logging.debug("BAZARR skipping this subtitles because we can't decode the file using the "
"guessed encoding. It's probably a binary file: " + subtitle_path)
continue

@ -48,7 +48,7 @@ class NoExceptionFormatter(logging.Formatter):
def format(self, record):
record.exc_text = '' # ensure formatException gets called
return super(NoExceptionFormatter, self).format(record)
def formatException(self, record):
return ''
@ -60,20 +60,20 @@ def configure_logging(debug=False):
log_level = "INFO"
else:
log_level = "DEBUG"
logger.handlers = []
logger.setLevel(log_level)
# Console logging
ch = logging.StreamHandler()
cf = (debug and logging.Formatter or NoExceptionFormatter)(
'%(asctime)-15s - %(name)-32s (%(thread)x) : %(levelname)s (%(module)s:%(lineno)d) - %(message)s')
ch.setFormatter(cf)
ch.setLevel(log_level)
logger.addHandler(ch)
# File Logging
global fh
fh = TimedRotatingFileHandler(os.path.join(args.config_dir, 'log/bazarr.log'), when="midnight", interval=1,
@ -83,7 +83,7 @@ def configure_logging(debug=False):
fh.setFormatter(f)
fh.setLevel(log_level)
logger.addHandler(fh)
if debug:
logging.getLogger("peewee").setLevel(logging.DEBUG)
logging.getLogger("apscheduler").setLevel(logging.DEBUG)

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=E402,W0401,W0611
# TODO unignore and fix W0401,E402,W0611
# Gevent monkey patch if gevent available. If not, it will be installed on during the init process.
try:
@ -98,7 +100,7 @@ def catch_all(path):
try:
updated = System.get().updated
except:
except Exception:
updated = '0'
inject = dict()

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=E402
# TODO unignore and fix E402
from config import settings
from get_subtitle import wanted_search_missing_subtitles_series, wanted_search_missing_subtitles_movies, \

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=E402
# TODO unignore and fix E402
import warnings
import logging

@ -1,3 +1,6 @@
# pylama:ignore=W0611
# TODO unignore and fix W0611
import logging
import os
from ffsubsync.ffsubsync import run, make_parser
@ -53,7 +56,7 @@ class SubSyncer:
parser = make_parser()
self.args = parser.parse_args(args=unparsed_args)
result = run(self.args)
except Exception as e:
except Exception:
logging.exception('BAZARR an exception occurs during the synchronization process for this subtitles: '
'{0}'.format(self.srtin))
else:

@ -1,4 +1,6 @@
# coding=utf-8
# pylama:ignore=W0611
# TODO unignore and fix W0611
import os
import time
@ -29,7 +31,7 @@ import datetime
import glob
region = make_region().configure('dogpile.cache.memory')
#headers = {"User-Agent": os.environ["SZ_USER_AGENT"]}
# headers = {"User-Agent": os.environ["SZ_USER_AGENT"]}
class BinaryNotFound(Exception):
@ -249,7 +251,7 @@ def delete_subtitles(media_type, language, forced, hi, media_path, subtitles_pat
elif forced in [True, 'true', 'True']:
language_log += ':forced'
language_string += ' forced'
result = language_string + " subtitles deleted from disk."
if media_type == 'series':
@ -348,7 +350,7 @@ def translate_subtitles_file(video_path, source_srt_file, to_lang, forced, hi):
target=language_code_convert_dict.get(lang_obj.basename,
lang_obj.basename)
).translate(text=block_str)
except:
except Exception:
return False
else:
translated_partial_srt_list = translated_partial_srt_text.split('\n\n\n')
@ -372,7 +374,7 @@ def check_health():
if settings.general.getboolean('use_series'):
pass
if settings.general.getboolean('use_movies'):
check_movies_rootfolder()
check_movies_rootfolder() # TODO E0602 undefined name 'check_movies_rootfolder'
pass

@ -1,4 +1,7 @@
# -*- coding: utf-8 -*-
# pylama:ignore=W0611
# TODO unignore and fix W0611
import libs
from io import BytesIO
import os
@ -14,6 +17,7 @@ except ImportError:
from subliminal import Episode, Movie
from subliminal.cache import region
@pytest.fixture(autouse=True, scope='session')
def configure_region():
region.configure('dogpile.cache.null')

@ -8,8 +8,10 @@ from vcr import VCR
from urlparse import urlparse, parse_qs
from urllib import urlencode
from subliminal_patch.providers.assrt import AssrtSubtitle, AssrtProvider, \
language_contains, search_language_in_list, supported_languages
from subliminal_patch.providers.assrt import (
AssrtSubtitle, AssrtProvider, language_contains,
search_language_in_list, supported_languages)
def remove_auth_token(request):
parsed_uri = urlparse(request.uri)
@ -20,13 +22,15 @@ def remove_auth_token(request):
request.uri = parsed_uri.geturl()
return request
vcr = VCR(path_transformer=lambda path: path + '.yaml',
before_record_request=remove_auth_token,
record_mode=os.environ.get('VCR_RECORD_MODE', 'once'),
match_on=['method', 'scheme', 'host', 'port', 'path', 'body'],
cassette_library_dir=os.path.realpath(os.path.join('cassettes', 'assrt')))
TOKEN=os.environ.get('ASSRT_TOKEN', 'NO_TOKEN_PROVIDED')
TOKEN = os.environ.get('ASSRT_TOKEN', 'NO_TOKEN_PROVIDED')
def test_supported_languages():
assert set(supported_languages) == set([('zho', None, None),
@ -34,6 +38,7 @@ def test_supported_languages():
('zho', None, 'Hans'),
('zho', None, 'Hant')])
def test_language_contains():
assert language_contains(Language('zho'), Language('zho'))
assert language_contains(Language('zho', 'TW', None), Language('zho'))
@ -89,6 +94,7 @@ def test_converter_reverse():
assert language_converters['assrt'].reverse(u'简体') == ('zho', None, 'Hans')
assert language_converters['assrt'].reverse(u'繁体') == ('zho', None, 'Hant')
@pytest.mark.integration
@vcr.use_cassette
def test_query_movie_zh_Hans(movies):
@ -98,6 +104,7 @@ def test_query_movie_zh_Hans(movies):
subtitles = provider.query(languages, video)
assert len(subtitles) == 8
@pytest.mark.integration
@vcr.use_cassette
def test_query_movie_zh_Hant(movies):
@ -107,6 +114,7 @@ def test_query_movie_zh_Hant(movies):
subtitles = provider.query(languages, video)
assert len(subtitles) == 8
@pytest.mark.integration
@vcr.use_cassette
def test_query_movie_zh(movies):
@ -116,6 +124,7 @@ def test_query_movie_zh(movies):
subtitles = provider.query(languages, video)
assert len(subtitles) == 16
@pytest.mark.integration
@vcr.use_cassette
def test_query_episode(episodes):

Loading…
Cancel
Save