Plex-Meta-Manager/modules/convert.py

366 lines
16 KiB
Python
Raw Normal View History

2021-05-08 00:40:07 +00:00
import logging, re, requests
2021-04-22 23:51:03 +00:00
from lxml import html
from modules import util
from modules.util import Failed
2021-05-19 17:12:34 +00:00
from plexapi.exceptions import BadRequest
2021-04-22 23:51:03 +00:00
from retrying import retry
logger = logging.getLogger("Plex Meta Manager")
2021-05-08 04:05:10 +00:00
class Convert:
2021-04-22 23:51:03 +00:00
def __init__(self, config):
self.config = config
self.arms_url = "https://relations.yuna.moe/api/ids"
self.anidb_url = "https://raw.githubusercontent.com/Anime-Lists/anime-lists/master/anime-list-master.xml"
self.AniDBIDs = self._get_anidb()
@retry(stop_max_attempt_number=6, wait_fixed=10000)
def _get_anidb(self):
return html.fromstring(requests.get(self.anidb_url).content)
2021-05-08 04:05:10 +00:00
def _anidb(self, input_id, to_id, fail=False):
2021-04-22 23:51:03 +00:00
ids = self.AniDBIDs.xpath(f"//anime[contains(@anidbid, '{input_id}')]/@{to_id}")
if len(ids) > 0:
try:
if len(ids[0]) > 0:
2021-05-08 23:49:55 +00:00
return util.get_list(ids[0]) if to_id == "imdbid" else int(ids[0])
2021-04-22 23:51:03 +00:00
raise ValueError
except ValueError:
2021-05-08 04:05:10 +00:00
fail_text = f"Convert Error: No {util.pretty_ids[to_id]} ID found for AniDB ID: {input_id}"
2021-04-22 23:51:03 +00:00
else:
2021-05-08 04:05:10 +00:00
fail_text = f"Convert Error: AniDB ID: {input_id} not found"
if fail:
raise Failed(fail_text)
2021-05-08 23:49:55 +00:00
return [] if to_id == "imdbid" else None
2021-04-22 23:51:03 +00:00
@retry(stop_max_attempt_number=6, wait_fixed=10000)
2021-04-23 00:11:37 +00:00
def _request(self, ids):
2021-04-22 23:51:03 +00:00
return requests.post(self.arms_url, json=ids).json()
def _arms_ids(self, anilist_ids=None, anidb_ids=None, mal_ids=None):
all_ids = []
def collect_ids(ids, id_name):
if ids:
if isinstance(ids, list):
all_ids.extend([{id_name: a_id} for a_id in ids])
else:
all_ids.append({id_name: ids})
collect_ids(anilist_ids, "anilist")
collect_ids(anidb_ids, "anidb")
collect_ids(mal_ids, "myanimelist")
converted_ids = []
2021-05-10 02:56:25 +00:00
unconverted_ids = []
unconverted_id_sets = []
for anime_dict in all_ids:
if self.config.Cache:
2021-04-22 23:51:03 +00:00
for id_type, anime_id in anime_dict.items():
2021-05-10 02:56:25 +00:00
query_ids, expired = self.config.Cache.query_anime_map(anime_id, id_type)
if query_ids and not expired:
2021-04-22 23:51:03 +00:00
converted_ids.append(query_ids)
else:
unconverted_ids.append({id_type: anime_id})
2021-05-10 02:56:25 +00:00
if len(unconverted_ids) == 100:
unconverted_id_sets.append(unconverted_ids)
unconverted_ids = []
else:
unconverted_ids.append(anime_dict)
if len(unconverted_ids) == 100:
unconverted_id_sets.append(unconverted_ids)
unconverted_ids = []
for unconverted_id_set in unconverted_id_sets:
for anime_ids in self._request(unconverted_id_set):
if anime_ids:
if self.config.Cache:
self.config.Cache.update_anime_map(False, anime_ids)
converted_ids.append(anime_ids)
2021-04-22 23:51:03 +00:00
return converted_ids
2021-05-08 23:49:55 +00:00
def anidb_to_ids(self, anidb_list):
2021-05-08 04:05:10 +00:00
show_ids = []
movie_ids = []
for anidb_id in anidb_list:
2021-05-08 23:49:55 +00:00
imdb_ids = self.anidb_to_imdb(anidb_id)
tmdb_ids = []
if imdb_ids:
for imdb_id in imdb_ids:
tmdb_id = self.imdb_to_tmdb(imdb_id)
2021-05-08 04:05:10 +00:00
if tmdb_id:
2021-05-08 23:49:55 +00:00
tmdb_ids.append(tmdb_id)
tvdb_id = self.anidb_to_tvdb(anidb_id)
if tvdb_id:
show_ids.append(tvdb_id)
if tmdb_ids:
movie_ids.extend(tmdb_ids)
if not tvdb_id and not tmdb_ids:
logger.error(f"Convert Error: No TVDb ID or IMDb ID found for AniDB ID: {anidb_id}")
2021-05-08 04:05:10 +00:00
return movie_ids, show_ids
2021-05-08 23:49:55 +00:00
def anilist_to_ids(self, anilist_ids):
2021-05-08 04:05:10 +00:00
anidb_ids = []
for id_set in self._arms_ids(anilist_ids=anilist_ids):
if id_set["anidb"] is not None:
anidb_ids.append(id_set["anidb"])
else:
logger.error(f"Convert Error: AniDB ID not found for AniList ID: {id_set['anilist']}")
2021-05-08 23:49:55 +00:00
return self.anidb_to_ids(anidb_ids)
2021-05-08 04:05:10 +00:00
2021-05-08 23:49:55 +00:00
def myanimelist_to_ids(self, mal_ids):
2021-05-08 04:05:10 +00:00
anidb_ids = []
for id_set in self._arms_ids(mal_ids=mal_ids):
if id_set["anidb"] is not None:
anidb_ids.append(id_set["anidb"])
else:
logger.error(f"Convert Error: AniDB ID not found for MyAnimeList ID: {id_set['myanimelist']}")
2021-05-08 23:49:55 +00:00
return self.anidb_to_ids(anidb_ids)
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def anidb_to_tvdb(self, anidb_id, fail=False):
return self._anidb(anidb_id, "tvdbid", fail=fail)
def anidb_to_imdb(self, anidb_id, fail=False):
return self._anidb(anidb_id, "imdbid", fail=fail)
def tmdb_to_imdb(self, tmdb_id, is_movie=True, fail=False):
2021-05-09 05:38:41 +00:00
media_type = "movie" if is_movie else "show"
expired = False
if self.config.Cache and is_movie:
cache_id, expired = self.config.Cache.query_imdb_to_tmdb_map(media_type, tmdb_id, imdb=False)
if cache_id and not expired:
return cache_id
imdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-09 05:38:41 +00:00
imdb_id = self.config.TMDb.convert_from(tmdb_id, "imdb_id", is_movie)
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-09 05:38:41 +00:00
imdb_id = self.config.Trakt.convert(tmdb_id, "tmdb", "imdb", "movie" if is_movie else "show")
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-09 05:38:41 +00:00
if fail and imdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No IMDb ID Found for TMDb ID: {tmdb_id}")
2021-05-09 05:38:41 +00:00
if self.config.Cache and imdb_id:
self.config.Cache.update_imdb_to_tmdb_map(media_type, expired, imdb_id, tmdb_id)
return imdb_id
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def imdb_to_tmdb(self, imdb_id, is_movie=True, fail=False):
2021-05-09 05:38:41 +00:00
media_type = "movie" if is_movie else "show"
2021-05-08 23:49:55 +00:00
expired = False
if self.config.Cache and is_movie:
2021-05-09 05:38:41 +00:00
cache_id, expired = self.config.Cache.query_imdb_to_tmdb_map(media_type, imdb_id, imdb=True)
2021-05-08 23:49:55 +00:00
if cache_id and not expired:
return cache_id
tmdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-08 23:49:55 +00:00
tmdb_id = self.config.TMDb.convert_to(imdb_id, "imdb_id", is_movie)
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-09 05:38:41 +00:00
tmdb_id = self.config.Trakt.convert(imdb_id, "imdb", "tmdb", media_type)
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-08 23:49:55 +00:00
if fail and tmdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No TMDb ID Found for IMDb ID: {imdb_id}")
2021-05-09 05:38:41 +00:00
if self.config.Cache and tmdb_id:
self.config.Cache.update_imdb_to_tmdb_map(media_type, expired, imdb_id, tmdb_id)
2021-05-08 23:49:55 +00:00
return tmdb_id
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def tmdb_to_tvdb(self, tmdb_id, fail=False):
2021-05-09 05:38:41 +00:00
expired = False
if self.config.Cache:
cache_id, expired = self.config.Cache.query_tmdb_to_tvdb_map(tmdb_id, tmdb=True)
if cache_id and not expired:
return cache_id
tvdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-09 05:38:41 +00:00
tvdb_id = self.config.TMDb.convert_from(tmdb_id, "tvdb_id", False)
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-09 05:38:41 +00:00
tvdb_id = self.config.Trakt.convert(tmdb_id, "tmdb", "tvdb", "show")
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-09 05:38:41 +00:00
if fail and tvdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No TVDb ID Found for TMDb ID: {tmdb_id}")
2021-05-09 05:38:41 +00:00
if self.config.Cache and tvdb_id:
self.config.Cache.update_tmdb_to_tvdb_map(expired, tmdb_id, tvdb_id)
return tvdb_id
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def tvdb_to_tmdb(self, tvdb_id, fail=False):
2021-05-09 05:38:41 +00:00
expired = False
if self.config.Cache:
cache_id, expired = self.config.Cache.query_tmdb_to_tvdb_map(tvdb_id, tmdb=False)
if cache_id and not expired:
return cache_id
tmdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-09 05:38:41 +00:00
tmdb_id = self.config.TMDb.convert_to(tvdb_id, "tvdb_id", False)
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-09 05:38:41 +00:00
tmdb_id = self.config.Trakt.convert(tvdb_id, "tvdb", "tmdb", "show")
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-09 05:38:41 +00:00
if fail and tmdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No TMDb ID Found for TVDb ID: {tvdb_id}")
2021-05-09 05:38:41 +00:00
if self.config.Cache and tmdb_id:
self.config.Cache.update_tmdb_to_tvdb_map(expired, tmdb_id, tvdb_id)
return tmdb_id
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def tvdb_to_imdb(self, tvdb_id, fail=False):
2021-05-09 05:38:41 +00:00
expired = False
if self.config.Cache:
cache_id, expired = self.config.Cache.query_imdb_to_tvdb_map(tvdb_id, imdb=False)
if cache_id and not expired:
return cache_id
imdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-09 05:38:41 +00:00
imdb_id = self.tmdb_to_imdb(self.tvdb_to_tmdb(tvdb_id), False)
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-09 05:38:41 +00:00
imdb_id = self.config.Trakt.convert(tvdb_id, "tvdb", "imdb", "show")
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-09 05:38:41 +00:00
if fail and imdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No IMDb ID Found for TVDb ID: {tvdb_id}")
2021-05-09 05:38:41 +00:00
if self.config.Cache and imdb_id:
self.config.Cache.update_imdb_to_tvdb_map(expired, imdb_id, tvdb_id)
return imdb_id
2021-05-08 00:40:07 +00:00
2021-05-08 04:05:10 +00:00
def imdb_to_tvdb(self, imdb_id, fail=False):
2021-05-08 23:49:55 +00:00
expired = False
if self.config.Cache:
2021-05-09 05:38:41 +00:00
cache_id, expired = self.config.Cache.query_imdb_to_tvdb_map(imdb_id, imdb=True)
2021-05-08 23:49:55 +00:00
if cache_id and not expired:
return cache_id
tvdb_id = None
2021-05-08 00:40:07 +00:00
try:
2021-05-08 23:49:55 +00:00
tvdb_id = self.tmdb_to_tvdb(self.imdb_to_tmdb(imdb_id, False))
2021-05-08 00:40:07 +00:00
except Failed:
if self.config.Trakt:
try:
2021-05-08 23:49:55 +00:00
tvdb_id = self.config.Trakt.convert(imdb_id, "imdb", "tvdb", "show")
2021-05-08 00:40:07 +00:00
except Failed:
pass
2021-05-08 23:49:55 +00:00
if fail and tvdb_id is None:
2021-05-08 04:05:10 +00:00
raise Failed(f"Convert Error: No TVDb ID Found for IMDb ID: {imdb_id}")
2021-05-08 23:49:55 +00:00
if self.config.Cache and tvdb_id:
2021-05-09 05:38:41 +00:00
self.config.Cache.update_imdb_to_tvdb_map(expired, imdb_id, tvdb_id)
2021-05-08 23:49:55 +00:00
return tvdb_id
2021-05-08 00:40:07 +00:00
def get_id(self, item, library, length):
expired = None
if self.config.Cache:
2021-05-08 23:49:55 +00:00
cache_id, media_type, expired = self.config.Cache.query_guid_map(item.guid)
if cache_id and not expired:
media_id_type = "movie" if "movie" in media_type else "show"
return media_id_type, util.get_list(cache_id, int_list=True)
try:
tmdb_id = None
imdb_id = None
tvdb_id = None
anidb_id = None
2021-05-08 00:40:07 +00:00
guid = requests.utils.urlparse(item.guid)
item_type = guid.scheme.split(".")[-1]
check_id = guid.netloc
if item_type == "plex":
tmdb_id = []
imdb_id = []
tvdb_id = []
2021-05-08 23:49:55 +00:00
try:
for guid_tag in library.get_guids(item):
url_parsed = requests.utils.urlparse(guid_tag.id)
if url_parsed.scheme == "tvdb": tvdb_id.append(int(url_parsed.netloc))
elif url_parsed.scheme == "imdb": imdb_id.append(url_parsed.netloc)
elif url_parsed.scheme == "tmdb": tmdb_id.append(int(url_parsed.netloc))
except requests.exceptions.ConnectionError:
util.print_stacktrace()
raise Failed("No External GUIDs found")
2021-05-18 21:56:57 +00:00
if not tvdb_id and not imdb_id and not tmdb_id:
raise Failed("Refresh Metadata")
2021-05-08 00:40:07 +00:00
elif item_type == "imdb": imdb_id = check_id
elif item_type == "thetvdb": tvdb_id = int(check_id)
elif item_type == "themoviedb": tmdb_id = int(check_id)
elif item_type == "hama":
if check_id.startswith("tvdb"): tvdb_id = int(re.search("-(.*)", check_id).group(1))
elif check_id.startswith("anidb"): anidb_id = re.search("-(.*)", check_id).group(1)
2021-05-08 23:49:55 +00:00
else: raise Failed(f"Hama Agent ID: {check_id} not supported")
elif item_type == "myanimelist":
anime_ids = self._arms_ids(mal_ids=check_id)
if anime_ids[0] and anime_ids[0]["anidb"]: anidb_id = anime_ids[0]["anidb"]
else: raise Failed(f"Unable to convert MyAnimeList ID: {check_id} to AniDB ID")
elif item_type == "local": raise Failed("No match in Plex")
else: raise Failed(f"Agent {item_type} not supported")
2021-05-08 00:40:07 +00:00
2021-05-08 23:49:55 +00:00
if anidb_id:
2021-05-10 03:16:42 +00:00
tvdb_id = self.anidb_to_tvdb(anidb_id)
if not tvdb_id:
imdb_id = self.anidb_to_imdb(anidb_id)
2021-05-08 23:49:55 +00:00
if not imdb_id and not tvdb_id:
raise Failed(f"Unable to convert AniDB ID: {anidb_id} to TVDb ID or IMDb ID")
2021-05-08 00:40:07 +00:00
2021-05-08 23:49:55 +00:00
if not tmdb_id and imdb_id:
if isinstance(imdb_id, list):
tmdb_id = []
for imdb in imdb_id:
try:
2021-05-09 14:52:42 +00:00
tmdb_id.append(self.imdb_to_tmdb(imdb, fail=True))
2021-05-08 23:49:55 +00:00
except Failed:
continue
else:
tmdb_id = self.imdb_to_tmdb(imdb_id)
if not tmdb_id:
raise Failed(f"Unable to convert IMDb ID: {util.compile_list(imdb_id)} to TMDb ID")
2021-05-08 23:49:55 +00:00
if not anidb_id and not tvdb_id and tmdb_id and library.is_show:
2021-05-12 02:34:14 +00:00
if isinstance(tmdb_id, list):
tvdb_id = []
for tmdb in tmdb_id:
2021-05-12 14:38:11 +00:00
try:
tvdb_id.append(self.tmdb_to_tvdb(tmdb, fail=True))
except Failed:
continue
2021-05-12 02:34:14 +00:00
else:
tvdb_id = self.tmdb_to_tvdb(tmdb_id)
2021-05-08 23:49:55 +00:00
if not tvdb_id:
raise Failed(f"Unable to convert TMDb ID: {util.compile_list(tmdb_id)} to TVDb ID")
2021-05-08 00:40:07 +00:00
2021-05-12 14:38:11 +00:00
if tvdb_id:
if isinstance(tvdb_id, list):
new_tvdb_id = []
for tvdb in tvdb_id:
try:
new_tvdb_id.append(int(tvdb))
except ValueError:
continue
tvdb_id = new_tvdb_id
else:
try:
tvdb_id = int(tvdb_id)
except ValueError:
tvdb_id = None
2021-05-08 23:49:55 +00:00
def update_cache(cache_ids, id_type, guid_type):
if self.config.Cache:
cache_ids = util.compile_list(cache_ids)
2021-05-14 15:42:45 +00:00
util.print_end(length, f" Cache | {'^' if expired else '+'} | {item.guid:<46} | {id_type} ID: {cache_ids:<6} | {item.title}")
2021-05-09 05:38:41 +00:00
self.config.Cache.update_guid_map(guid_type, item.guid, cache_ids, expired)
2021-05-08 00:40:07 +00:00
2021-05-08 23:49:55 +00:00
if tmdb_id and library.is_movie:
update_cache(tmdb_id, "TMDb", "movie")
return "movie", tmdb_id
elif tvdb_id and library.is_show:
update_cache(tvdb_id, "TVDb", "show")
return "show", tvdb_id
elif anidb_id and tmdb_id and library.is_show:
update_cache(tmdb_id, "TMDb", "show_movie")
return "movie", tmdb_id
else:
raise Failed(f"No ID to convert")
except Failed as e:
util.print_end(length, f"Mapping Error | {item.guid:<46} | {e} for {item.title}")
2021-05-19 17:12:34 +00:00
except BadRequest:
util.print_stacktrace()
util.print_end(length, f"Mapping Error: | {item.guid} for {item.title} not found")
return None, None