using arr for lookups now

pull/165/head
meisnate12 4 years ago
parent f5fc9a8509
commit eaee4d9abd

@ -345,7 +345,7 @@ class Config:
radarr_params["add"] = check_for_attribute(lib, "add", parent="radarr", var_type="bool", default=self.general["radarr"]["add"], save=False) radarr_params["add"] = check_for_attribute(lib, "add", parent="radarr", var_type="bool", default=self.general["radarr"]["add"], save=False)
radarr_params["search"] = check_for_attribute(lib, "search", parent="radarr", var_type="bool", default=self.general["radarr"]["search"], save=False) radarr_params["search"] = check_for_attribute(lib, "search", parent="radarr", var_type="bool", default=self.general["radarr"]["search"], save=False)
radarr_params["tag"] = check_for_attribute(lib, "search", parent="radarr", var_type="lower_list", default=self.general["radarr"]["tag"], default_is_none=True, save=False) radarr_params["tag"] = check_for_attribute(lib, "search", parent="radarr", var_type="lower_list", default=self.general["radarr"]["tag"], default_is_none=True, save=False)
library.Radarr = RadarrAPI(self.TMDb, radarr_params) library.Radarr = RadarrAPI(radarr_params)
except Failed as e: except Failed as e:
util.print_multiline(e, error=True) util.print_multiline(e, error=True)
logger.info(f"{params['name']} library's Radarr Connection {'Failed' if library.Radarr is None else 'Successful'}") logger.info(f"{params['name']} library's Radarr Connection {'Failed' if library.Radarr is None else 'Successful'}")
@ -367,7 +367,7 @@ class Config:
sonarr_params["search"] = check_for_attribute(lib, "search", parent="sonarr", var_type="bool", default=self.general["sonarr"]["search"], save=False) sonarr_params["search"] = check_for_attribute(lib, "search", parent="sonarr", var_type="bool", default=self.general["sonarr"]["search"], save=False)
sonarr_params["season_folder"] = check_for_attribute(lib, "season_folder", parent="sonarr", var_type="bool", default=self.general["sonarr"]["season_folder"], save=False) sonarr_params["season_folder"] = check_for_attribute(lib, "season_folder", parent="sonarr", var_type="bool", default=self.general["sonarr"]["season_folder"], save=False)
sonarr_params["tag"] = check_for_attribute(lib, "search", parent="sonarr", var_type="lower_list", default=self.general["sonarr"]["tag"], default_is_none=True, save=False) sonarr_params["tag"] = check_for_attribute(lib, "search", parent="sonarr", var_type="lower_list", default=self.general["sonarr"]["tag"], default_is_none=True, save=False)
library.Sonarr = SonarrAPI(self.TVDb, sonarr_params, library.Plex.language) library.Sonarr = SonarrAPI(sonarr_params, library.Plex.language)
except Failed as e: except Failed as e:
util.print_multiline(e, error=True) util.print_multiline(e, error=True)
logger.info(f"{params['name']} library's Sonarr Connection {'Failed' if library.Sonarr is None else 'Successful'}") logger.info(f"{params['name']} library's Sonarr Connection {'Failed' if library.Sonarr is None else 'Successful'}")

@ -6,11 +6,11 @@ from retrying import retry
logger = logging.getLogger("Plex Meta Manager") logger = logging.getLogger("Plex Meta Manager")
class RadarrAPI: class RadarrAPI:
def __init__(self, tmdb, params): def __init__(self, params):
self.url_params = {"apikey": f"{params['token']}"}
self.base_url = f"{params['url']}/api{'/v3' if params['version'] == 'v3' else ''}/" self.base_url = f"{params['url']}/api{'/v3' if params['version'] == 'v3' else ''}/"
self.token = params["token"]
try: try:
result = requests.get(f"{self.base_url}system/status", params=self.url_params).json() result = requests.get(f"{self.base_url}system/status", params={"apikey": f"{self.token}"}).json()
except Exception: except Exception:
util.print_stacktrace() util.print_stacktrace()
raise Failed(f"Radarr Error: Could not connect to Radarr at {params['url']}") raise Failed(f"Radarr Error: Could not connect to Radarr at {params['url']}")
@ -29,7 +29,6 @@ class RadarrAPI:
if not self.quality_profile_id: if not self.quality_profile_id:
raise Failed(f"Radarr Error: quality_profile: {params['quality_profile']} does not exist in radarr. Profiles available: {profiles}") raise Failed(f"Radarr Error: quality_profile: {params['quality_profile']} does not exist in radarr. Profiles available: {profiles}")
self.tags = self.get_tags() self.tags = self.get_tags()
self.tmdb = tmdb
self.url = params["url"] self.url = params["url"]
self.version = params["version"] self.version = params["version"]
self.token = params["token"] self.token = params["token"]
@ -50,6 +49,13 @@ class RadarrAPI:
if added: if added:
self.tags = self.get_tags() self.tags = self.get_tags()
def lookup(self, tmdb_id):
results = self.send_get("movie/lookup", params={"term": f"tmdb:{tmdb_id}"})
if results:
return results[0]
else:
raise Failed(f"Sonarr Error: TMDb ID: {tmdb_id} not found")
def add_tmdb(self, tmdb_ids, tags=None, folder=None): def add_tmdb(self, tmdb_ids, tags=None, folder=None):
logger.info("") logger.info("")
logger.debug(f"TMDb IDs: {tmdb_ids}") logger.debug(f"TMDb IDs: {tmdb_ids}")
@ -62,54 +68,49 @@ class RadarrAPI:
tag_nums = [self.tags[label] for label in tags if label in self.tags] tag_nums = [self.tags[label] for label in tags if label in self.tags]
for tmdb_id in tmdb_ids: for tmdb_id in tmdb_ids:
try: try:
movie = self.tmdb.get_movie(tmdb_id) movie_info = self.lookup(tmdb_id)
except Failed as e: except Failed as e:
logger.error(e) logger.error(e)
continue continue
try: poster_url = None
year = movie.release_date.split("-")[0] for image in movie_info["images"]:
except AttributeError: if "coverType" in image and image["coverType"] == "poster" and "remoteUrl" in image:
logger.error(f"TMDb Error: No year for ({tmdb_id}) {movie.title}") poster_url = image["remoteUrl"]
continue
if year.isdigit() is False:
logger.error(f"TMDb Error: No release date yet for ({tmdb_id}) {movie.title}")
continue
poster = f"https://image.tmdb.org/t/p/original{movie.poster_path}"
titleslug = re.sub(r"([^\s\w]|_)+", "", f"{movie.title} {year}").replace(" ", "-").lower()
url_json = { url_json = {
"title": movie.title, "title": movie_info["title"],
f"{'qualityProfileId' if self.version == 'v3' else 'profileId'}": self.quality_profile_id, f"{'qualityProfileId' if self.version == 'v3' else 'profileId'}": self.quality_profile_id,
"year": int(year), "year": int(movie_info["year"]),
"tmdbid": int(tmdb_id), "tmdbid": int(tmdb_id),
"titleslug": titleslug, "titleslug": movie_info["titleSlug"],
"monitored": True, "monitored": True,
"rootFolderPath": self.root_folder_path if folder is None else folder, "rootFolderPath": self.root_folder_path if folder is None else folder,
"images": [{"covertype": "poster", "url": poster}], "images": [{"covertype": "poster", "url": poster_url}],
"addOptions": {"searchForMovie": self.search} "addOptions": {"searchForMovie": self.search}
} }
if tag_nums: if tag_nums:
url_json["tags"] = tag_nums url_json["tags"] = tag_nums
response = self.send_post("movie", url_json) response = self.send_post("movie", url_json)
if response.status_code < 400: if response.status_code < 400:
logger.info(f"Added to Radarr | {tmdb_id:<6} | {movie.title}") logger.info(f"Added to Radarr | {tmdb_id:<6} | {movie_info['title']}")
add_count += 1 add_count += 1
else: else:
try: try:
logger.error(f"Radarr Error: ({tmdb_id}) {movie.title}: ({response.status_code}) {response.json()[0]['errorMessage']}") logger.error(f"Radarr Error: ({tmdb_id}) {movie_info['title']}: ({response.status_code}) {response.json()[0]['errorMessage']}")
except KeyError: except KeyError:
logger.debug(url_json) logger.debug(url_json)
logger.error(f"Radarr Error: {response.json()}") logger.error(f"Radarr Error: {response.json()}")
logger.info(f"{add_count} Movie{'s' if add_count > 1 else ''} added to Radarr") logger.info(f"{add_count} Movie{'s' if add_count > 1 else ''} added to Radarr")
@retry(stop_max_attempt_number=6, wait_fixed=10000) @retry(stop_max_attempt_number=6, wait_fixed=10000)
def send_get(self, url): def send_get(self, url, params=None):
return requests.get(f"{self.base_url}{url}", params=self.url_params).json() url_params = {"apikey": f"{self.token}"}
if params:
for param in params:
url_params[param] = params[param]
return requests.get(f"{self.base_url}{url}", params=url_params).json()
@retry(stop_max_attempt_number=6, wait_fixed=10000) @retry(stop_max_attempt_number=6, wait_fixed=10000)
def send_post(self, url, url_json): def send_post(self, url, url_json):
return requests.post(f"{self.base_url}{url}", json=url_json, params=self.url_params) return requests.post(f"{self.base_url}{url}", json=url_json, params={"apikey": f"{self.token}"})

@ -6,11 +6,11 @@ from retrying import retry
logger = logging.getLogger("Plex Meta Manager") logger = logging.getLogger("Plex Meta Manager")
class SonarrAPI: class SonarrAPI:
def __init__(self, tvdb, params, language): def __init__(self, params, language):
self.url_params = {"apikey": f"{params['token']}"}
self.base_url = f"{params['url']}/api{'/v3/' if params['version'] == 'v3' else '/'}" self.base_url = f"{params['url']}/api{'/v3/' if params['version'] == 'v3' else '/'}"
self.token = params["token"]
try: try:
result = requests.get(f"{self.base_url}system/status", params=self.url_params).json() result = requests.get(f"{self.base_url}system/status", params={"apikey": f"{self.token}"}).json()
except Exception: except Exception:
util.print_stacktrace() util.print_stacktrace()
raise Failed(f"Sonarr Error: Could not connect to Sonarr at {params['url']}") raise Failed(f"Sonarr Error: Could not connect to Sonarr at {params['url']}")
@ -45,11 +45,8 @@ class SonarrAPI:
self.language_profile_id = 1 self.language_profile_id = 1
self.tags = self.get_tags() self.tags = self.get_tags()
self.tvdb = tvdb
self.language = language self.language = language
self.url = params["url"]
self.version = params["version"] self.version = params["version"]
self.token = params["token"]
self.root_folder_path = params["root_folder_path"] self.root_folder_path = params["root_folder_path"]
self.add = params["add"] self.add = params["add"]
self.search = params["search"] self.search = params["search"]
@ -68,6 +65,13 @@ class SonarrAPI:
if added: if added:
self.tags = self.get_tags() self.tags = self.get_tags()
def lookup(self, tvdb_id):
results = self.send_get("series/lookup", params={"term": f"tvdb:{tvdb_id}"})
if results:
return results[0]
else:
raise Failed(f"Sonarr Error: TVDb ID: {tvdb_id} not found")
def add_tvdb(self, tvdb_ids, tags=None, folder=None): def add_tvdb(self, tvdb_ids, tags=None, folder=None):
logger.info("") logger.info("")
logger.debug(f"TVDb IDs: {tvdb_ids}") logger.debug(f"TVDb IDs: {tvdb_ids}")
@ -80,45 +84,52 @@ class SonarrAPI:
tag_nums = [self.tags[label] for label in tags if label in self.tags] tag_nums = [self.tags[label] for label in tags if label in self.tags]
for tvdb_id in tvdb_ids: for tvdb_id in tvdb_ids:
try: try:
show = self.tvdb.get_series(self.language, tvdb_id) show_info = self.lookup(tvdb_id)
except Failed as e: except Failed as e:
logger.error(e) logger.error(e)
continue continue
titleslug = re.sub(r"([^\s\w]|_)+", "", show.title).replace(" ", "-").lower() poster_url = None
for image in show_info["images"]:
if "coverType" in image and image["coverType"] == "poster" and "remoteUrl" in image:
poster_url = image["remoteUrl"]
url_json = { url_json = {
"title": show.title, "title": show_info["title"],
f"{'qualityProfileId' if self.version == 'v3' else 'profileId'}": self.quality_profile_id, f"{'qualityProfileId' if self.version == 'v3' else 'profileId'}": self.quality_profile_id,
"languageProfileId": self.language_profile_id, "languageProfileId": self.language_profile_id,
"tvdbId": int(tvdb_id), "tvdbId": int(tvdb_id),
"titleslug": titleslug, "titleslug": show_info["titleSlug"],
"language": self.language, "language": self.language,
"monitored": True, "monitored": True,
"seasonFolder": self.season_folder, "seasonFolder": self.season_folder,
"rootFolderPath": self.root_folder_path if folder is None else folder, "rootFolderPath": self.root_folder_path if folder is None else folder,
"seasons": [], "seasons": [],
"images": [{"covertype": "poster", "url": show.poster_path}], "images": [{"covertype": "poster", "url": poster_url}],
"addOptions": {"searchForMissingEpisodes": self.search} "addOptions": {"searchForMissingEpisodes": self.search}
} }
if tag_nums: if tag_nums:
url_json["tags"] = tag_nums url_json["tags"] = tag_nums
response = self.send_post("series", url_json) response = self.send_post("series", url_json)
if response.status_code < 400: if response.status_code < 400:
logger.info(f"Added to Sonarr | {tvdb_id:<6} | {show.title}") logger.info(f"Added to Sonarr | {tvdb_id:<6} | {show_info['title']}")
add_count += 1 add_count += 1
else: else:
try: try:
logger.error(f"Sonarr Error: ({tvdb_id}) {show.title}: ({response.status_code}) {response.json()[0]['errorMessage']}") logger.error(f"Sonarr Error: ({tvdb_id}) {show_info['title']}: ({response.status_code}) {response.json()[0]['errorMessage']}")
except KeyError: except KeyError:
logger.debug(url_json) logger.debug(url_json)
logger.error(f"Sonarr Error: {response.json()}") logger.error(f"Sonarr Error: {response.json()}")
logger.info(f"{add_count} Show{'s' if add_count > 1 else ''} added to Sonarr") logger.info(f"{add_count} Show{'s' if add_count > 1 else ''} added to Sonarr")
@retry(stop_max_attempt_number=6, wait_fixed=10000) @retry(stop_max_attempt_number=6, wait_fixed=10000)
def send_get(self, url): def send_get(self, url, params=None):
return requests.get(f"{self.base_url}{url}", params=self.url_params).json() url_params = {"apikey": f"{self.token}"}
if params:
for param in params:
url_params[param] = params[param]
return requests.get(f"{self.base_url}{url}", params=url_params).json()
@retry(stop_max_attempt_number=6, wait_fixed=10000) @retry(stop_max_attempt_number=6, wait_fixed=10000)
def send_post(self, url, url_json): def send_post(self, url, url_json):
return requests.post(f"{self.base_url}{url}", json=url_json, params=self.url_params) return requests.post(f"{self.base_url}{url}", json=url_json, params={"apikey": f"{self.token}"})

Loading…
Cancel
Save