code cleanup: get_series

pull/788/head
ngosang 5 years ago
parent 9cf2cdb868
commit 93cdd562b7

@ -6,197 +6,193 @@ import os
import requests import requests
import logging import logging
from queueconfig import notifications from queueconfig import notifications
from collections import OrderedDict
import datetime
from get_args import args
from config import settings, url_sonarr from config import settings, url_sonarr
from list_subtitles import list_missing_subtitles from list_subtitles import list_missing_subtitles
from database import database, dict_converter from database import database, dict_converter
from utils import get_sonarr_version from utils import get_sonarr_version
import six
from helper import path_replace from helper import path_replace
def update_series(): def update_series():
notifications.write(msg="Update series list from Sonarr is running...", queue='get_series') notifications.write(msg="Update series list from Sonarr is running...", queue='get_series')
apikey_sonarr = settings.sonarr.apikey apikey_sonarr = settings.sonarr.apikey
if apikey_sonarr is None:
return
sonarr_version = get_sonarr_version() sonarr_version = get_sonarr_version()
serie_default_enabled = settings.general.getboolean('serie_default_enabled') serie_default_enabled = settings.general.getboolean('serie_default_enabled')
serie_default_language = settings.general.serie_default_language serie_default_language = settings.general.serie_default_language
serie_default_hi = settings.general.serie_default_hi serie_default_hi = settings.general.serie_default_hi
serie_default_forced = settings.general.serie_default_forced serie_default_forced = settings.general.serie_default_forced
audio_profiles = get_profile_list()
if apikey_sonarr is None:
pass # Get shows data from Sonarr
else: url_sonarr_api_series = url_sonarr() + "/api/series?apikey=" + apikey_sonarr
audio_profiles = get_profile_list() try:
r = requests.get(url_sonarr_api_series, timeout=60, verify=False)
# Get shows data from Sonarr r.raise_for_status()
url_sonarr_api_series = url_sonarr() + "/api/series?apikey=" + apikey_sonarr except requests.exceptions.HTTPError:
try: logging.exception("BAZARR Error trying to get series from Sonarr. Http error.")
r = requests.get(url_sonarr_api_series, timeout=60, verify=False) return
r.raise_for_status() except requests.exceptions.ConnectionError:
except requests.exceptions.HTTPError as errh: logging.exception("BAZARR Error trying to get series from Sonarr. Connection Error.")
logging.exception("BAZARR Error trying to get series from Sonarr. Http error.") return
return except requests.exceptions.Timeout:
except requests.exceptions.ConnectionError as errc: logging.exception("BAZARR Error trying to get series from Sonarr. Timeout Error.")
logging.exception("BAZARR Error trying to get series from Sonarr. Connection Error.") return
return except requests.exceptions.RequestException:
except requests.exceptions.Timeout as errt: logging.exception("BAZARR Error trying to get series from Sonarr.")
logging.exception("BAZARR Error trying to get series from Sonarr. Timeout Error.") return
return
except requests.exceptions.RequestException as err: # Get current shows in DB
logging.exception("BAZARR Error trying to get series from Sonarr.") current_shows_db = database.execute("SELECT sonarrSeriesId FROM table_shows")
return
current_shows_db_list = [x['sonarrSeriesId'] for x in current_shows_db]
current_shows_sonarr = []
series_to_update = []
series_to_add = []
series_list_length = len(r.json())
for i, show in enumerate(r.json(), 1):
notifications.write(msg="Getting series data from Sonarr...", queue='get_series', item=i,
length=series_list_length)
overview = show['overview'] if 'overview' in show else ''
poster = ''
fanart = ''
for image in show['images']:
if image['coverType'] == 'poster':
poster_big = image['url'].split('?')[0]
poster = os.path.splitext(poster_big)[0] + '-250' + os.path.splitext(poster_big)[1]
if image['coverType'] == 'fanart':
fanart = image['url'].split('?')[0]
alternate_titles = None
if show['alternateTitles'] is not None:
alternate_titles = str([item['title'] for item in show['alternateTitles']])
if sonarr_version.startswith('2'):
audio_language = profile_id_to_language(show['qualityProfileId'], audio_profiles)
else:
audio_language = profile_id_to_language(show['languageProfileId'], audio_profiles)
# Add shows in Sonarr to current shows list
current_shows_sonarr.append(show['id'])
if show['id'] in current_shows_db_list:
series_to_update.append({'title': show["title"],
'path': show["path"],
'tvdbId': int(show["tvdbId"]),
'sonarrSeriesId': int(show["id"]),
'overview': overview,
'poster': poster,
'fanart': fanart,
'audio_language': audio_language,
'sortTitle': show['sortTitle'],
'year': show['year'],
'alternateTitles': alternate_titles})
else: else:
# Get current shows in DB if serie_default_enabled is True:
current_shows_db = database.execute("SELECT sonarrSeriesId FROM table_shows") series_to_add.append({'title': show["title"],
'path': show["path"],
current_shows_db_list = [x['sonarrSeriesId'] for x in current_shows_db] 'tvdbId': show["tvdbId"],
current_shows_sonarr = [] 'languages': serie_default_language,
series_to_update = [] 'hearing_impaired': serie_default_hi,
series_to_add = [] 'sonarrSeriesId': show["id"],
altered_series = [] 'overview': overview,
'poster': poster,
seriesListLength = len(r.json()) 'fanart': fanart,
for i, show in enumerate(r.json(), 1): 'audio_language': audio_language,
notifications.write(msg="Getting series data from Sonarr...", queue='get_series', item=i, length=seriesListLength) 'sortTitle': show['sortTitle'],
'year': show['year'],
if 'overview' in show: 'alternateTitles': alternate_titles,
overview = show['overview'] 'forced': serie_default_forced})
else: else:
overview = '' series_to_add.append({'title': show["title"],
'path': show["path"],
poster = '' 'tvdbId': show["tvdbId"],
fanart = '' 'sonarrSeriesId': show["id"],
for image in show['images']: 'overview': overview,
if image['coverType'] == 'poster': 'poster': poster,
poster_big = image['url'].split('?')[0] 'fanart': fanart,
poster = os.path.splitext(poster_big)[0] + '-250' + os.path.splitext(poster_big)[1] 'audio_language': audio_language,
'sortTitle': show['sortTitle'],
if image['coverType'] == 'fanart': 'year': show['year'],
fanart = image['url'].split('?')[0] 'alternateTitles': alternate_titles})
if show['alternateTitles'] != None: # Remove old series from DB
alternateTitles = str([item['title'] for item in show['alternateTitles']]) removed_series = list(set(current_shows_db_list) - set(current_shows_sonarr))
else:
alternateTitles = None for series in removed_series:
database.execute("DELETE FROM table_shows WHERE sonarrSEriesId=?", (series,))
# Add shows in Sonarr to current shows list
current_shows_sonarr.append(show['id']) # Update existing series in DB
series_in_db_list = []
if show['id'] in current_shows_db_list: series_in_db = database.execute("SELECT title, path, tvdbId, sonarrSeriesId, overview, poster, fanart, "
series_to_update.append({'title': show["title"], "audio_language, sortTitle, year, alternateTitles FROM table_shows")
'path': show["path"],
'tvdbId': int(show["tvdbId"]), for item in series_in_db:
'sonarrSeriesId': int(show["id"]), series_in_db_list.append(item)
'overview': overview,
'poster': poster, series_to_update_list = [i for i in series_to_update if i not in series_in_db_list]
'fanart': fanart,
'audio_language': profile_id_to_language((show['qualityProfileId'] if get_sonarr_version().startswith('2') else show['languageProfileId']), audio_profiles), for updated_series in series_to_update_list:
'sortTitle': show['sortTitle'], query = dict_converter.convert(updated_series)
'year': show['year'], database.execute('''UPDATE table_shows SET ''' + query.keys_update + ''' WHERE sonarrSeriesId = ?''',
'alternateTitles': alternateTitles}) query.values + (updated_series['sonarrSeriesId'],))
else:
if serie_default_enabled is True: # Insert new series in DB
series_to_add.append({'title': show["title"], for added_series in series_to_add:
'path': show["path"], query = dict_converter.convert(added_series)
'tvdbId': show["tvdbId"], result = database.execute(
'languages': serie_default_language, '''INSERT OR IGNORE INTO table_shows(''' + query.keys_insert + ''') VALUES(''' +
'hearing_impaired': serie_default_hi, query.question_marks + ''')''', query.values)
'sonarrSeriesId': show["id"], if result:
'overview': overview, list_missing_subtitles(no=added_series['sonarrSeriesId'])
'poster': poster, else:
'fanart': fanart, logging.debug('BAZARR unable to insert this series into the database:',
'audio_language': profile_id_to_language((show['qualityProfileId'] if sonarr_version.startswith('2') else show['languageProfileId']), audio_profiles), path_replace(added_series['path']))
'sortTitle': show['sortTitle'],
'year': show['year'], logging.debug('BAZARR All series synced from Sonarr into database.')
'alternateTitles': alternateTitles,
'forced': serie_default_forced})
else:
series_to_add.append({'title': show["title"],
'path': show["path"],
'tvdbId': show["tvdbId"],
'sonarrSeriesId': show["id"],
'overview': overview,
'poster': poster,
'fanart': fanart,
'audio_language': profile_id_to_language((show['qualityProfileId'] if sonarr_version.startswith('2') else show['languageProfileId']), audio_profiles),
'sortTitle': show['sortTitle'],
'year': show['year'],
'alternateTitles': alternateTitles})
# Remove old series from DB
removed_series = list(set(current_shows_db_list) - set(current_shows_sonarr))
for series in removed_series:
database.execute("DELETE FROM table_shows WHERE sonarrSEriesId=?",(series,))
# Update existing series in DB
series_in_db_list = []
series_in_db = database.execute("SELECT title, path, tvdbId, sonarrSeriesId, overview, poster, fanart, "
"audio_language, sortTitle, year, alternateTitles FROM table_shows")
for item in series_in_db:
series_in_db_list.append(item)
series_to_update_list = [i for i in series_to_update if i not in series_in_db_list]
for updated_series in series_to_update_list:
query = dict_converter.convert(updated_series)
database.execute('''UPDATE table_shows SET ''' + query.keys_update + ''' WHERE sonarrSeriesId = ?''',
query.values + (updated_series['sonarrSeriesId'],))
# Insert new series in DB
for added_series in series_to_add:
query = dict_converter.convert(added_series)
result = database.execute(
'''INSERT OR IGNORE INTO table_shows(''' + query.keys_insert + ''') VALUES(''' +
query.question_marks + ''')''', query.values)
if result:
list_missing_subtitles(no=added_series['sonarrSeriesId'])
else:
logging.debug('BAZARR unable to insert this series into the database:',
path_replace(added_series['path']))
logging.debug('BAZARR All series synced from Sonarr into database.')
def get_profile_list(): def get_profile_list():
apikey_sonarr = settings.sonarr.apikey apikey_sonarr = settings.sonarr.apikey
sonarr_version = get_sonarr_version() sonarr_version = get_sonarr_version()
profiles_list = [] profiles_list = []
# Get profiles data from Sonarr
# Get profiles data from Sonarr
if sonarr_version.startswith('2'): if sonarr_version.startswith('2'):
url_sonarr_api_series = url_sonarr() + "/api/profile?apikey=" + apikey_sonarr url_sonarr_api_series = url_sonarr() + "/api/profile?apikey=" + apikey_sonarr
elif sonarr_version.startswith('3'): else:
url_sonarr_api_series = url_sonarr() + "/api/v3/languageprofile?apikey=" + apikey_sonarr url_sonarr_api_series = url_sonarr() + "/api/v3/languageprofile?apikey=" + apikey_sonarr
try: try:
profiles_json = requests.get(url_sonarr_api_series, timeout=60, verify=False) profiles_json = requests.get(url_sonarr_api_series, timeout=60, verify=False)
except requests.exceptions.ConnectionError as errc: except requests.exceptions.ConnectionError:
logging.exception("BAZARR Error trying to get profiles from Sonarr. Connection Error.") logging.exception("BAZARR Error trying to get profiles from Sonarr. Connection Error.")
except requests.exceptions.Timeout as errt: return None
except requests.exceptions.Timeout:
logging.exception("BAZARR Error trying to get profiles from Sonarr. Timeout Error.") logging.exception("BAZARR Error trying to get profiles from Sonarr. Timeout Error.")
except requests.exceptions.RequestException as err: return None
except requests.exceptions.RequestException:
logging.exception("BAZARR Error trying to get profiles from Sonarr.") logging.exception("BAZARR Error trying to get profiles from Sonarr.")
else: return None
# Parsing data returned from Sonarr
if sonarr_version.startswith('2'):
for profile in profiles_json.json():
profiles_list.append([profile['id'], profile['language'].capitalize()])
elif sonarr_version.startswith('3'):
for profile in profiles_json.json():
profiles_list.append([profile['id'], profile['name'].capitalize()])
return profiles_list # Parsing data returned from Sonarr
if sonarr_version.startswith('2'):
for profile in profiles_json.json():
profiles_list.append([profile['id'], profile['language'].capitalize()])
else:
for profile in profiles_json.json():
profiles_list.append([profile['id'], profile['name'].capitalize()])
return None return profiles_list
def profile_id_to_language(id, profiles): def profile_id_to_language(id_, profiles):
for profile in profiles: for profile in profiles:
if id == profile[0]: if id_ == profile[0]:
return profile[1] return profile[1]

Loading…
Cancel
Save