Plex-Meta-Manager/modules/tautulli.py

73 lines
3.2 KiB
Python
Raw Permalink Normal View History

2021-01-20 21:37:59 +00:00
from modules import util
from modules.util import Failed
from plexapi.exceptions import BadRequest
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:
2024-05-28 20:22:51 +00:00
def __init__(self, requests, library, params):
self.requests = requests
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"]
self.api = f"{self.url}/api/v2"
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:
response = self._request("get_tautulli_info")
2021-02-24 06:42:58 +00:00
except Exception:
logger.stacktrace()
2023-04-28 15:18:45 +00:00
raise Failed("Tautulli Error: Invalid URL")
2021-01-20 21:37:59 +00:00
if response["response"]["result"] != "success":
2021-02-24 06:44:06 +00:00
raise Failed(f"Tautulli Error: {response['response']['message']}")
self.has_section = True if int(response["response"]["data"]["tautulli_version"].split(".")[1]) > 11 else False
self.section_id = self.library.Plex.key
2021-01-20 21:37:59 +00:00
def get_rating_keys(self, data, all_items):
logger.info(f"Processing Tautulli Most {data['list_type'].capitalize()}: {data['list_size']} {'Movies' if self.library.is_movie else 'Shows'}")
params = {"time_range": data["list_days"], "stats_count": int(data["list_size"]) + int(data["list_buffer"])}
if self.has_section and not all_items:
params["section_id"] = self.section_id
response = self._request("get_home_stats", params=params)
stat_id = f"{'popular' if data['list_type'] == 'popular' else 'top'}_{'movies' if self.library.is_movie else 'tv'}"
stat_type = "users_watched" if data['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")
rating_keys = []
for item in items:
if (all_items or item["section_id"] == self.section_id) and len(rating_keys) < int(data['list_size']):
if int(item[stat_type]) < data['list_minimum']:
continue
2021-05-11 01:22:18 +00:00
try:
2023-02-27 19:54:52 +00:00
plex_item = self.library.fetch_item(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"))
2023-02-27 19:54:52 +00:00
except Failed as e:
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:
2023-02-27 19:54:52 +00:00
logger.error(e)
2021-01-20 21:37:59 +00:00
return rating_keys
def _request(self, cmd, params=None):
logger.trace(f"Tautulli CMD: {cmd}")
if params:
logger.trace(f"Tautulli Params: {params}")
final_params = {"apikey": self.apikey, "cmd": cmd}
if params:
for k, v in params.items():
final_params[k] = v
2024-05-28 20:22:51 +00:00
return self.requests.get_json(self.api, params=final_params)