Plex-Meta-Manager/modules/tautulli.py

66 lines
2.9 KiB
Python
Raw Normal View History

2021-01-20 21:37:59 +00:00
from modules import util
from modules.util import Failed
2021-05-11 01:22:18 +00:00
from plexapi.exceptions import BadRequest, NotFound
from plexapi.video import Movie, Show
2021-01-20 21:37:59 +00:00
logger = util.logger
2021-01-20 21:37:59 +00:00
2021-03-30 05:50:53 +00:00
builders = ["tautulli_popular", "tautulli_watched"]
2021-06-14 15:24:11 +00:00
class Tautulli:
2021-11-29 15:24:36 +00:00
def __init__(self, config, library, params):
2021-07-14 14:47:20 +00:00
self.config = config
2021-11-29 15:24:36 +00:00
self.library = library
2021-05-28 16:02:33 +00:00
self.url = params["url"]
self.apikey = params["apikey"]
logger.secret(self.url)
2022-02-13 22:47:08 +00:00
logger.secret(self.apikey)
2021-01-20 21:37:59 +00:00
try:
2021-05-28 16:02:33 +00:00
response = self._request(f"{self.url}/api/v2?apikey={self.apikey}&cmd=get_library_names")
2021-02-24 06:42:58 +00:00
except Exception:
logger.stacktrace()
2021-01-20 21:37:59 +00:00
raise Failed("Tautulli Error: Invalid url")
if response["response"]["result"] != "success":
2021-02-24 06:44:06 +00:00
raise Failed(f"Tautulli Error: {response['response']['message']}")
2021-01-20 21:37:59 +00:00
def get_rating_keys(self, params, all_items):
2021-05-12 14:25:48 +00:00
query_size = int(params["list_size"]) + int(params["list_buffer"])
logger.info(f"Processing Tautulli Most {params['list_type'].capitalize()}: {params['list_size']} {'Movies' if self.library.is_movie else 'Shows'}")
2021-05-12 14:25:48 +00:00
response = self._request(f"{self.url}/api/v2?apikey={self.apikey}&cmd=get_home_stats&time_range={params['list_days']}&stats_count={query_size}")
stat_id = f"{'popular' if params['list_type'] == 'popular' else 'top'}_{'movies' if self.library.is_movie else 'tv'}"
2021-11-30 16:10:47 +00:00
stat_type = "users_watched" if params['list_type'] == 'popular' else "total_plays"
2021-01-20 21:37:59 +00:00
items = None
for entry in response["response"]["data"]:
if entry["stat_id"] == stat_id:
items = entry["rows"]
break
if items is None:
raise Failed("Tautulli Error: No Items found in the response")
section_id = self.library.Plex.key
2021-01-20 21:37:59 +00:00
rating_keys = []
for item in items:
2022-01-04 16:46:56 +00:00
if (all_items or item["section_id"] == section_id) and len(rating_keys) < int(params['list_size']):
2021-11-29 19:04:43 +00:00
if int(item[stat_type]) < params['list_minimum']:
continue
2021-05-11 01:22:18 +00:00
try:
plex_item = self.library.fetchItem(int(item["rating_key"]))
2021-09-30 13:48:28 +00:00
if not isinstance(plex_item, (Movie, Show)):
2021-09-21 18:42:32 +00:00
raise BadRequest
2021-12-14 05:51:36 +00:00
rating_keys.append((item["rating_key"], "ratingKey"))
2021-05-11 01:22:18 +00:00
except (BadRequest, NotFound):
new_item = self.library.exact_search(item["title"], year=item["year"])
2021-05-11 01:22:18 +00:00
if new_item:
2021-12-14 05:51:36 +00:00
rating_keys.append((new_item[0].ratingKey, "ratingKey"))
2021-05-11 01:22:18 +00:00
else:
2022-04-16 20:53:53 +00:00
logger.error(f"Plex Error: Item not found {item}")
2021-08-07 06:01:21 +00:00
logger.debug("")
logger.debug(f"{len(rating_keys)} Keys Found: {rating_keys}")
2021-01-20 21:37:59 +00:00
return rating_keys
2021-05-07 19:53:54 +00:00
def _request(self, url):
if self.config.trace_mode:
logger.debug(f"Tautulli URL: {url}")
2021-07-14 14:47:20 +00:00
return self.config.get_json(url)