Reformat code

pull/479/head
Halali 5 years ago
parent 78b819ef50
commit daa6d87e76

@ -1,7 +1,6 @@
# coding=utf-8 # coding=utf-8
import subprocess as sp import subprocess as sp
import threading
import time import time
import os import os
import sys import sys
@ -14,7 +13,7 @@ dir_name = os.path.dirname(__file__)
def start_bazarr(): def start_bazarr():
script = [sys.executable, "-u", os.path.normcase(os.path.join(dir_name, 'bazarr', 'main.py'))] + sys.argv[1:] script = [sys.executable, "-u", os.path.normcase(os.path.join(dir_name, 'bazarr', 'main.py'))] + sys.argv[1:]
ep = sp.Popen(script, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE) ep = sp.Popen(script, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE)
print "Bazarr starting..." print "Bazarr starting..."
try: try:
@ -27,17 +26,18 @@ def start_bazarr():
if __name__ == '__main__': if __name__ == '__main__':
restartfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.restart')) restartfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.restart'))
stopfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.stop')) stopfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.stop'))
try: try:
os.remove(restartfile) os.remove(restartfile)
except: except:
pass pass
try: try:
os.remove(stopfile) os.remove(stopfile)
except: except:
pass pass
def daemon(): def daemon():
if os.path.exists(stopfile): if os.path.exists(stopfile):
try: try:
@ -47,7 +47,7 @@ if __name__ == '__main__':
else: else:
print 'Bazarr exited.' print 'Bazarr exited.'
os._exit(0) os._exit(0)
if os.path.exists(restartfile): if os.path.exists(restartfile):
try: try:
os.remove(restartfile) os.remove(restartfile)
@ -55,9 +55,10 @@ if __name__ == '__main__':
print 'Unable to delete restart file.' print 'Unable to delete restart file.'
else: else:
start_bazarr() start_bazarr()
start_bazarr() start_bazarr()
# Keep the script running forever. # Keep the script running forever.
while True: while True:
daemon() daemon()

@ -9,7 +9,7 @@ parser = argparse.ArgumentParser()
def get_args(): def get_args():
parser.register('type', bool, strtobool) parser.register('type', bool, strtobool)
config_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data')) 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", parser.add_argument('-c', '--config', default=config_dir, type=str, metavar="DIR",
dest="config_dir", help="Directory containing the configuration (default: %s)" % config_dir) dest="config_dir", help="Directory containing the configuration (default: %s)" % config_dir)
@ -21,7 +21,7 @@ def get_args():
help="Enable console debugging (default: False)") help="Enable console debugging (default: False)")
parser.add_argument('--release-update', default=False, type=bool, const=True, metavar="BOOL", nargs="?", parser.add_argument('--release-update', default=False, type=bool, const=True, metavar="BOOL", nargs="?",
help="Enable file based updater (default: False)") help="Enable file based updater (default: False)")
return parser.parse_args() return parser.parse_args()

@ -115,13 +115,13 @@ def get_language_set():
languages = c.execute('''SELECT code3 FROM table_settings_languages WHERE enabled = 1''').fetchall() languages = c.execute('''SELECT code3 FROM table_settings_languages WHERE enabled = 1''').fetchall()
db.close() db.close()
language_set = set() language_set = set()
for lang in languages: for lang in languages:
if lang[0] == 'pob': if lang[0] == 'pob':
language_set.add(Language('por', 'BR')) language_set.add(Language('por', 'BR'))
else: else:
language_set.add(Language(lang[0])) language_set.add(Language(lang[0]))
return language_set return language_set

@ -65,7 +65,7 @@ def get_video(path, title, sceneName, use_scenename, providers=None, media_type=
video.used_scene_name = dont_use_actual_file video.used_scene_name = dont_use_actual_file
video.original_name = original_name video.original_name = original_name
video.original_path = original_path video.original_path = original_path
refine_from_db(original_path,video) refine_from_db(original_path, video)
logging.debug('BAZARR is using those video object properties: %s', vars(video)) logging.debug('BAZARR is using those video object properties: %s', vars(video))
return video return video
@ -100,25 +100,26 @@ def get_scores(video, media_type, min_score_movie_perc=60 * 100 / 120.0, min_sco
return min_score, max_score, set(scores) return min_score, max_score, set(scores)
def download_subtitle(path, language, hi, forced, providers, providers_auth, sceneName, title, media_type, forced_minimum_score=None, is_upgrade=False): def download_subtitle(path, language, hi, forced, providers, providers_auth, sceneName, 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 # fixme: supply all missing languages, not only one, to hit providers only once who support multiple languages in
# one query # one query
if settings.general.getboolean('utf8_encode'): if settings.general.getboolean('utf8_encode'):
os.environ["SZ_KEEP_ENCODING"] = "" os.environ["SZ_KEEP_ENCODING"] = ""
else: else:
os.environ["SZ_KEEP_ENCODING"] = True os.environ["SZ_KEEP_ENCODING"] = True
logging.debug('BAZARR Searching subtitles for this file: ' + path) logging.debug('BAZARR Searching subtitles for this file: ' + path)
if hi == "True": if hi == "True":
hi = "force HI" hi = "force HI"
else: else:
hi = "force non-HI" hi = "force non-HI"
language_set = set() language_set = set()
if not isinstance(language, types.ListType): if not isinstance(language, types.ListType):
language = [language] language = [language]
if forced == "True": if forced == "True":
providers_auth['podnapisi']['only_foreign'] = True providers_auth['podnapisi']['only_foreign'] = True
providers_auth['subscene']['only_foreign'] = True providers_auth['subscene']['only_foreign'] = True
@ -127,7 +128,7 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
providers_auth['podnapisi']['only_foreign'] = False providers_auth['podnapisi']['only_foreign'] = False
providers_auth['subscene']['only_foreign'] = False providers_auth['subscene']['only_foreign'] = False
providers_auth['opensubtitles']['only_foreign'] = False providers_auth['opensubtitles']['only_foreign'] = False
for l in language: for l in language:
if l == 'pob': if l == 'pob':
lang_obj = Language('por', 'BR') lang_obj = Language('por', 'BR')
@ -160,7 +161,7 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
if video: if video:
min_score, max_score, scores = get_scores(video, media_type, min_score_movie_perc=int(minimum_score_movie), min_score, max_score, scores = get_scores(video, media_type, min_score_movie_perc=int(minimum_score_movie),
min_score_series_perc=int(minimum_score)) min_score_series_perc=int(minimum_score))
if providers: if providers:
if forced_minimum_score: if forced_minimum_score:
min_score = int(forced_minimum_score) + 1 min_score = int(forced_minimum_score) + 1
@ -187,7 +188,8 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
try: try:
fld = get_target_folder(path) fld = get_target_folder(path)
chmod = int(settings.general.chmod, 8) if not sys.platform.startswith('win') and settings.general.getboolean('chmod_enabled') else None 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, saved_subtitles = save_subtitles(video.original_path, subtitles, single=single,
tags=None, # fixme tags=None, # fixme
directory=fld, directory=fld,
@ -224,7 +226,8 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
if use_postprocessing is True: if use_postprocessing is True:
command = pp_replace(postprocessing_cmd, path, downloaded_path, downloaded_language, command = pp_replace(postprocessing_cmd, path, downloaded_path, downloaded_language,
downloaded_language_code2, downloaded_language_code3, subtitle.language.forced) downloaded_language_code2, downloaded_language_code3,
subtitle.language.forced)
try: try:
if os.name == 'nt': if os.name == 'nt':
codepage = subprocess.Popen("chcp", shell=True, stdout=subprocess.PIPE, codepage = subprocess.Popen("chcp", shell=True, stdout=subprocess.PIPE,
@ -259,7 +262,7 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
reversed_path = path_replace_reverse(path) reversed_path = path_replace_reverse(path)
else: else:
reversed_path = path_replace_reverse_movie(path) reversed_path = path_replace_reverse_movie(path)
return message, reversed_path, downloaded_language_code2, downloaded_provider, subtitle.score, subtitle.language.forced return message, reversed_path, downloaded_language_code2, downloaded_provider, subtitle.score, subtitle.language.forced
if not saved_any: if not saved_any:
@ -270,7 +273,7 @@ def download_subtitle(path, language, hi, forced, providers, providers_auth, sce
def manual_search(path, language, hi, forced, providers, providers_auth, sceneName, title, media_type): def manual_search(path, language, hi, forced, providers, providers_auth, sceneName, title, media_type):
logging.debug('BAZARR Manually searching subtitles for this file: ' + path) logging.debug('BAZARR Manually searching subtitles for this file: ' + path)
final_subtitles = [] final_subtitles = []
if hi == "True": if hi == "True":
@ -278,7 +281,7 @@ def manual_search(path, language, hi, forced, providers, providers_auth, sceneNa
else: else:
hi = "force non-HI" hi = "force non-HI"
language_set = set() language_set = set()
if forced == "True": if forced == "True":
providers_auth['podnapisi']['only_foreign'] = True providers_auth['podnapisi']['only_foreign'] = True
providers_auth['subscene']['only_foreign'] = True providers_auth['subscene']['only_foreign'] = True
@ -287,7 +290,7 @@ def manual_search(path, language, hi, forced, providers, providers_auth, sceneNa
providers_auth['podnapisi']['only_foreign'] = False providers_auth['podnapisi']['only_foreign'] = False
providers_auth['subscene']['only_foreign'] = False providers_auth['subscene']['only_foreign'] = False
providers_auth['opensubtitles']['only_foreign'] = False providers_auth['opensubtitles']['only_foreign'] = False
for lang in ast.literal_eval(language): for lang in ast.literal_eval(language):
lang = alpha3_from_alpha2(lang) lang = alpha3_from_alpha2(lang)
if lang == 'pob': if lang == 'pob':
@ -341,7 +344,7 @@ def manual_search(path, language, hi, forced, providers, providers_auth, sceneNa
if can_verify_series and not {"series", "season", "episode"}.issubset(matches): if can_verify_series and not {"series", "season", "episode"}.issubset(matches):
logging.debug(u"BAZARR Skipping %s, because it doesn't match our series/episode", s) logging.debug(u"BAZARR Skipping %s, because it doesn't match our series/episode", s)
continue continue
score = compute_score(matches, s, video, hearing_impaired=hi) score = compute_score(matches, s, video, hearing_impaired=hi)
not_matched = scores - matches not_matched = scores - matches
s.score = score s.score = score
@ -359,14 +362,15 @@ def manual_search(path, language, hi, forced, providers, providers_auth, sceneNa
return final_subtitles return final_subtitles
def manual_download_subtitle(path, language, hi, forced, subtitle, provider, providers_auth, sceneName, title, media_type): def manual_download_subtitle(path, language, hi, forced, subtitle, provider, providers_auth, sceneName, title,
media_type):
logging.debug('BAZARR Manually downloading subtitles for this file: ' + path) logging.debug('BAZARR Manually downloading subtitles for this file: ' + path)
if settings.general.getboolean('utf8_encode'): if settings.general.getboolean('utf8_encode'):
os.environ["SZ_KEEP_ENCODING"] = "" os.environ["SZ_KEEP_ENCODING"] = ""
else: else:
os.environ["SZ_KEEP_ENCODING"] = True os.environ["SZ_KEEP_ENCODING"] = True
subtitle = pickle.loads(codecs.decode(subtitle.encode(), "base64")) subtitle = pickle.loads(codecs.decode(subtitle.encode(), "base64"))
use_scenename = settings.general.getboolean('use_scenename') use_scenename = settings.general.getboolean('use_scenename')
use_postprocessing = settings.general.getboolean('use_postprocessing') use_postprocessing = settings.general.getboolean('use_postprocessing')
@ -394,7 +398,8 @@ def manual_download_subtitle(path, language, hi, forced, subtitle, provider, pro
try: try:
score = round(subtitle.score / max_score * 100, 2) score = round(subtitle.score / max_score * 100, 2)
fld = get_target_folder(path) fld = get_target_folder(path)
chmod = int(settings.general.chmod, 8) if not sys.platform.startswith('win') and settings.general.getboolean('chmod_enabled') else None 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, saved_subtitles = save_subtitles(video.original_path, [subtitle], single=single,
tags=None, # fixme tags=None, # fixme
directory=fld, directory=fld,
@ -423,7 +428,8 @@ def manual_download_subtitle(path, language, hi, forced, subtitle, provider, pro
if use_postprocessing is True: if use_postprocessing is True:
command = pp_replace(postprocessing_cmd, path, downloaded_path, downloaded_language, command = pp_replace(postprocessing_cmd, path, downloaded_path, downloaded_language,
downloaded_language_code2, downloaded_language_code3, subtitle.language.forced) downloaded_language_code2, downloaded_language_code3,
subtitle.language.forced)
try: try:
if os.name == 'nt': if os.name == 'nt':
codepage = subprocess.Popen("chcp", shell=True, stdout=subprocess.PIPE, codepage = subprocess.Popen("chcp", shell=True, stdout=subprocess.PIPE,
@ -452,12 +458,12 @@ def manual_download_subtitle(path, language, hi, forced, subtitle, provider, pro
'BAZARR Post-processing result for file ' + path + ' : Nothing returned from command execution') 'BAZARR Post-processing result for file ' + path + ' : Nothing returned from command execution')
else: else:
logging.info('BAZARR Post-processing result for file ' + path + ' : ' + out) logging.info('BAZARR Post-processing result for file ' + path + ' : ' + out)
if media_type == 'series': if media_type == 'series':
reversed_path = path_replace_reverse(path) reversed_path = path_replace_reverse(path)
else: else:
reversed_path = path_replace_reverse_movie(path) reversed_path = path_replace_reverse_movie(path)
return message, reversed_path, downloaded_language_code2, downloaded_provider, subtitle.score, subtitle.language.forced return message, reversed_path, downloaded_language_code2, downloaded_provider, subtitle.score, subtitle.language.forced
else: else:
logging.error( logging.error(
@ -486,14 +492,15 @@ def series_download_subtitles(no):
providers_auth = get_providers_auth() providers_auth = get_providers_auth()
count_episodes_details = len(episodes_details) count_episodes_details = len(episodes_details)
for i, episode in enumerate(episodes_details, 1): for i, episode in enumerate(episodes_details, 1):
for language in ast.literal_eval(episode[1]): for language in ast.literal_eval(episode[1]):
if language is not None: if language is not None:
notifications.write(msg='Searching for series subtitles...', queue='get_subtitle', item=i, length=count_episodes_details) notifications.write(msg='Searching for series subtitles...', queue='get_subtitle', item=i,
length=count_episodes_details)
result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)), result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)),
series_details[0], series_details[2], providers_list, series_details[0], series_details[2], providers_list,
providers_auth, str(episode[3]), series_details[1], 'series') providers_auth, str(episode[3]), series_details[1], 'series')
if result is not None: if result is not None:
message = result[0] message = result[0]
path = result[1] path = result[1]
@ -505,9 +512,10 @@ def series_download_subtitles(no):
history_log(1, no, episode[2], message, path, language_code, provider, score) history_log(1, no, episode[2], message, path, language_code, provider, score)
send_notifications(no, episode[2], message) send_notifications(no, episode[2], message)
list_missing_subtitles(no) list_missing_subtitles(no)
if count_episodes_details: if count_episodes_details:
notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent', button='refresh', queue='get_subtitle') notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent',
button='refresh', queue='get_subtitle')
def episode_download_subtitles(no): def episode_download_subtitles(no):
@ -515,16 +523,17 @@ def episode_download_subtitles(no):
monitored_only_query_string = ' AND monitored = "True"' monitored_only_query_string = ' AND monitored = "True"'
else: else:
monitored_only_query_string = "" monitored_only_query_string = ""
conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c_db = conn_db.cursor() c_db = conn_db.cursor()
episodes_details = c_db.execute( episodes_details = c_db.execute(
'SELECT table_episodes.path, table_episodes.missing_subtitles, table_episodes.sonarrEpisodeId, table_episodes.scene_name, table_shows.hearing_impaired, table_shows.title, table_shows.sonarrSeriesId, table_shows.forced FROM table_episodes INNER JOIN table_shows on table_shows.sonarrSeriesId = table_episodes.sonarrSeriesId WHERE table_episodes.sonarrEpisodeId = ?' + monitored_only_query_string, (no,)).fetchall() 'SELECT table_episodes.path, table_episodes.missing_subtitles, table_episodes.sonarrEpisodeId, table_episodes.scene_name, table_shows.hearing_impaired, table_shows.title, table_shows.sonarrSeriesId, table_shows.forced FROM table_episodes INNER JOIN table_shows on table_shows.sonarrSeriesId = table_episodes.sonarrSeriesId WHERE table_episodes.sonarrEpisodeId = ?' + monitored_only_query_string,
(no,)).fetchall()
c_db.close() c_db.close()
providers_list = get_providers() providers_list = get_providers()
providers_auth = get_providers_auth() providers_auth = get_providers_auth()
for episode in episodes_details: for episode in episodes_details:
for language in ast.literal_eval(episode[1]): for language in ast.literal_eval(episode[1]):
if language is not None: if language is not None:
@ -544,7 +553,7 @@ def episode_download_subtitles(no):
store_subtitles(path_replace(episode[0])) store_subtitles(path_replace(episode[0]))
history_log(1, episode[6], episode[2], message, path, language_code, provider, score) history_log(1, episode[6], episode[2], message, path, language_code, provider, score)
send_notifications(episode[6], episode[2], message) send_notifications(episode[6], episode[2], message)
list_missing_subtitles(episode[6]) list_missing_subtitles(episode[6])
@ -555,17 +564,17 @@ def movies_download_subtitles(no):
"SELECT path, missing_subtitles, radarrId, sceneName, hearing_impaired, title, forced FROM table_movies WHERE radarrId = ?", "SELECT path, missing_subtitles, radarrId, sceneName, hearing_impaired, title, forced FROM table_movies WHERE radarrId = ?",
(no,)).fetchone() (no,)).fetchone()
c_db.close() c_db.close()
providers_list = get_providers() providers_list = get_providers()
providers_auth = get_providers_auth() providers_auth = get_providers_auth()
count_movie = len(ast.literal_eval(movie[1])) count_movie = len(ast.literal_eval(movie[1]))
for i, language in enumerate(ast.literal_eval(movie[1]), 1): for i, language in enumerate(ast.literal_eval(movie[1]), 1):
if language is not None: if language is not None:
notifications.write(msg='Searching for movies subtitles', queue='get_subtitle', item=i, length=count_movie) notifications.write(msg='Searching for movies subtitles', queue='get_subtitle', item=i, length=count_movie)
result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), movie[4], result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), movie[4],
movie[6], providers_list, providers_auth, str(movie[3]), movie[5], 'movie') movie[6], providers_list, providers_auth, str(movie[3]), movie[5], 'movie')
if result is not None: if result is not None:
message = result[0] message = result[0]
path = result[1] path = result[1]
@ -577,9 +586,10 @@ def movies_download_subtitles(no):
history_log_movie(1, no, message, path, language_code, provider, score) history_log_movie(1, no, message, path, language_code, provider, score)
send_notifications_movie(no, message) send_notifications_movie(no, message)
list_missing_subtitles_movies(no) list_missing_subtitles_movies(no)
if count_movie: if count_movie:
notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent', button='refresh', queue='get_subtitle') notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent',
button='refresh', queue='get_subtitle')
def wanted_download_subtitles(path, l, count_episodes): def wanted_download_subtitles(path, l, count_episodes):
@ -617,10 +627,11 @@ def wanted_download_subtitles(path, l, count_episodes):
if attempt[i][0] == language: if attempt[i][0] == language:
language = language.split(':')[0] language = language.split(':')[0]
if search_active(attempt[i][1]): if search_active(attempt[i][1]):
notifications.write(msg='Searching for series subtitles...', queue='get_subtitle', item=l, length=count_episodes) notifications.write(msg='Searching for series subtitles...', queue='get_subtitle', item=l,
length=count_episodes)
result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)), result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)),
episode[4], episode[8], providers_list, providers_auth, episode[4], episode[8], providers_list, providers_auth,
str(episode[5]), episode[7], 'series') str(episode[5]), episode[7], 'series')
if result is not None: if result is not None:
message = result[0] message = result[0]
path = result[1] path = result[1]
@ -671,10 +682,11 @@ def wanted_download_subtitles_movie(path, l, count_movies):
if attempt[i][0] == language: if attempt[i][0] == language:
language = language.split(':')[0] language = language.split(':')[0]
if search_active(attempt[i][1]) is True: if search_active(attempt[i][1]) is True:
notifications.write(msg='Searching for movies subtitles...', queue='get_subtitle', item=l, length=count_movies) notifications.write(msg='Searching for movies subtitles...', queue='get_subtitle', item=l,
length=count_movies)
result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)),
movie[4], movie[8], providers_list, providers_auth, str(movie[5]), movie[4], movie[8], providers_list, providers_auth, str(movie[5]),
movie[7], 'movie') movie[7], 'movie')
if result is not None: if result is not None:
message = result[0] message = result[0]
path = result[1] path = result[1]
@ -696,7 +708,7 @@ def wanted_search_missing_subtitles():
db.create_function("path_substitution", 1, path_replace) db.create_function("path_substitution", 1, path_replace)
db.create_function("path_substitution_movie", 1, path_replace_movie) db.create_function("path_substitution_movie", 1, path_replace_movie)
c = db.cursor() c = db.cursor()
if settings.sonarr.getboolean('only_monitored'): if settings.sonarr.getboolean('only_monitored'):
monitored_only_query_string_sonarr = ' AND monitored = "True"' monitored_only_query_string_sonarr = ' AND monitored = "True"'
else: else:
@ -706,7 +718,7 @@ def wanted_search_missing_subtitles():
monitored_only_query_string_radarr = ' AND monitored = "True"' monitored_only_query_string_radarr = ' AND monitored = "True"'
else: else:
monitored_only_query_string_radarr = "" monitored_only_query_string_radarr = ""
c.execute( c.execute(
"SELECT path_substitution(path) FROM table_episodes WHERE missing_subtitles != '[]'" + monitored_only_query_string_sonarr) "SELECT path_substitution(path) FROM table_episodes WHERE missing_subtitles != '[]'" + monitored_only_query_string_sonarr)
episodes = c.fetchall() episodes = c.fetchall()
@ -719,7 +731,7 @@ def wanted_search_missing_subtitles():
providers = get_providers() providers = get_providers()
if settings.general.getboolean('use_sonarr'): if settings.general.getboolean('use_sonarr'):
if providers: if providers:
count_episodes= len(episodes) count_episodes = len(episodes)
for i, episode in enumerate(episodes, 1): for i, episode in enumerate(episodes, 1):
wanted_download_subtitles(episode[0], i, count_episodes) wanted_download_subtitles(episode[0], i, count_episodes)
else: else:
@ -736,8 +748,9 @@ def wanted_search_missing_subtitles():
logging.info("BAZARR All providers are throttled") logging.info("BAZARR All providers are throttled")
logging.info('BAZARR Finished searching for missing subtitles. Check histories for more information.') logging.info('BAZARR Finished searching for missing subtitles. Check histories for more information.')
notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent', button='refresh', queue='get_subtitle') notifications.write(msg='Searching completed. Please reload the page.', type='success', duration='permanent',
button='refresh', queue='get_subtitle')
def search_active(timestamp): def search_active(timestamp):
@ -763,7 +776,9 @@ def refine_from_db(path, video):
if isinstance(video, Episode): if isinstance(video, Episode):
db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c = db.cursor() c = db.cursor()
data = c.execute("SELECT table_shows.title, table_episodes.season, table_episodes.episode, table_episodes.title, table_shows.year, table_shows.tvdbId, table_shows.alternateTitles, table_episodes.format, table_episodes.resolution, table_episodes.video_codec, table_episodes.audio_codec FROM table_episodes INNER JOIN table_shows on table_shows.sonarrSeriesId = table_episodes.sonarrSeriesId WHERE table_episodes.path = ?", (unicode(path_replace_reverse(path)),)).fetchone() data = c.execute(
"SELECT table_shows.title, table_episodes.season, table_episodes.episode, table_episodes.title, table_shows.year, table_shows.tvdbId, table_shows.alternateTitles, table_episodes.format, table_episodes.resolution, table_episodes.video_codec, table_episodes.audio_codec FROM table_episodes INNER JOIN table_shows on table_shows.sonarrSeriesId = table_episodes.sonarrSeriesId WHERE table_episodes.path = ?",
(unicode(path_replace_reverse(path)),)).fetchone()
db.close() db.close()
if data: if data:
video.series, year, country = series_re.match(data[0]).groups() video.series, year, country = series_re.match(data[0]).groups()
@ -785,10 +800,12 @@ def refine_from_db(path, video):
elif isinstance(video, Movie): elif isinstance(video, Movie):
db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c = db.cursor() c = db.cursor()
data = c.execute("SELECT title, year, alternativeTitles, format, resolution, video_codec, audio_codec, imdbId FROM table_movies WHERE path = ?", (unicode(path_replace_reverse_movie(path)),)).fetchone() data = c.execute(
"SELECT title, year, alternativeTitles, format, resolution, video_codec, audio_codec, imdbId FROM table_movies WHERE path = ?",
(unicode(path_replace_reverse_movie(path)),)).fetchone()
db.close() db.close()
if data: if data:
video.title = re.sub(r'(\(\d\d\d\d\))' , '', data[0]) video.title = re.sub(r'(\(\d\d\d\d\))', '', data[0])
if data[1]: if data[1]:
if int(data[1]) > 0: video.year = int(data[1]) if int(data[1]) > 0: video.year = int(data[1])
if data[7]: video.imdb_id = data[7] if data[7]: video.imdb_id = data[7]
@ -801,7 +818,7 @@ def refine_from_db(path, video):
if data[5]: video.video_codec = data[5] if data[5]: video.video_codec = data[5]
if not video.audio_codec: if not video.audio_codec:
if data[6]: video.audio_codec = data[6] if data[6]: video.audio_codec = data[6]
return video return video
@ -809,12 +826,12 @@ def upgrade_subtitles():
days_to_upgrade_subs = settings.general.days_to_upgrade_subs days_to_upgrade_subs = settings.general.days_to_upgrade_subs
minimum_timestamp = ((datetime.now() - timedelta(days=int(days_to_upgrade_subs))) - minimum_timestamp = ((datetime.now() - timedelta(days=int(days_to_upgrade_subs))) -
datetime(1970, 1, 1)).total_seconds() datetime(1970, 1, 1)).total_seconds()
if settings.general.getboolean('upgrade_manual'): if settings.general.getboolean('upgrade_manual'):
query_actions = [1, 2, 3] query_actions = [1, 2, 3]
else: else:
query_actions = [1, 3] query_actions = [1, 3]
db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c = db.cursor() c = db.cursor()
episodes_list = c.execute("""SELECT table_history.video_path, table_history.language, table_history.score, episodes_list = c.execute("""SELECT table_history.video_path, table_history.language, table_history.score,
@ -839,25 +856,25 @@ def upgrade_subtitles():
GROUP BY table_history_movie.video_path, table_history_movie.language""", GROUP BY table_history_movie.video_path, table_history_movie.language""",
(minimum_timestamp,)).fetchall() (minimum_timestamp,)).fetchall()
db.close() db.close()
episodes_to_upgrade = [] episodes_to_upgrade = []
if settings.general.getboolean('use_sonarr'): if settings.general.getboolean('use_sonarr'):
for episode in episodes_list: for episode in episodes_list:
if os.path.exists(path_replace(episode[0])) and int(episode[2]) < 357: if os.path.exists(path_replace(episode[0])) and int(episode[2]) < 357:
episodes_to_upgrade.append(episode) episodes_to_upgrade.append(episode)
movies_to_upgrade = [] movies_to_upgrade = []
if settings.general.getboolean('use_radarr'): if settings.general.getboolean('use_radarr'):
for movie in movies_list: for movie in movies_list:
if os.path.exists(path_replace_movie(movie[0])) and int(movie[2]) < 117: if os.path.exists(path_replace_movie(movie[0])) and int(movie[2]) < 117:
movies_to_upgrade.append(movie) movies_to_upgrade.append(movie)
providers_list = get_providers() providers_list = get_providers()
providers_auth = get_providers_auth() providers_auth = get_providers_auth()
count_episode_to_upgrade = len(episodes_to_upgrade) count_episode_to_upgrade = len(episodes_to_upgrade)
count_movie_to_upgrade = len(movies_to_upgrade) count_movie_to_upgrade = len(movies_to_upgrade)
if settings.general.getboolean('use_sonarr'): if settings.general.getboolean('use_sonarr'):
for i, episode in enumerate(episodes_to_upgrade, 1): for i, episode in enumerate(episodes_to_upgrade, 1):
if episode[9] != "None": if episode[9] != "None":
@ -868,18 +885,18 @@ def upgrade_subtitles():
forced_languages = [l + ":forced" for l in desired_languages] + desired_languages forced_languages = [l + ":forced" for l in desired_languages] + desired_languages
else: else:
forced_languages = desired_languages forced_languages = desired_languages
if episode[1] in forced_languages: if episode[1] in forced_languages:
notifications.write(msg='Upgrading series subtitles...', notifications.write(msg='Upgrading series subtitles...',
queue='upgrade_subtitle', item=i, length=count_episode_to_upgrade) queue='upgrade_subtitle', item=i, length=count_episode_to_upgrade)
if episode[1].endswith('forced'): if episode[1].endswith('forced'):
language = episode[1].split(':')[0] language = episode[1].split(':')[0]
is_forced = "True" is_forced = "True"
else: else:
language = episode[1] language = episode[1]
is_forced = "False" is_forced = "False"
result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)), result = download_subtitle(path_replace(episode[0]), str(alpha3_from_alpha2(language)),
episode[3], is_forced, providers_list, providers_auth, str(episode[4]), episode[3], is_forced, providers_list, providers_auth, str(episode[4]),
episode[5], 'series', forced_minimum_score=int(episode[2]), episode[5], 'series', forced_minimum_score=int(episode[2]),
@ -894,7 +911,7 @@ def upgrade_subtitles():
store_subtitles(path_replace(episode[0])) store_subtitles(path_replace(episode[0]))
history_log(3, episode[6], episode[7], message, path, language_code, provider, score) history_log(3, episode[6], episode[7], message, path, language_code, provider, score)
send_notifications(episode[6], episode[7], message) send_notifications(episode[6], episode[7], message)
if settings.general.getboolean('use_radarr'): if settings.general.getboolean('use_radarr'):
for i, movie in enumerate(movies_to_upgrade, 1): for i, movie in enumerate(movies_to_upgrade, 1):
if movie[8] != "None": if movie[8] != "None":
@ -905,18 +922,18 @@ def upgrade_subtitles():
forced_languages = [l + ":forced" for l in desired_languages] + desired_languages forced_languages = [l + ":forced" for l in desired_languages] + desired_languages
else: else:
forced_languages = desired_languages forced_languages = desired_languages
if movie[1] in forced_languages: if movie[1] in forced_languages:
notifications.write(msg='Upgrading movie subtitles...', notifications.write(msg='Upgrading movie subtitles...',
queue='upgrade_subtitle', item=i, length=count_movie_to_upgrade) queue='upgrade_subtitle', item=i, length=count_movie_to_upgrade)
if movie[1].endswith('forced'): if movie[1].endswith('forced'):
language = movie[1].split(':')[0] language = movie[1].split(':')[0]
is_forced = "True" is_forced = "True"
else: else:
language = movie[1] language = movie[1]
is_forced = "False" is_forced = "False"
result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)), result = download_subtitle(path_replace_movie(movie[0]), str(alpha3_from_alpha2(language)),
movie[3], is_forced, providers_list, providers_auth, str(movie[4]), movie[3], is_forced, providers_list, providers_auth, str(movie[4]),
movie[5], 'movie', forced_minimum_score=int(movie[2]), is_upgrade=True) movie[5], 'movie', forced_minimum_score=int(movie[2]), is_upgrade=True)

@ -4,7 +4,6 @@ import os
import re import re
import types import types
import logging import logging
import sqlite3
import chardet import chardet
from bs4 import UnicodeDammit from bs4 import UnicodeDammit
@ -85,7 +84,7 @@ def get_target_folder(file_path):
if subfolder != "current" and fld_custom: if subfolder != "current" and fld_custom:
# specific subFolder requested, create it if it doesn't exist # specific subFolder requested, create it if it doesn't exist
fld_base = os.path.split(file_path)[0] fld_base = os.path.split(file_path)[0]
if subfolder == "absolute": if subfolder == "absolute":
# absolute folder # absolute folder
fld = fld_custom fld = fld_custom
@ -93,9 +92,9 @@ def get_target_folder(file_path):
fld = os.path.join(fld_base, fld_custom) fld = os.path.join(fld_base, fld_custom)
else: else:
fld = None fld = None
fld = force_unicode(fld) fld = force_unicode(fld)
if not os.path.isdir(fld): if not os.path.isdir(fld):
try: try:
os.makedirs(fld) os.makedirs(fld)
@ -104,7 +103,7 @@ def get_target_folder(file_path):
fld = None fld = None
else: else:
fld = None fld = None
return fld return fld

@ -22,7 +22,8 @@ if settings.general.anti_captcha_provider == 'anti-captcha' and settings.anticap
os.environ["ANTICAPTCHA_ACCOUNT_KEY"] = settings.anticaptcha.anti_captcha_key os.environ["ANTICAPTCHA_ACCOUNT_KEY"] = settings.anticaptcha.anti_captcha_key
elif settings.general.anti_captcha_provider == 'death-by-captcha' and settings.deathbycaptcha.username != "" and settings.deathbycaptcha.password != "": elif settings.general.anti_captcha_provider == 'death-by-captcha' and settings.deathbycaptcha.username != "" and settings.deathbycaptcha.password != "":
os.environ["ANTICAPTCHA_CLASS"] = 'DeathByCaptchaProxyLess' os.environ["ANTICAPTCHA_CLASS"] = 'DeathByCaptchaProxyLess'
os.environ["ANTICAPTCHA_ACCOUNT_KEY"] = ':'.join({settings.deathbycaptcha.username, settings.deathbycaptcha.password}) os.environ["ANTICAPTCHA_ACCOUNT_KEY"] = ':'.join(
{settings.deathbycaptcha.username, settings.deathbycaptcha.password})
else: else:
os.environ["ANTICAPTCHA_CLASS"] = '' os.environ["ANTICAPTCHA_CLASS"] = ''
@ -123,7 +124,7 @@ try:
providers_list.append(provider[0]) providers_list.append(provider[0])
else: else:
providers_list = None providers_list = None
if settings_providers: if settings_providers:
for provider in settings_providers: for provider in settings_providers:
if provider[0] == 'opensubtitles': if provider[0] == 'opensubtitles':
@ -135,7 +136,7 @@ try:
elif provider[0] == 'legendastv': elif provider[0] == 'legendastv':
settings.legendastv.username = provider[2] settings.legendastv.username = provider[2]
settings.legendastv.password = provider[3] settings.legendastv.password = provider[3]
settings.general.enabled_providers = u'' if not providers_list else ','.join(providers_list) settings.general.enabled_providers = u'' if not providers_list else ','.join(providers_list)
with open(os.path.join(args.config_dir, 'config', 'config.ini'), 'w+') as handle: with open(os.path.join(args.config_dir, 'config', 'config.ini'), 'w+') as handle:
settings.write(handle) settings.write(handle)
@ -167,20 +168,21 @@ if not os.path.exists(os.path.normpath(os.path.join(args.config_dir, 'config', '
def init_binaries(): def init_binaries():
exe = get_binary("unrar") exe = get_binary("unrar")
rarfile.UNRAR_TOOL = exe rarfile.UNRAR_TOOL = exe
rarfile.ORIG_UNRAR_TOOL = exe rarfile.ORIG_UNRAR_TOOL = exe
try: try:
rarfile.custom_check([rarfile.UNRAR_TOOL], True) rarfile.custom_check([rarfile.UNRAR_TOOL], True)
except: except:
logging.debug("custom check failed for: %s", exe) logging.debug("custom check failed for: %s", exe)
rarfile.OPEN_ARGS = rarfile.ORIG_OPEN_ARGS rarfile.OPEN_ARGS = rarfile.ORIG_OPEN_ARGS
rarfile.EXTRACT_ARGS = rarfile.ORIG_EXTRACT_ARGS rarfile.EXTRACT_ARGS = rarfile.ORIG_EXTRACT_ARGS
rarfile.TEST_ARGS = rarfile.ORIG_TEST_ARGS rarfile.TEST_ARGS = rarfile.ORIG_TEST_ARGS
logging.info("Using UnRAR from: %s", exe) logging.info("Using UnRAR from: %s", exe)
unrar = exe unrar = exe
return unrar return unrar
init_binaries() init_binaries()

@ -1,7 +1,7 @@
# coding=utf-8 # coding=utf-8
import sys
import os import os
import sys
def set_libs(): def set_libs():

@ -47,7 +47,8 @@ def store_subtitles(file):
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language) logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass pass
except Exception as e: except Exception as e:
logging.exception("BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(file)[1], file)) logging.exception(
"BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(file)[1], file))
pass pass
brazilian_portuguese = [".pt-br", ".pob", "pb"] brazilian_portuguese = [".pt-br", ".pob", "pb"]
@ -71,7 +72,7 @@ def store_subtitles(file):
logging.debug("BAZARR external subtitles detected: " + "pb:forced") logging.debug("BAZARR external subtitles detected: " + "pb:forced")
actual_subtitles.append( actual_subtitles.append(
[str("pb:forced"), path_replace_reverse(subtitle_path)]) [str("pb:forced"), path_replace_reverse(subtitle_path)])
elif str(language) != 'und': elif str(language) != 'und':
logging.debug("BAZARR external subtitles detected: " + str(language)) logging.debug("BAZARR external subtitles detected: " + str(language))
actual_subtitles.append( actual_subtitles.append(
@ -136,9 +137,10 @@ def store_subtitles_movie(file):
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language) logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass pass
except Exception as e: except Exception as e:
logging.exception("BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(file)[1], file)) logging.exception(
"BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(file)[1], file))
pass pass
dest_folder = get_subtitle_destination_folder() or '' dest_folder = get_subtitle_destination_folder() or ''
subliminal_patch.core.CUSTOM_PATHS = [dest_folder] if dest_folder else [] subliminal_patch.core.CUSTOM_PATHS = [dest_folder] if dest_folder else []
brazilian_portuguese = [".pt-br", ".pob", "pb"] brazilian_portuguese = [".pt-br", ".pob", "pb"]
@ -154,19 +156,23 @@ def store_subtitles_movie(file):
if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese)) is True: if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese)) is True:
logging.debug("BAZARR external subtitles detected: " + "pb") logging.debug("BAZARR external subtitles detected: " + "pb")
actual_subtitles.append( actual_subtitles.append(
[str("pb"), path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))]) [str("pb"),
path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))])
elif str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese_forced)) is True: elif str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese_forced)) is True:
logging.debug("BAZARR external subtitles detected: " + "pb:forced") logging.debug("BAZARR external subtitles detected: " + "pb:forced")
actual_subtitles.append( actual_subtitles.append(
[str("pb:forced"), path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))]) [str("pb:forced"),
path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))])
elif str(language) != 'und': elif str(language) != 'und':
logging.debug("BAZARR external subtitles detected: " + str(language)) logging.debug("BAZARR external subtitles detected: " + str(language))
actual_subtitles.append( actual_subtitles.append(
[str(language), path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))]) [str(language),
path_replace_reverse_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle))])
else: else:
if os.path.splitext(subtitle)[1] != ".sub": if os.path.splitext(subtitle)[1] != ".sub":
logging.debug("BAZARR falling back to file content analysis to detect language.") logging.debug("BAZARR falling back to file content analysis to detect language.")
with open(path_replace_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle)), 'r') as f: with open(path_replace_movie(os.path.join(os.path.dirname(file), dest_folder, subtitle)),
'r') as f:
text = list(islice(f, 100)) text = list(islice(f, 100))
text = ' '.join(text) text = ' '.join(text)
encoding = UnicodeDammit(text) encoding = UnicodeDammit(text)
@ -270,7 +276,8 @@ def list_missing_subtitles_movies(*no):
pass pass
conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c_db = conn_db.cursor() c_db = conn_db.cursor()
movies_subtitles = c_db.execute("SELECT radarrId, subtitles, languages, forced FROM table_movies" + query_string).fetchall() movies_subtitles = c_db.execute(
"SELECT radarrId, subtitles, languages, forced FROM table_movies" + query_string).fetchall()
c_db.close() c_db.close()
missing_subtitles_global = [] missing_subtitles_global = []
@ -326,7 +333,7 @@ def series_full_scan_subtitles():
episodes = c_db.execute("SELECT path FROM table_episodes").fetchall() episodes = c_db.execute("SELECT path FROM table_episodes").fetchall()
c_db.close() c_db.close()
count_episodes = len(episodes) count_episodes = len(episodes)
for i, episode in enumerate(episodes, 1): for i, episode in enumerate(episodes, 1):
notifications.write(msg='Updating all episodes subtitles from disk...', notifications.write(msg='Updating all episodes subtitles from disk...',
queue='list_subtitles_series', item=i, length=count_episodes) queue='list_subtitles_series', item=i, length=count_episodes)
@ -341,7 +348,7 @@ def movies_full_scan_subtitles():
movies = c_db.execute("SELECT path FROM table_movies").fetchall() movies = c_db.execute("SELECT path FROM table_movies").fetchall()
c_db.close() c_db.close()
count_movies = len(movies) count_movies = len(movies)
for i, movie in enumerate(movies, 1): for i, movie in enumerate(movies, 1):
notifications.write(msg='Updating all movies subtitles from disk...', notifications.write(msg='Updating all movies subtitles from disk...',
queue='list_subtitles_movies', item=i, length=count_movies) queue='list_subtitles_movies', item=i, length=count_movies)
@ -376,7 +383,7 @@ def movies_scan_subtitles(no):
def get_external_subtitles_path(file, subtitle): def get_external_subtitles_path(file, subtitle):
fld = os.path.dirname(file) fld = os.path.dirname(file)
if settings.general.subfolder == "current": if settings.general.subfolder == "current":
path = os.path.join(fld, subtitle) path = os.path.join(fld, subtitle)
elif settings.general.subfolder == "absolute": elif settings.general.subfolder == "absolute":
@ -397,5 +404,5 @@ def get_external_subtitles_path(file, subtitle):
path = None path = None
else: else:
path = None path = None
return path return path

@ -86,13 +86,12 @@ def configure_logging(debug=False):
logging.getLogger("subliminal").setLevel(logging.CRITICAL) logging.getLogger("subliminal").setLevel(logging.CRITICAL)
logging.getLogger("subliminal_patch").setLevel(logging.CRITICAL) logging.getLogger("subliminal_patch").setLevel(logging.CRITICAL)
logging.getLogger("subzero").setLevel(logging.ERROR) logging.getLogger("subzero").setLevel(logging.ERROR)
logging.getLogger("enzyme").setLevel(logging.CRITICAL) logging.getLogger("enzyme").setLevel(logging.CRITICAL)
logging.getLogger("guessit").setLevel(logging.WARNING) logging.getLogger("guessit").setLevel(logging.WARNING)
logging.getLogger("rebulk").setLevel(logging.WARNING) logging.getLogger("rebulk").setLevel(logging.WARNING)
logging.getLogger("stevedore.extension").setLevel(logging.CRITICAL) logging.getLogger("stevedore.extension").setLevel(logging.CRITICAL)
logging.getLogger("geventwebsocket.handler").setLevel(logging.WARNING) logging.getLogger("geventwebsocket.handler").setLevel(logging.WARNING)
class MyFilter(logging.Filter): class MyFilter(logging.Filter):

File diff suppressed because it is too large Load Diff

@ -11,13 +11,13 @@ from get_args import args
def update_notifier(): def update_notifier():
# define apprise object # define apprise object
a = apprise.Apprise() a = apprise.Apprise()
# Retrieve all of the details # Retrieve all of the details
results = a.details() results = a.details()
notifiers_new = [] notifiers_new = []
notifiers_old = [] notifiers_old = []
conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) conn_db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c_db = conn_db.cursor() c_db = conn_db.cursor()
notifiers_current = c_db.execute('SELECT name FROM table_settings_notifier').fetchall() notifiers_current = c_db.execute('SELECT name FROM table_settings_notifier').fetchall()
@ -28,15 +28,15 @@ def update_notifier():
else: else:
notifiers_old.append(x['service_name']) notifiers_old.append(x['service_name'])
notifier_current = [i[0] for i in notifiers_current] notifier_current = [i[0] for i in notifiers_current]
notifiers_to_delete = list(set(notifier_current) - set(notifiers_old)) notifiers_to_delete = list(set(notifier_current) - set(notifiers_old))
for notifier_new in notifiers_new: for notifier_new in notifiers_new:
c_db.execute('INSERT INTO `table_settings_notifier` (name, enabled) VALUES (?, ?);', (notifier_new, '0')) c_db.execute('INSERT INTO `table_settings_notifier` (name, enabled) VALUES (?, ?);', (notifier_new, '0'))
for notifier_to_delete in notifiers_to_delete: for notifier_to_delete in notifiers_to_delete:
c_db.execute('DELETE FROM `table_settings_notifier` WHERE name=?', (notifier_to_delete,)) c_db.execute('DELETE FROM `table_settings_notifier` WHERE name=?', (notifier_to_delete,))
conn_db.commit() conn_db.commit()
c_db.close() c_db.close()
@ -46,7 +46,7 @@ def get_notifier_providers():
c_db = conn_db.cursor() c_db = conn_db.cursor()
providers = c_db.execute('SELECT name, url FROM table_settings_notifier WHERE enabled = 1').fetchall() providers = c_db.execute('SELECT name, url FROM table_settings_notifier WHERE enabled = 1').fetchall()
c_db.close() c_db.close()
return providers return providers
@ -55,7 +55,7 @@ def get_series_name(sonarrSeriesId):
c_db = conn_db.cursor() c_db = conn_db.cursor()
data = c_db.execute('SELECT title FROM table_shows WHERE sonarrSeriesId = ?', (sonarrSeriesId,)).fetchone() data = c_db.execute('SELECT title FROM table_shows WHERE sonarrSeriesId = ?', (sonarrSeriesId,)).fetchone()
c_db.close() c_db.close()
return data[0] return data[0]
@ -65,7 +65,7 @@ def get_episode_name(sonarrEpisodeId):
data = c_db.execute('SELECT title, season, episode FROM table_episodes WHERE sonarrEpisodeId = ?', data = c_db.execute('SELECT title, season, episode FROM table_episodes WHERE sonarrEpisodeId = ?',
(sonarrEpisodeId,)).fetchone() (sonarrEpisodeId,)).fetchone()
c_db.close() c_db.close()
return data[0], data[1], data[2] return data[0], data[1], data[2]
@ -74,7 +74,7 @@ def get_movies_name(radarrId):
c_db = conn_db.cursor() c_db = conn_db.cursor()
data = c_db.execute('SELECT title FROM table_movies WHERE radarrId = ?', (radarrId,)).fetchone() data = c_db.execute('SELECT title FROM table_movies WHERE radarrId = ?', (radarrId,)).fetchone()
c_db.close() c_db.close()
return data[0] return data[0]
@ -82,13 +82,13 @@ def send_notifications(sonarrSeriesId, sonarrEpisodeId, message):
providers = get_notifier_providers() providers = get_notifier_providers()
series = get_series_name(sonarrSeriesId) series = get_series_name(sonarrSeriesId)
episode = get_episode_name(sonarrEpisodeId) episode = get_episode_name(sonarrEpisodeId)
apobj = apprise.Apprise() apobj = apprise.Apprise()
for provider in providers: for provider in providers:
if provider[1] is not None: if provider[1] is not None:
apobj.add(provider[1]) apobj.add(provider[1])
apobj.notify( apobj.notify(
title='Bazarr notification', title='Bazarr notification',
body=(series + ' - S' + str(episode[1]).zfill(2) + 'E' + str(episode[2]).zfill(2) + ' - ' + episode[ body=(series + ' - S' + str(episode[1]).zfill(2) + 'E' + str(episode[2]).zfill(2) + ' - ' + episode[
@ -99,13 +99,13 @@ def send_notifications(sonarrSeriesId, sonarrEpisodeId, message):
def send_notifications_movie(radarrId, message): def send_notifications_movie(radarrId, message):
providers = get_notifier_providers() providers = get_notifier_providers()
movie = get_movies_name(radarrId) movie = get_movies_name(radarrId)
apobj = apprise.Apprise() apobj = apprise.Apprise()
for provider in providers: for provider in providers:
if provider[1] is not None: if provider[1] is not None:
apobj.add(provider[1]) apobj.add(provider[1])
apobj.notify( apobj.notify(
title='Bazarr notification', title='Bazarr notification',
body=movie + ' : ' + message, body=movie + ' : ' + message,

@ -6,11 +6,11 @@ class Notify:
""" """
This class is used to read or write items to the notifications deque. This class is used to read or write items to the notifications deque.
""" """
def __init__(self): def __init__(self):
self.queue = deque(maxlen=10) self.queue = deque(maxlen=10)
def write(self, msg, type='info', duration='temporary', button='null', queue='main', item=0, length=0): def write(self, msg, type='info', duration='temporary', button='null', queue='main', item=0, length=0):
""" """
:param msg: The message to display. :param msg: The message to display.
:type msg: str :type msg: str
@ -27,15 +27,15 @@ class Notify:
:param length: The length of the group of item for progress bar :param length: The length of the group of item for progress bar
:type length: int :type length: int
""" """
self.queue.append(json.dumps([msg, type, duration, button, queue, item, length])) self.queue.append(json.dumps([msg, type, duration, button, queue, item, length]))
def read(self): def read(self):
""" """
:return: Return the oldest notification available. :return: Return the oldest notification available.
:rtype: str :rtype: str
""" """
if self.queue: if self.queue:
return self.queue.popleft() return self.queue.popleft()

@ -67,7 +67,6 @@ if str(get_localzone()) == "local":
else: else:
scheduler = BackgroundScheduler() scheduler = BackgroundScheduler()
global running_tasks global running_tasks
running_tasks = [] running_tasks = []
@ -81,19 +80,25 @@ def task_listener(event):
scheduler.add_listener(task_listener, EVENT_JOB_SUBMITTED | EVENT_JOB_EXECUTED) scheduler.add_listener(task_listener, EVENT_JOB_SUBMITTED | EVENT_JOB_EXECUTED)
def schedule_update_job(): def schedule_update_job():
if not args.no_update: if not args.no_update:
if settings.general.getboolean('auto_update'): if settings.general.getboolean('auto_update'):
scheduler.add_job(check_and_apply_update, IntervalTrigger(hours=6), max_instances=1, coalesce=True, scheduler.add_job(check_and_apply_update, IntervalTrigger(hours=6), max_instances=1, coalesce=True,
misfire_grace_time=15, id='update_bazarr', name='Update bazarr from source on Github' if not args.release_update else 'Update bazarr from release on Github', replace_existing=True) misfire_grace_time=15, id='update_bazarr',
name='Update bazarr from source on Github' if not args.release_update else 'Update bazarr from release on Github',
replace_existing=True)
else: else:
scheduler.add_job(check_and_apply_update, CronTrigger(year='2100'), hour=4, id='update_bazarr', scheduler.add_job(check_and_apply_update, CronTrigger(year='2100'), hour=4, id='update_bazarr',
name='Update bazarr from source on Github' if not args.release_update else 'Update bazarr from release on Github', replace_existing=True) name='Update bazarr from source on Github' if not args.release_update else 'Update bazarr from release on Github',
replace_existing=True)
scheduler.add_job(check_releases, IntervalTrigger(hours=6), max_instances=1, coalesce=True, scheduler.add_job(check_releases, IntervalTrigger(hours=6), max_instances=1, coalesce=True,
misfire_grace_time=15, id='update_release', name='Update release info', replace_existing=True) misfire_grace_time=15, id='update_release', name='Update release info',
replace_existing=True)
else: else:
scheduler.add_job(check_releases, IntervalTrigger(hours=6), max_instances=1, coalesce=True, misfire_grace_time=15, scheduler.add_job(check_releases, IntervalTrigger(hours=6), max_instances=1, coalesce=True,
misfire_grace_time=15,
id='update_release', name='Update release info', replace_existing=True) id='update_release', name='Update release info', replace_existing=True)
@ -123,7 +128,6 @@ scheduler.start()
def add_job(job, name=None, max_instances=1, coalesce=True, args=None): def add_job(job, name=None, max_instances=1, coalesce=True, args=None):
scheduler.add_job(job, DateTrigger(run_date=datetime.now()), name=name, id=name, max_instances=max_instances, scheduler.add_job(job, DateTrigger(run_date=datetime.now()), name=name, id=name, max_instances=max_instances,
coalesce=coalesce, args=args) coalesce=coalesce, args=args)

@ -95,16 +95,16 @@ if os.path.exists(os.path.join(args.config_dir, 'db', 'bazarr.db')):
else: else:
if settings.general.getboolean('use_radarr'): if settings.general.getboolean('use_radarr'):
execute_now('update_movies') execute_now('update_movies')
try: try:
c.execute('alter table table_shows add column "year" "text"') c.execute('alter table table_shows add column "year" "text"')
c.execute('alter table table_shows add column "alternateTitles" "text"') c.execute('alter table table_shows add column "alternateTitles" "text"')
c.execute('alter table table_episodes add column "format" "text"') c.execute('alter table table_episodes add column "format" "text"')
c.execute('alter table table_episodes add column "resolution" "text"') c.execute('alter table table_episodes add column "resolution" "text"')
c.execute('alter table table_episodes add column "video_codec" "text"') c.execute('alter table table_episodes add column "video_codec" "text"')
c.execute('alter table table_episodes add column "audio_codec" "text"') c.execute('alter table table_episodes add column "audio_codec" "text"')
c.execute('alter table table_movies add column "year" "text"') c.execute('alter table table_movies add column "year" "text"')
c.execute('alter table table_movies add column "alternativeTitles" "text"') c.execute('alter table table_movies add column "alternativeTitles" "text"')
c.execute('alter table table_movies add column "format" "text"') c.execute('alter table table_movies add column "format" "text"')
@ -121,22 +121,22 @@ if os.path.exists(os.path.join(args.config_dir, 'db', 'bazarr.db')):
execute_now('sync_episodes') execute_now('sync_episodes')
if settings.general.getboolean('use_radarr'): if settings.general.getboolean('use_radarr'):
execute_now('update_movies') execute_now('update_movies')
try: try:
c.execute('alter table table_history add column "video_path" "text"') c.execute('alter table table_history add column "video_path" "text"')
c.execute('alter table table_history add column "language" "text"') c.execute('alter table table_history add column "language" "text"')
c.execute('alter table table_history add column "provider" "text"') c.execute('alter table table_history add column "provider" "text"')
c.execute('alter table table_history add column "score" "text"') c.execute('alter table table_history add column "score" "text"')
c.execute('alter table table_history_movie add column "video_path" "text"') c.execute('alter table table_history_movie add column "video_path" "text"')
c.execute('alter table table_history_movie add column "language" "text"') c.execute('alter table table_history_movie add column "language" "text"')
c.execute('alter table table_history_movie add column "provider" "text"') c.execute('alter table table_history_movie add column "provider" "text"')
c.execute('alter table table_history_movie add column "score" "text"') c.execute('alter table table_history_movie add column "score" "text"')
db.commit() db.commit()
except: except:
pass pass
try: try:
c.execute('alter table table_shows add column "forced" "text"') c.execute('alter table table_shows add column "forced" "text"')
except: except:
@ -144,7 +144,7 @@ if os.path.exists(os.path.join(args.config_dir, 'db', 'bazarr.db')):
else: else:
c.execute('UPDATE table_shows SET forced="False"') c.execute('UPDATE table_shows SET forced="False"')
db.commit() db.commit()
try: try:
c.execute('alter table table_movies add column "forced" "text"') c.execute('alter table table_movies add column "forced" "text"')
db.commit() db.commit()
@ -153,5 +153,5 @@ if os.path.exists(os.path.join(args.config_dir, 'db', 'bazarr.db')):
else: else:
c.execute('UPDATE table_movies SET forced="False"') c.execute('UPDATE table_movies SET forced="False"')
db.commit() db.commit()
db.close() db.close()

@ -9,61 +9,64 @@ from whichcraft import which
from get_args import args from get_args import args
def history_log(action, sonarrSeriesId, sonarrEpisodeId, description, video_path=None, language=None, provider=None, score=None, forced=False): def history_log(action, sonarrSeriesId, sonarrEpisodeId, description, video_path=None, language=None, provider=None,
score=None, forced=False):
# Open database connection # Open database connection
db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c = db.cursor() c = db.cursor()
if forced: if forced:
language = language + ":forced" language = language + ":forced"
# Get Sonarr API URL from database config table # Get Sonarr API URL from database config table
history = c.execute( history = c.execute(
'''INSERT INTO table_history(action, sonarrSeriesId, sonarrEpisodeId, timestamp, description, video_path, language, provider, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', '''INSERT INTO table_history(action, sonarrSeriesId, sonarrEpisodeId, timestamp, description, video_path, language, provider, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(action, sonarrSeriesId, sonarrEpisodeId, time.time(), description, video_path, language, provider, score)) (action, sonarrSeriesId, sonarrEpisodeId, time.time(), description, video_path, language, provider, score))
# Commit changes to DB # Commit changes to DB
db.commit() db.commit()
# Close database connection # Close database connection
db.close() db.close()
def history_log_movie(action, radarrId, description, video_path=None, language=None, provider=None, score=None, forced=False): def history_log_movie(action, radarrId, description, video_path=None, language=None, provider=None, score=None,
forced=False):
# Open database connection # Open database connection
db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30) db = sqlite3.connect(os.path.join(args.config_dir, 'db', 'bazarr.db'), timeout=30)
c = db.cursor() c = db.cursor()
if forced: if forced:
language = language + ":forced" language = language + ":forced"
history = c.execute( history = c.execute(
'''INSERT INTO table_history_movie(action, radarrId, timestamp, description, video_path, language, provider, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', '''INSERT INTO table_history_movie(action, radarrId, timestamp, description, video_path, language, provider, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
(action, radarrId, time.time(), description, video_path, language, provider, score)) (action, radarrId, time.time(), description, video_path, language, provider, score))
# Commit changes to DB # Commit changes to DB
db.commit() db.commit()
# Close database connection # Close database connection
db.close() db.close()
def get_binary(name): def get_binary(name):
binaries_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'bin')) binaries_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'bin'))
exe = None exe = None
installed_exe = which(name) installed_exe = which(name)
if installed_exe and os.path.isfile(installed_exe): if installed_exe and os.path.isfile(installed_exe):
return installed_exe return installed_exe
else: else:
if platform.system() == "Windows": # Windows if platform.system() == "Windows": # Windows
exe = os.path.abspath(os.path.join(binaries_dir, "Windows", "i386", name, "%s.exe" % name)) exe = os.path.abspath(os.path.join(binaries_dir, "Windows", "i386", name, "%s.exe" % name))
elif platform.system() == "Darwin": # MacOSX elif platform.system() == "Darwin": # MacOSX
exe = os.path.abspath(os.path.join(binaries_dir, "MacOSX", "i386", name, name)) exe = os.path.abspath(os.path.join(binaries_dir, "MacOSX", "i386", name, name))
elif platform.system() == "Linux": # Linux elif platform.system() == "Linux": # Linux
exe = os.path.abspath(os.path.join(binaries_dir, "Linux", platform.machine(), name, name)) exe = os.path.abspath(os.path.join(binaries_dir, "Linux", platform.machine(), name, name))
if exe and os.path.isfile(exe): if exe and os.path.isfile(exe):
return exe return exe

Loading…
Cancel
Save