Skip to content

Commit

Permalink
traktarr
Browse files Browse the repository at this point in the history
  • Loading branch information
MrDoobPG authored and MrDoobPG committed Nov 6, 2019
1 parent 934de09 commit 333ad1d
Show file tree
Hide file tree
Showing 19 changed files with 2,815 additions and 2 deletions.
84 changes: 84 additions & 0 deletions menu/pgtrakt/helpers/misc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
from copy import copy

from misc.log import logger

log = logger.get_logger(__name__)


def get_response_dict(response, key_field=None, key_value=None):
found_response = None
try:
if isinstance(response, list):
if not key_field or not key_value:
found_response = response[0]
else:
for result in response:
if isinstance(result, dict) and key_field in result and result[key_field] == key_value:
found_response = result
break

if not found_response:
log.error("Unable to find a result with key %s where the value is %s", key_field, key_value)

elif isinstance(response, dict):
found_response = response
else:
log.error("Unexpected response instance type of %s for %s", type(response).__name__, response)

except Exception:
log.exception("Exception determining response for %s: ", response)
return found_response


def backoff_handler(details):
log.warning("Backing off {wait:0.1f} seconds afters {tries} tries "
"calling function {target} with args {args} and kwargs "
"{kwargs}".format(**details))


def dict_merge(dct, merge_dct):
for k, v in merge_dct.items():
import collections

if k in dct and isinstance(dct[k], dict) and isinstance(merge_dct[k], collections.Mapping):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]

return dct


def unblacklist_genres(genre, blacklisted_genres):
genres = genre.split(',')
for allow_genre in genres:
if allow_genre in blacklisted_genres:
blacklisted_genres.remove(allow_genre)
return


def allowed_genres(genre, object_type, trakt_object):
allowed_object = False
genres = genre.split(',')

for item in genres:
if item.lower() in trakt_object[object_type]['genres']:
allowed_object = True
break
return allowed_object


def sorted_list(original_list, list_type, sort_key, reverse=True):
prepared_list = copy(original_list)
for item in prepared_list:
if not item[list_type][sort_key]:
if sort_key == 'released' or sort_key == 'first_aired':
item[list_type][sort_key] = ""
else:
item[list_type][sort_key] = 0

return sorted(prepared_list, key=lambda k: k[list_type][sort_key], reverse=reverse)


# reference: https://stackoverflow.com/a/16712886
def substring_after(s, delim):
return s.partition(delim)[2]
54 changes: 54 additions & 0 deletions menu/pgtrakt/helpers/radarr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from misc.log import logger

log = logger.get_logger(__name__)


def movies_to_tmdb_dict(radarr_movies):
movies = {}
try:
for tmp in radarr_movies:
if 'tmdbId' not in tmp:
log.debug("Could not handle movie: %s", tmp['title'])
continue
movies[tmp['tmdbId']] = tmp
return movies
except Exception:
log.exception("Exception processing Radarr movies to TMDB dict: ")
return None


def remove_existing_movies(radarr_movies, trakt_movies, callback=None):
new_movies_list = []

if not radarr_movies or not trakt_movies:
log.error("Inappropriate parameters were supplied")
return None

try:
# turn radarr movies result into a dict with tmdb id as keys
processed_movies = movies_to_tmdb_dict(radarr_movies)
if not processed_movies:
return None

# loop list adding to movies that do not already exist
for tmp in trakt_movies:
if 'movie' not in tmp or 'ids' not in tmp['movie'] or 'tmdb' not in tmp['movie']['ids']:
log.debug("Skipping movie because it did not have required fields: %s", tmp)
if callback:
callback('movie', tmp)
continue
# check if movie exists in processed_movies
if tmp['movie']['ids']['tmdb'] in processed_movies:
log.debug("Removing existing movie: %s", tmp['movie']['title'])
if callback:
callback('movie', tmp)
continue

new_movies_list.append(tmp)

log.debug("Filtered %d Trakt movies to %d movies that weren't already in Radarr", len(trakt_movies),
len(new_movies_list))
return new_movies_list
except Exception:
log.exception("Exception removing existing movies from Trakt list: ")
return None
30 changes: 30 additions & 0 deletions menu/pgtrakt/helpers/rating.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from misc.log import logger
import json
import requests

log = logger.get_logger(__name__)
def get_rating(apikey,movie):
imdbID = movie['movie']['ids']['imdb']
if(imdbID):
log.debug("Requesting ratings from OMDB for %s (%d) | Genres: %s | Country: %s | imdbID: %s",movie['movie']['title'], movie['movie']['year'],
', '.join(movie['movie']['genres']), movie['movie']['country'].upper(),imdbID)
r = requests.get('http://www.omdbapi.com/?i=' + imdbID + '&apikey=' + apikey)
if(r.status_code == 200):
log.debug("Successfully requested ratings from OMDB for %s (%d) | Genres: %s | Country: %s | imdbID: %s",
movie['movie']['title'], movie['movie']['year'],
', '.join(movie['movie']['genres']), movie['movie']['country'].upper(), imdbID)
for source in json.loads(r.text)["Ratings"]:
if(source['Source'] == 'Rotten Tomatoes'):
log.debug("Rotten Tomatoes shows rating: %s for %s (%d) | Genres: %s | Country: %s | imdbID: %s ",source['Value'],movie['movie']['title'], movie['movie']['year'],
', '.join(movie['movie']['genres']), movie['movie']['country'].upper(),imdbID)
return int(source['Value'].split('%')[0])
else:
log.debug("Error encountered when requesting ratings from OMDB for %s (%d) | Genres: %s | Country: %s | imdbID: %s",
movie['movie']['title'], movie['movie']['year'],
', '.join(movie['movie']['genres']), movie['movie']['country'].upper(), imdbID)
else:
log.debug("Skipping %s (%d) | Genres: %s | Country: %s as it does not have an imdbID",
movie['movie']['title'], movie['movie']['year'],
', '.join(movie['movie']['genres']), movie['movie']['country'].upper())

return -1
85 changes: 85 additions & 0 deletions menu/pgtrakt/helpers/sonarr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
from misc.log import logger

log = logger.get_logger(__name__)


def series_tag_id_from_network(profile_tags, network_tags, network):
try:
tags = []
for tag_name, tag_networks in network_tags.items():
for tag_network in tag_networks:
if tag_network.lower() in network.lower() and tag_name.lower() in profile_tags:
log.debug("Using %s tag for network: %s", tag_name, network)
tags.append(profile_tags[tag_name.lower()])
if tags:
return tags
except Exception:
log.exception("Exception determining tag to use for network %s: ", network)
return None


def readable_tag_from_ids(profile_tag_ids, chosen_tag_ids):
try:
if not chosen_tag_ids:
return None

tags = []
for tag_name, tag_id in profile_tag_ids.items():
if tag_id in chosen_tag_ids:
tags.append(tag_name)
if tags:
return tags
except Exception:
log.exception("Exception building readable tag name list from ids %s: ", chosen_tag_ids)
return None


def series_to_tvdb_dict(sonarr_series):
series = {}
try:
for tmp in sonarr_series:
if 'tvdbId' not in tmp:
log.debug("Could not handle show: %s", tmp['title'])
continue
series[tmp['tvdbId']] = tmp
return series
except Exception:
log.exception("Exception processing Sonarr shows to TVDB dict: ")
return None


def remove_existing_series(sonarr_series, trakt_series, callback=None):
new_series_list = []

if not sonarr_series or not trakt_series:
log.error("Inappropriate parameters were supplied")
return None

try:
# turn sonarr series result into a dict with tvdb id as keys
processed_series = series_to_tvdb_dict(sonarr_series)
if not processed_series:
return None

# loop list adding to series that do not already exist
for tmp in trakt_series:
if 'show' not in tmp or 'ids' not in tmp['show'] or 'tvdb' not in tmp['show']['ids']:
log.debug("Skipping show because it did not have required fields: %s", tmp)
if callback:
callback('show', tmp)
continue
# check if show exists in processed_series
if tmp['show']['ids']['tvdb'] in processed_series:
log.debug("Removing existing show: %s", tmp['show']['title'])
if callback:
callback('show', tmp)
continue

new_series_list.append(tmp)

log.debug("Filtered %d Trakt shows to %d shows that weren't already in Sonarr", len(trakt_series),
len(new_series_list))
return new_series_list
except Exception:
log.exception("Exception removing existing shows from Trakt list: ")
return None
Loading

0 comments on commit 333ad1d

Please sign in to comment.