Better exception handling and logging when calling Sonarr and Radarr

pull/115/merge
morpheus65535 6 years ago
parent 8825a83c95
commit ad4203fb8e

@ -130,7 +130,7 @@ def image_proxy(url):
apikey = get_sonarr_settings()[2] apikey = get_sonarr_settings()[2]
url_image = url_sonarr_short + '/' + url + '?apikey=' + apikey url_image = url_sonarr_short + '/' + url + '?apikey=' + apikey
try: try:
img_pil = Image.open(BytesIO(requests.get(url_sonarr_short + '/api' + url_image.split(url_sonarr)[1]).content)) img_pil = Image.open(BytesIO(requests.get(url_sonarr_short + '/api' + url_image.split(url_sonarr)[1], timeout=15).content))
except: except:
return None return None
else: else:
@ -148,10 +148,10 @@ def image_proxy_movies(url):
apikey = get_radarr_settings()[2] apikey = get_radarr_settings()[2]
try: try:
url_image = (url_radarr_short + '/' + url + '?apikey=' + apikey).replace('/fanart.jpg', '/banner.jpg') url_image = (url_radarr_short + '/' + url + '?apikey=' + apikey).replace('/fanart.jpg', '/banner.jpg')
img_pil = Image.open(BytesIO(requests.get(url_radarr_short + '/api' + url_image.split(url_radarr)[1]).content)) img_pil = Image.open(BytesIO(requests.get(url_radarr_short + '/api' + url_image.split(url_radarr)[1], timeout=15).content))
except: except:
url_image = url_radarr_short + '/' + url + '?apikey=' + apikey url_image = url_radarr_short + '/' + url + '?apikey=' + apikey
img_pil = Image.open(BytesIO(requests.get(url_radarr_short + '/api' + url_image.split(url_radarr)[1]).content)) img_pil = Image.open(BytesIO(requests.get(url_radarr_short + '/api' + url_image.split(url_radarr)[1], timeout=15).content))
img_buffer = BytesIO() img_buffer = BytesIO()
img_pil.tobytes() img_pil.tobytes()

@ -36,18 +36,29 @@ def sync_episodes():
for seriesId in seriesIdList: for seriesId in seriesIdList:
# Get episodes data for a series from Sonarr # Get episodes data for a series from Sonarr
url_sonarr_api_episode = url_sonarr + "/api/episode?seriesId=" + str(seriesId[0]) + "&apikey=" + apikey_sonarr url_sonarr_api_episode = url_sonarr + "/api/episode?seriesId=" + str(seriesId[0]) + "&apikey=" + apikey_sonarr
r = requests.get(url_sonarr_api_episode) try:
for episode in r.json(): r = requests.get(url_sonarr_api_episode, timeout=15)
if 'hasFile' in episode: r.raise_for_status()
if episode['hasFile'] is True: except requests.exceptions.HTTPError as errh:
if 'episodeFile' in episode: logging.exception("Error trying to get episodes from Sonarr. Http error.")
if episode['episodeFile']['size'] > 20480: except requests.exceptions.ConnectionError as errc:
# Add shows in Sonarr to current shows list logging.exception("Error trying to get episodes from Sonarr. Connection Error.")
if 'sceneName' in episode['episodeFile']: except requests.exceptions.Timeout as errt:
sceneName = episode['episodeFile']['sceneName'] logging.exception("Error trying to get episodes from Sonarr. Timeout Error.")
else: except requests.exceptions.RequestException as err:
sceneName = None logging.exception("Error trying to get episodes from Sonarr.")
current_episodes_sonarr.append((episode['seriesId'], episode['id'], episode['title'], episode['episodeFile']['path'], episode['seasonNumber'], episode['episodeNumber'], sceneName)) else:
for episode in r.json():
if 'hasFile' in episode:
if episode['hasFile'] is True:
if 'episodeFile' in episode:
if episode['episodeFile']['size'] > 20480:
# Add shows in Sonarr to current shows list
if 'sceneName' in episode['episodeFile']:
sceneName = episode['episodeFile']['sceneName']
else:
sceneName = None
current_episodes_sonarr.append((episode['seriesId'], episode['id'], episode['title'], episode['episodeFile']['path'], episode['seasonNumber'], episode['episodeNumber'], sceneName))
added_episodes = list(set(current_episodes_sonarr) - set(current_episodes_db)) added_episodes = list(set(current_episodes_sonarr) - set(current_episodes_db))
removed_episodes = list(set(current_episodes_db) - set(current_episodes_sonarr)) removed_episodes = list(set(current_episodes_db) - set(current_episodes_sonarr))

@ -1,6 +1,7 @@
import os import os
import sqlite3 import sqlite3
import requests import requests
import logging
from get_general_settings import * from get_general_settings import *
from list_subtitles import * from list_subtitles import *
@ -25,69 +26,79 @@ def update_movies():
# Get movies data from radarr # Get movies data from radarr
url_radarr_api_movies = url_radarr + "/api/movie?apikey=" + apikey_radarr url_radarr_api_movies = url_radarr + "/api/movie?apikey=" + apikey_radarr
r = requests.get(url_radarr_api_movies) try:
r = requests.get(url_radarr_api_movies, timeout=15)
# Get current movies in DB r.raise_for_status()
current_movies_db = c.execute('SELECT tmdbId FROM table_movies').fetchall() except requests.exceptions.HTTPError as errh:
current_movies_db_list = [x[0] for x in current_movies_db] logging.exception("Error trying to get movies from Radarr. Http error.")
current_movies_radarr = [] except requests.exceptions.ConnectionError as errc:
logging.exception("Error trying to get movies from Radarr. Connection Error.")
for movie in r.json(): except requests.exceptions.Timeout as errt:
if movie['hasFile'] is True: logging.exception("Error trying to get movies from Radarr. Timeout Error.")
try: except requests.exceptions.RequestException as err:
overview = unicode(movie['overview']) logging.exception("Error trying to get movies from Radarr.")
except: else:
overview = "" # Get current movies in DB
try: current_movies_db = c.execute('SELECT tmdbId FROM table_movies').fetchall()
poster_big = movie['images'][0]['url'] current_movies_db_list = [x[0] for x in current_movies_db]
poster = os.path.splitext(poster_big)[0] + '-500' + os.path.splitext(poster_big)[1] current_movies_radarr = []
except:
poster = "" for movie in r.json():
try: if movie['hasFile'] is True:
fanart = movie['images'][1]['url'] try:
except: overview = unicode(movie['overview'])
fanart = "" except:
overview = ""
if 'movieFile' in movie: try:
if 'sceneName' in movie['movieFile']: poster_big = movie['images'][0]['url']
sceneName = movie['movieFile']['sceneName'] poster = os.path.splitext(poster_big)[0] + '-500' + os.path.splitext(poster_big)[1]
except:
poster = ""
try:
fanart = movie['images'][1]['url']
except:
fanart = ""
if 'movieFile' in movie:
if 'sceneName' in movie['movieFile']:
sceneName = movie['movieFile']['sceneName']
else:
sceneName = None
else: else:
sceneName = None sceneName = None
else:
sceneName = None
# Add movies in radarr to current movies list
current_movies_radarr.append(unicode(movie['tmdbId']))
# Detect file separator
if movie['path'][0] == "/":
separator = "/"
else:
separator = "\\"
# Update or insert movies list in database table
try:
if movie_default_enabled == 'True':
c.execute('''INSERT INTO table_movies(title, path, tmdbId, languages,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName) VALUES (?,?,?,?,?, ?, ?, ?, ?, ?, ?)''', (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie_default_language, movie_default_hi, movie["id"], overview, poster, fanart, profile_id_to_language(movie['qualityProfileId']), sceneName))
else:
c.execute('''INSERT INTO table_movies(title, path, tmdbId, languages,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName) VALUES (?,?,?,(SELECT languages FROM table_movies WHERE tmdbId = ?),(SELECT `hearing_impaired` FROM table_movies WHERE tmdbId = ?), ?, ?, ?, ?, ?, ?)''', (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["tmdbId"], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language(movie['qualityProfileId']), sceneName))
except:
c.execute('''UPDATE table_movies SET title = ?, path = ?, tmdbId = ?, radarrId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ?, sceneName = ? WHERE tmdbid = ?''', (movie["title"],movie["path"] + separator + movie['movieFile']['relativePath'],movie["tmdbId"],movie["id"],overview,poster,fanart,profile_id_to_language(movie['qualityProfileId']),sceneName,movie["tmdbId"]))
# Commit changes to database table
db.commit()
# Delete movies not in radarr anymore # Add movies in radarr to current movies list
added_movies = list(set(current_movies_radarr) - set(current_movies_db_list)) current_movies_radarr.append(unicode(movie['tmdbId']))
removed_movies = list(set(current_movies_db_list) - set(current_movies_radarr))
for removed_movie in removed_movies: # Detect file separator
c.execute('DELETE FROM table_movies WHERE radarrId = ?', (removed_movie,)) if movie['path'][0] == "/":
db.commit() separator = "/"
else:
separator = "\\"
# Update or insert movies list in database table
try:
if movie_default_enabled == 'True':
c.execute('''INSERT INTO table_movies(title, path, tmdbId, languages,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName) VALUES (?,?,?,?,?, ?, ?, ?, ?, ?, ?)''', (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie_default_language, movie_default_hi, movie["id"], overview, poster, fanart, profile_id_to_language(movie['qualityProfileId']), sceneName))
else:
c.execute('''INSERT INTO table_movies(title, path, tmdbId, languages,`hearing_impaired`, radarrId, overview, poster, fanart, `audio_language`, sceneName) VALUES (?,?,?,(SELECT languages FROM table_movies WHERE tmdbId = ?),(SELECT `hearing_impaired` FROM table_movies WHERE tmdbId = ?), ?, ?, ?, ?, ?, ?)''', (movie["title"], movie["path"] + separator + movie['movieFile']['relativePath'], movie["tmdbId"], movie["tmdbId"], movie["tmdbId"], movie["id"], overview, poster, fanart, profile_id_to_language(movie['qualityProfileId']), sceneName))
except:
c.execute('''UPDATE table_movies SET title = ?, path = ?, tmdbId = ?, radarrId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ?, sceneName = ? WHERE tmdbid = ?''', (movie["title"],movie["path"] + separator + movie['movieFile']['relativePath'],movie["tmdbId"],movie["id"],overview,poster,fanart,profile_id_to_language(movie['qualityProfileId']),sceneName,movie["tmdbId"]))
# Commit changes to database table
db.commit()
# Delete movies not in radarr anymore
added_movies = list(set(current_movies_radarr) - set(current_movies_db_list))
removed_movies = list(set(current_movies_db_list) - set(current_movies_radarr))
for removed_movie in removed_movies:
c.execute('DELETE FROM table_movies WHERE radarrId = ?', (removed_movie,))
db.commit()
for added_movie in added_movies: for added_movie in added_movies:
added_path = c.execute('SELECT path FROM table_movies WHERE tmdbId = ?', (added_movie,)).fetchone() added_path = c.execute('SELECT path FROM table_movies WHERE tmdbId = ?', (added_movie,)).fetchone()
store_subtitles_movie(path_replace_movie(added_path[0])) store_subtitles_movie(path_replace_movie(added_path[0]))
# Close database connection # Close database connection
db.close() db.close()
@ -101,14 +112,22 @@ def get_profile_list():
apikey_radarr = get_radarr_settings()[2] apikey_radarr = get_radarr_settings()[2]
# Get profiles data from radarr # Get profiles data from radarr
url_radarr_api_movies = url_radarr + "/api/profile?apikey=" + apikey_radarr
profiles_json = requests.get(url_radarr_api_movies)
global profiles_list global profiles_list
profiles_list = [] profiles_list = []
# Parsing data returned from radarr url_radarr_api_movies = url_radarr + "/api/profile?apikey=" + apikey_radarr
for profile in profiles_json.json(): try:
profiles_list.append([profile['id'], profile['language'].capitalize()]) profiles_json = requests.get(url_radarr_api_movies, timeout=15)
except requests.exceptions.ConnectionError as errc:
logging.exception("Error trying to get profiles from Sonarr. Connection Error.")
except requests.exceptions.Timeout as errt:
logging.exception("Error trying to get profiles from Sonarr. Timeout Error.")
except requests.exceptions.RequestException as err:
logging.exception("Error trying to get profiles from Sonarr.")
else:
# Parsing data returned from radarr
for profile in profiles_json.json():
profiles_list.append([profile['id'], profile['language'].capitalize()])
def profile_id_to_language(id): def profile_id_to_language(id):
for profile in profiles_list: for profile in profiles_list:

@ -1,6 +1,7 @@
import os import os
import sqlite3 import sqlite3
import requests import requests
import logging
from get_general_settings import * from get_general_settings import *
from list_subtitles import * from list_subtitles import *
@ -25,50 +26,60 @@ def update_series():
# Get shows data from Sonarr # Get shows data from Sonarr
url_sonarr_api_series = url_sonarr + "/api/series?apikey=" + apikey_sonarr url_sonarr_api_series = url_sonarr + "/api/series?apikey=" + apikey_sonarr
r = requests.get(url_sonarr_api_series) try:
r = requests.get(url_sonarr_api_series, timeout=15)
# Get current shows in DB r.raise_for_status()
current_shows_db = c.execute('SELECT tvdbId FROM table_shows').fetchall() except requests.exceptions.HTTPError as errh:
current_shows_db_list = [x[0] for x in current_shows_db] logging.exception("Error trying to get series from Sonarr. Http error.")
current_shows_sonarr = [] except requests.exceptions.ConnectionError as errc:
logging.exception("Error trying to get series from Sonarr. Connection Error.")
for show in r.json(): except requests.exceptions.Timeout as errt:
try: logging.exception("Error trying to get series from Sonarr. Timeout Error.")
overview = unicode(show['overview']) except requests.exceptions.RequestException as err:
except: logging.exception("Error trying to get series from Sonarr.")
overview = "" else:
try: # Get current shows in DB
poster_big = show['images'][2]['url'].split('?')[0] current_shows_db = c.execute('SELECT tvdbId FROM table_shows').fetchall()
poster = os.path.splitext(poster_big)[0] + '-250' + os.path.splitext(poster_big)[1] current_shows_db_list = [x[0] for x in current_shows_db]
except: current_shows_sonarr = []
poster = ""
try: for show in r.json():
fanart = show['images'][0]['url'].split('?')[0] try:
except: overview = unicode(show['overview'])
fanart = "" except:
overview = ""
# Add shows in Sonarr to current shows list try:
current_shows_sonarr.append(show['tvdbId']) poster_big = show['images'][2]['url'].split('?')[0]
poster = os.path.splitext(poster_big)[0] + '-250' + os.path.splitext(poster_big)[1]
# Update or insert shows list in database table except:
try: poster = ""
if serie_default_enabled == 'True': try:
c.execute('''INSERT INTO table_shows(title, path, tvdbId, languages,`hearing_impaired`, sonarrSeriesId, overview, poster, fanart, `audio_language`, sortTitle) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (show["title"], show["path"], show["tvdbId"], serie_default_language, serie_default_hi, show["id"], overview, poster, fanart, profile_id_to_language(show['qualityProfileId']), show['sortTitle'])) fanart = show['images'][0]['url'].split('?')[0]
list_missing_subtitles(show["id"]) except:
else: fanart = ""
c.execute('''INSERT INTO table_shows(title, path, tvdbId, languages,`hearing_impaired`, sonarrSeriesId, overview, poster, fanart, `audio_language`, sortTitle) VALUES (?,?,?,(SELECT languages FROM table_shows WHERE tvdbId = ?),(SELECT `hearing_impaired` FROM table_shows WHERE tvdbId = ?), ?, ?, ?, ?, ?, ?)''', (show["title"], show["path"], show["tvdbId"], show["tvdbId"], show["tvdbId"], show["id"], overview, poster, fanart, profile_id_to_language(show['qualityProfileId']), show['sortTitle']))
except: # Add shows in Sonarr to current shows list
c.execute('''UPDATE table_shows SET title = ?, path = ?, tvdbId = ?, sonarrSeriesId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ? , sortTitle = ? WHERE tvdbid = ?''', (show["title"],show["path"],show["tvdbId"],show["id"],overview,poster,fanart,profile_id_to_language((show['qualityProfileId'] if sonarr_version == 2 else show['languageProfileId'])),show['sortTitle'],show["tvdbId"])) current_shows_sonarr.append(show['tvdbId'])
# Delete shows not in Sonarr anymore # Update or insert shows list in database table
deleted_items = [] try:
for item in current_shows_db_list: if serie_default_enabled == 'True':
if item not in current_shows_sonarr: c.execute('''INSERT INTO table_shows(title, path, tvdbId, languages,`hearing_impaired`, sonarrSeriesId, overview, poster, fanart, `audio_language`, sortTitle) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (show["title"], show["path"], show["tvdbId"], serie_default_language, serie_default_hi, show["id"], overview, poster, fanart, profile_id_to_language(show['qualityProfileId']), show['sortTitle']))
deleted_items.append(tuple([item])) list_missing_subtitles(show["id"])
c.executemany('DELETE FROM table_shows WHERE tvdbId = ?',deleted_items) else:
c.execute('''INSERT INTO table_shows(title, path, tvdbId, languages,`hearing_impaired`, sonarrSeriesId, overview, poster, fanart, `audio_language`, sortTitle) VALUES (?,?,?,(SELECT languages FROM table_shows WHERE tvdbId = ?),(SELECT `hearing_impaired` FROM table_shows WHERE tvdbId = ?), ?, ?, ?, ?, ?, ?)''', (show["title"], show["path"], show["tvdbId"], show["tvdbId"], show["tvdbId"], show["id"], overview, poster, fanart, profile_id_to_language(show['qualityProfileId']), show['sortTitle']))
# Commit changes to database table except:
db.commit() c.execute('''UPDATE table_shows SET title = ?, path = ?, tvdbId = ?, sonarrSeriesId = ?, overview = ?, poster = ?, fanart = ?, `audio_language` = ? , sortTitle = ? WHERE tvdbid = ?''', (show["title"],show["path"],show["tvdbId"],show["id"],overview,poster,fanart,profile_id_to_language((show['qualityProfileId'] if sonarr_version == 2 else show['languageProfileId'])),show['sortTitle'],show["tvdbId"]))
# Delete shows not in Sonarr anymore
deleted_items = []
for item in current_shows_db_list:
if item not in current_shows_sonarr:
deleted_items.append(tuple([item]))
c.executemany('DELETE FROM table_shows WHERE tvdbId = ?',deleted_items)
# Commit changes to database table
db.commit()
# Close database connection # Close database connection
db.close() db.close()
@ -80,23 +91,48 @@ def get_profile_list():
apikey_sonarr = get_sonarr_settings()[2] apikey_sonarr = get_sonarr_settings()[2]
# Get profiles data from Sonarr # Get profiles data from Sonarr
error = False
url_sonarr_api_series = url_sonarr + "/api/profile?apikey=" + apikey_sonarr url_sonarr_api_series = url_sonarr + "/api/profile?apikey=" + apikey_sonarr
profiles_json = requests.get(url_sonarr_api_series) try:
profiles_json = requests.get(url_sonarr_api_series, timeout=15)
except requests.exceptions.ConnectionError as errc:
error = True
logging.exception("Error trying to get profiles from Sonarr. Connection Error.")
except requests.exceptions.Timeout as errt:
error = True
logging.exception("Error trying to get profiles from Sonarr. Timeout Error.")
except requests.exceptions.RequestException as err:
error = True
logging.exception("Error trying to get profiles from Sonarr.")
url_sonarr_api_series_v3 = url_sonarr + "/api/v3/languageprofile?apikey=" + apikey_sonarr url_sonarr_api_series_v3 = url_sonarr + "/api/v3/languageprofile?apikey=" + apikey_sonarr
profiles_json_v3 = requests.get(url_sonarr_api_series_v3) try:
profiles_json_v3 = requests.get(url_sonarr_api_series_v3, timeout=15)
except requests.exceptions.ConnectionError as errc:
error = True
logging.exception("Error trying to get profiles from Sonarr. Connection Error.")
except requests.exceptions.Timeout as errt:
error = True
logging.exception("Error trying to get profiles from Sonarr. Timeout Error.")
except requests.exceptions.RequestException as err:
error = True
logging.exception("Error trying to get profiles from Sonarr.")
global profiles_list global profiles_list
profiles_list = [] profiles_list = []
# Parsing data returned from Sonarr if error is False:
global sonarr_version # Parsing data returned from Sonarr
if type(profiles_json_v3.json()) != list: global sonarr_version
sonarr_version = 2 if type(profiles_json_v3.json()) != list:
for profile in profiles_json.json(): sonarr_version = 2
profiles_list.append([profile['id'], profile['language'].capitalize()]) for profile in profiles_json.json():
else: profiles_list.append([profile['id'], profile['language'].capitalize()])
sonarr_version = 3 else:
for profile in profiles_json_v3.json(): sonarr_version = 3
profiles_list.append([profile['id'], profile['name'].capitalize()]) for profile in profiles_json_v3.json():
profiles_list.append([profile['id'], profile['name'].capitalize()])
def profile_id_to_language(id): def profile_id_to_language(id):
for profile in profiles_list: for profile in profiles_list:

Loading…
Cancel
Save