Plex-Meta-Manager/modules/trakt.py

182 lines
9.1 KiB
Python
Raw Normal View History

2021-01-21 21:42:31 +00:00
import logging, requests, webbrowser
2021-01-20 21:37:59 +00:00
from modules import util
from modules.util import Failed, TimeoutExpired
from ruamel import yaml
logger = logging.getLogger("Plex Meta Manager")
2021-07-15 17:42:28 +00:00
redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
redirect_uri_encoded = redirect_uri.replace(":", "%3A")
base_url = "https://api.trakt.tv"
2021-03-30 05:50:53 +00:00
builders = [
2021-07-23 19:44:21 +00:00
"trakt_collected", "trakt_collection", "trakt_list", "trakt_list_details", "trakt_popular",
"trakt_recommended", "trakt_trending", "trakt_watched", "trakt_watchlist"
2021-03-30 05:50:53 +00:00
]
2021-07-29 21:36:26 +00:00
sorts = [
"rank", "added", "title", "released", "runtime", "popularity",
"percentage", "votes", "random", "my_rating", "watched", "collected"
]
2021-03-30 05:50:53 +00:00
2021-06-14 15:24:11 +00:00
class Trakt:
2021-07-26 19:03:17 +00:00
def __init__(self, config, params):
2021-07-14 14:47:20 +00:00
self.config = config
2021-01-20 21:37:59 +00:00
self.client_id = params["client_id"]
self.client_secret = params["client_secret"]
self.config_path = params["config_path"]
2021-07-26 19:03:17 +00:00
self.authorization = params["authorization"]
2021-05-07 19:53:54 +00:00
if not self._save(self.authorization):
if not self._refresh():
self._authorization()
2021-01-20 21:37:59 +00:00
2021-05-07 19:53:54 +00:00
def _authorization(self):
2021-07-15 17:42:28 +00:00
url = f"https://trakt.tv/oauth/authorize?response_type=code&client_id={self.client_id}&redirect_uri={redirect_uri_encoded}"
2021-02-24 06:44:06 +00:00
logger.info(f"Navigate to: {url}")
2021-01-20 21:37:59 +00:00
logger.info("If you get an OAuth error your client_id or client_secret is invalid")
webbrowser.open(url, new=2)
try: pin = util.logger_input("Trakt pin (case insensitive)", timeout=300).strip()
except TimeoutExpired: raise Failed("Input Timeout: Trakt pin required.")
if not pin: raise Failed("Trakt Error: No input Trakt pin required.")
2021-07-15 17:42:28 +00:00
json = {
"code": pin,
"client_id": self.client_id,
"client_secret": self.client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code"
}
response = self.config.post(f"{base_url}/oauth/token", json=json, headers={"Content-Type": "application/json"})
if response.status_code != 200:
2021-01-20 21:37:59 +00:00
raise Failed("Trakt Error: Invalid trakt pin. If you're sure you typed it in correctly your client_id or client_secret may be invalid")
2021-07-15 17:42:28 +00:00
elif not self._save(response.json()):
2021-01-20 21:37:59 +00:00
raise Failed("Trakt Error: New Authorization Failed")
2021-07-15 17:42:28 +00:00
def _check(self, authorization=None):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.authorization['access_token'] if authorization is None else authorization['access_token']}",
"trakt-api-version": "2",
"trakt-api-key": self.client_id
}
response = self.config.get(f"{base_url}/users/settings", headers=headers)
return response.status_code == 200
2021-01-20 21:37:59 +00:00
2021-05-07 19:53:54 +00:00
def _refresh(self):
2021-01-20 21:37:59 +00:00
if self.authorization and "refresh_token" in self.authorization and self.authorization["refresh_token"]:
logger.info("Refreshing Access Token...")
2021-07-15 17:42:28 +00:00
json = {
"refresh_token": self.authorization["refresh_token"],
"client_id": self.client_id,
"client_secret": self.client_secret,
"redirect_uri": redirect_uri,
"grant_type": "refresh_token"
}
response = self.config.post(f"{base_url}/oauth/token", json=json, headers={"Content-Type": "application/json"})
if response.status_code != 200:
return False
return self._save(response.json())
2021-01-20 21:37:59 +00:00
return False
2021-05-07 19:53:54 +00:00
def _save(self, authorization):
if authorization and self._check(authorization):
2021-01-20 21:37:59 +00:00
if self.authorization != authorization:
yaml.YAML().allow_duplicate_keys = True
config, ind, bsi = yaml.util.load_yaml_guess_indent(open(self.config_path))
config["trakt"]["authorization"] = {
"access_token": authorization["access_token"],
"token_type": authorization["token_type"],
"expires_in": authorization["expires_in"],
"refresh_token": authorization["refresh_token"],
"scope": authorization["scope"],
"created_at": authorization["created_at"]
}
2021-02-24 06:44:06 +00:00
logger.info(f"Saving authorization information to {self.config_path}")
2021-01-20 21:37:59 +00:00
yaml.round_trip_dump(config, open(self.config_path, "w"), indent=ind, block_seq_indent=bsi)
2021-07-15 17:42:28 +00:00
self.authorization = authorization
2021-01-20 21:37:59 +00:00
return True
return False
2021-07-15 17:42:28 +00:00
def _request(self, url):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.authorization['access_token']}",
"trakt-api-version": "2",
"trakt-api-key": self.client_id
}
response = self.config.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Failed(f"({response.status_code}) {response.reason}")
2021-05-08 00:40:07 +00:00
def convert(self, external_id, from_source, to_source, media_type):
2021-07-15 17:42:28 +00:00
path = f"/search/{from_source}/{external_id}"
if from_source in ["tmdb", "tvdb"]:
path = f"{path}?type={media_type}"
lookup = self._request(f"{base_url}{path}")
if lookup and media_type in lookup[0] and to_source in lookup[0][media_type]["ids"]:
return lookup[0][media_type]["ids"][to_source]
2021-05-08 04:05:10 +00:00
raise Failed(f"Trakt Error: No {to_source.upper().replace('B', 'b')} ID found for {from_source.upper().replace('B', 'b')} ID: {external_id}")
2021-01-20 21:37:59 +00:00
2021-07-15 17:42:28 +00:00
def list_description(self, data):
try:
return self._request(f"{base_url}{requests.utils.urlparse(data).path}")["description"]
except Failed:
raise Failed(f"Trakt Error: List {data} not found")
2021-03-30 05:49:10 +00:00
2021-05-07 19:53:54 +00:00
def _user_list(self, list_type, data, is_movie):
2021-07-15 17:42:28 +00:00
path = f"{requests.utils.urlparse(data).path}/items" if list_type == "list" else f"/users/{data}/{list_type}"
try:
items = self._request(f"{base_url}{path}/{'movies' if is_movie else 'shows'}")
except Failed:
raise Failed(f"Trakt Error: {'List' if list_type == 'list' else 'User'} {data} not found")
if len(items) == 0:
if list_type == "list":
raise Failed(f"Trakt Error: List {data} is empty")
else:
raise Failed(f"Trakt Error: {data}'s {list_type.capitalize()} is empty")
2021-03-27 07:30:07 +00:00
if is_movie: return [item["movie"]["ids"]["tmdb"] for item in items], []
else: return [], [item["show"]["ids"]["tvdb"] for item in items]
2021-05-07 19:53:54 +00:00
def _pagenation(self, pagenation, amount, is_movie):
2021-07-15 17:42:28 +00:00
items = self._request(f"{base_url}/{'movies' if is_movie else 'shows'}/{pagenation}?limit={amount}")
2021-03-18 13:41:30 +00:00
if pagenation == "popular" and is_movie: return [item["ids"]["tmdb"] for item in items], []
elif pagenation == "popular": return [], [item["ids"]["tvdb"] for item in items]
elif is_movie: return [item["movie"]["ids"]["tmdb"] for item in items], []
else: return [], [item["show"]["ids"]["tvdb"] for item in items]
2021-07-21 17:40:05 +00:00
def validate_trakt(self, trakt_lists, is_movie, trakt_type="list"):
2021-07-29 21:36:26 +00:00
values = util.get_list(trakt_lists, split=False)
2021-01-20 21:37:59 +00:00
trakt_values = []
for value in values:
try:
2021-07-15 17:42:28 +00:00
self._user_list(trakt_type, value, is_movie)
2021-01-20 21:37:59 +00:00
trakt_values.append(value)
except Failed as e:
logger.error(e)
if len(trakt_values) == 0:
2021-07-15 17:42:28 +00:00
if trakt_type == "watchlist":
2021-03-27 07:30:07 +00:00
raise Failed(f"Trakt Error: No valid Trakt Watchlists in {values}")
2021-07-15 17:42:28 +00:00
elif trakt_type == "collection":
2021-03-27 07:30:07 +00:00
raise Failed(f"Trakt Error: No valid Trakt Collections in {values}")
else:
raise Failed(f"Trakt Error: No valid Trakt Lists in {values}")
2021-01-20 21:37:59 +00:00
return trakt_values
2021-05-09 05:37:45 +00:00
def get_items(self, method, data, is_movie):
2021-08-01 04:35:42 +00:00
pretty = method.replace("_", " ").title()
2021-01-20 21:37:59 +00:00
media_type = "Movie" if is_movie else "Show"
2021-03-10 16:58:39 +00:00
if method in ["trakt_trending", "trakt_popular", "trakt_recommended", "trakt_watched", "trakt_collected"]:
2021-05-07 19:53:54 +00:00
movie_ids, show_ids = self._pagenation(method[6:], data, is_movie)
2021-05-09 05:37:45 +00:00
logger.info(f"Processing {pretty}: {data} {media_type}{'' if data == 1 else 's'}")
2021-07-15 17:42:28 +00:00
elif method in ["trakt_collection", "trakt_watchlist"]:
movie_ids, show_ids = self._user_list(method[6:], data, is_movie)
2021-05-09 05:37:45 +00:00
logger.info(f"Processing {pretty} {media_type}s for {data}")
2021-07-15 17:42:28 +00:00
elif method == "trakt_list":
movie_ids, show_ids = self._user_list(method[6:], data, is_movie)
2021-05-09 05:37:45 +00:00
logger.info(f"Processing {pretty}: {data}")
2021-07-15 17:42:28 +00:00
else:
raise Failed(f"Trakt Error: Method {method} not supported")
2021-05-24 03:38:46 +00:00
logger.debug("")
2021-07-03 01:47:09 +00:00
logger.debug(f"{len(movie_ids)} TMDb IDs Found: {movie_ids}")
logger.debug(f"{len(show_ids)} TVDb IDs Found: {show_ids}")
2021-01-20 21:37:59 +00:00
return movie_ids, show_ids