Skip to content

Commit

Permalink
check kometa, anidb and anilist
Browse files Browse the repository at this point in the history
  • Loading branch information
meisnate12 committed Jan 22, 2025
1 parent d0bfc14 commit 5f9b517
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 42 deletions.
44 changes: 22 additions & 22 deletions kometa.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
from modules.logs import MyLogger

if sys.version_info[0] != 3 or sys.version_info[1] < 9:
print("[E001] Python Error: Python version %s.%s.%s has been detected and is not supported. Kometa requires a minimum of Python 3.9.0. Update python to a supported version")
sys.exit(0)
msg = "[E001] Python Error: Python version %s.%s.%s has been detected and is not supported. Kometa requires a minimum of Python 3.9.0. Update python to a supported version"
print(msg)
sys.exit(msg)

try:
import arrapi, lxml, pathvalidate, PIL, plexapi, psutil, dateutil, requests, ruamel.yaml, schedule, setuptools, tmdbapis
Expand All @@ -16,8 +17,9 @@
from plexapi.exceptions import NotFound
from plexapi.video import Show, Season
except (ModuleNotFoundError, ImportError) as ie:
print(f"[E002] Requirements Error: Requirements are not installed. Please follow the documentation for instructions on installing requirements. ({ie})")
sys.exit(0)
msg = f"[E002] Requirements Error: Requirements are not installed. Please follow the documentation for instructions on installing requirements. ({ie})"
print(msg)
sys.exit(msg)

system_versions = {
"arrapi": arrapi.__version__,
Expand Down Expand Up @@ -193,8 +195,9 @@ def get_env(env_str, default, arg_bool=False, arg_int=False):
if run_args["config"] and os.path.exists(run_args["config"]):
default_dir = os.path.join(os.path.dirname(os.path.abspath(run_args["config"])))
elif run_args["config"] and not os.path.exists(run_args["config"]):
print(f"[C001] Config Error: Configuration file (config.yml) not found at {os.path.abspath(run_args['config'])}. Please check the path is correct and try again")
sys.exit(0)
msg = f"[C001] Config Error: Configuration file (config.yml) not found at {os.path.abspath(run_args['config'])}. Please check the path is correct and try again"
print(msg)
sys.exit(msg)
elif not os.path.exists(os.path.join(default_dir, "config.yml")):
git_branch = git_branch or "master"
github_url = f"https://raw.githubusercontent.com/Kometa-Team/Kometa/{git_branch}/config/config.yml.template"
Expand All @@ -204,13 +207,15 @@ def get_env(env_str, default, arg_bool=False, arg_int=False):
if response.status_code == 200:
with open(config_path, 'w') as config_file:
config_file.write(response.text)
print(f"Configuration File ('config.yml') has been downloaded from GitHub (Branch: '{git_branch}') and saved as '{config_path}'. Please update this file with your API keys and other required settings")
sys.exit(1)
msg = f"Configuration File ('config.yml') has been downloaded from GitHub (Branch: '{git_branch}') and saved as '{config_path}'. Please update this file with your API keys and other required settings"
print(msg)
sys.exit(msg)
else:
raise requests.RequestException
except requests.RequestException as e:
print(f"[C002] Config Error: Unable to download the configuration file from GitHub (URL: {github_url}'). Please save it as '{config_path}' and complete the relevant sections before running Kometa again")
sys.exit(1)
msg = f"[C002] Config Error: Unable to download the configuration file from GitHub (URL: {github_url}'). Please save it as '{config_path}' and complete the relevant sections before running Kometa again"
print(msg)
sys.exit(msg)


logger = MyLogger("Kometa", default_dir, run_args["width"], run_args["divider"][0], run_args["ignore-ghost"],
Expand Down Expand Up @@ -365,13 +370,8 @@ def start(attrs):
try:
config = ConfigFile(my_requests, default_dir, attrs, secret_args)
except Exception as e:
if "Invalid API key" in str(e):
logger.stacktrace()
logger.critical("[S001] Connector Error: TMDb API key is invalid. Please check the API key is correct or check TMDb guidance for obtaining a new key")
else:
logger.stacktrace()
logger.critical(e)

logger.stacktrace()
logger.critical(e)
else:
try:
stats = run_config(config, stats)
Expand Down Expand Up @@ -576,7 +576,7 @@ def print_status(status):
logger.info(f"{name:<{longest}} | {data['added']:>5} | {data['unchanged']:>5} | {data['removed']:>5} | {data['run_time']:>8} | {data['status']}")
if data["errors"]:
for error in data["errors"]:
logger.info(error.upper() if isinstance(error, str) else str(error).upper())
logger.info(str(error).upper())
logger.info("")

logger.info("")
Expand Down Expand Up @@ -1186,8 +1186,9 @@ def run_playlists(config):
raise Failed(f"[E303] Argument Error: 'time' argument does not have a value. Please enter a value in the HH:MM format between 00:00-23:59")
for time_to_run in valid_times:
schedule.every().day.at(time_to_run).do(process, {"time": time_to_run})
logger.info("Kometa is currently waiting until the next scheduled run. The default run time is 05:00 unless otherwise specified using the `--times` Run Command or `KOMETA_TIMES` Environment Variable.")
logger.info("If you would rather run Kometa immediately, use the `--run` Run Command or `KOMETA_RUN` Environment Variable.")
logger.info("Kometa is currently waiting until the next scheduled run.")
logger.info("To change the run times use the `--times` Run Command or `KOMETA_TIMES` Environment Variable.")
logger.info("To Run Kometa immediately use the `--run` Run Command or `KOMETA_RUN` Environment Variable.")
logger.info("")
while True:
schedule.run_pending()
Expand All @@ -1207,8 +1208,7 @@ def run_playlists(config):
minutes = int((seconds % 3600) // 60)
time_str = f"{hours} Hour{'s' if hours > 1 else ''} and " if hours > 0 else ""
time_str += f"{minutes} Minute{'s' if minutes > 1 else ''}"

logger.ghostnopipe(f"Current Time: {current_time} | Next Scheduled Run: {og_time_str} ({time_str} from now) | Scheduled Runs: {', '.join(valid_times)}")
logger.ghost(f"Current Time: {current_time} | Next Scheduled Run: {og_time_str} ({time_str} from now) | Scheduled Runs: {', '.join(valid_times)}", prefix="")
else:
logger.error(f"Argument Error: {valid_times}")
time.sleep(60)
Expand Down
1 change: 1 addition & 0 deletions modules/anidb.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def authorize(self, client, version, expiration):
if self.cache:
self.cache.update_testing("anidb_login", self.client, self.version, "False")
raise Failed("[S201] Connector Error: AniDB Client/Version could not be verified. Please check these are correct. AniDB Library Operations will not function until this is resolved")

@property
def is_authorized(self):
return self.client is not None
Expand Down
11 changes: 5 additions & 6 deletions modules/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from arrapi import ArrException
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from modules import anidb, anilist, icheckmovies, imdb, letterboxd, mal, mojo, plex, radarr, reciperr, sonarr, tautulli, tmdb, trakt, tvdb, mdblist, util
from modules import anidb, anilist, errors, icheckmovies, imdb, letterboxd, mal, mojo, plex, radarr, reciperr, sonarr, tautulli, tmdb, trakt, tvdb, mdblist, util
from modules.util import Failed, FilterFailed, NonExisting, NotScheduled, NotScheduledRange, Deleted
from modules.overlay import Overlay
from modules.poster import KometaImage
Expand Down Expand Up @@ -208,7 +208,7 @@ def __init__(self, config, metadata, name, data, library=None, overlay=None, ext
logger.info("")

if f"{self.type}_name" in methods:
logger.info(f"Config Warning: Running {self.type}_name as name")
logger.warning(f"Config Warning: Running {self.type}_name as name")
self.data["name"] = self.data[methods[f"{self.type}_name"]]
methods["name"] = "name"

Expand Down Expand Up @@ -259,9 +259,8 @@ def __init__(self, config, metadata, name, data, library=None, overlay=None, ext
if "name" in methods:
logger.debug("")
logger.debug("Validating Method: name")
logger.debug("Validating Method: name")
if not self.data[methods["name"]]:
raise Failed(f"[B310] Builder Error: 'name' attribute has no value set. Please set a value")
raise Failed(errors.no_value("name"))
logger.debug(f"Value: {self.data[methods['name']]}")
self.name = str(self.data[methods["name"]])

Expand All @@ -273,7 +272,7 @@ def __init__(self, config, metadata, name, data, library=None, overlay=None, ext
logger.debug("")
logger.debug("Validating Method: limit")
if not self.data[methods["limit"]]:
raise Failed(f"[B311] Builder Error: 'limit' attribute has no value set. Please set a value")
raise Failed(errors.no_value("limit"))
self.limit = util.parse(self.Type, "limit", self.data[methods["limit"]], datatype="int", minimum=1)

en_key = None
Expand All @@ -284,7 +283,7 @@ def __init__(self, config, metadata, name, data, library=None, overlay=None, ext
logger.debug("")
logger.debug("Validating Method: key_name")
if not self.data[methods["key_name"]]:
raise Failed(f"[B312] Builder Error: 'key_name' attribute has no value set. Please set a value")
raise Failed(errors.no_value("key_name"))
en_key = str(self.data[methods["key_name"]])
trans_key = en_key
if self.builder_language != "en":
Expand Down
3 changes: 3 additions & 0 deletions modules/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

def no_value(attribute):
return f"[B310] Builder Error: '{attribute}' attribute has no value set. Please set a value"
16 changes: 3 additions & 13 deletions modules/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,23 +217,13 @@ def _space(self, display_title):
display_title += " " * space_length
return display_title


def ghost(self, text):
if not self.ignore_ghost:
try:
print(self._space(f"| {text}"), end="\r")
except UnicodeEncodeError:
text = text.encode("utf-8")
print(self._space(f"| {text}"), end="\r")
self.spacing = len(text) + 2

def ghostnopipe(self, text):
def ghost(self, text, prefix="| "):
if not self.ignore_ghost:
try:
print(self._space(f" {text}"), end="\r")
print(self._space(f"{prefix}{text}"), end="\r")
except UnicodeEncodeError:
text = text.encode("utf-8")
print(self._space(f" {text}"), end="\r")
print(self._space(f"{prefix}{text}"), end="\r")
self.spacing = len(text) + 2

def exorcise(self):
Expand Down
4 changes: 3 additions & 1 deletion modules/tmdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from modules import util
from modules.util import Failed
from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_not_exception_type
from tmdbapis import TMDbAPIs, TMDbException, NotFound, Movie
from tmdbapis import TMDbAPIs, TMDbException, NotFound, Movie, Unauthorized

logger = util.logger

Expand Down Expand Up @@ -219,6 +219,8 @@ def __init__(self, config, params):
logger.secret(self.apikey)
try:
self.TMDb = TMDbAPIs(self.apikey, language=self.language, session=self.requests.session)
except Unauthorized:
raise Failed("[S001] Connector Error: TMDb API key is invalid. Please check the API key is correct or check TMDb guidance for obtaining a new key")
except TMDbException as e:
raise Failed(f"TMDb Error: {e}")
self.iso_3166_1 = {iso: i.name for iso, i in self.TMDb._iso_3166_1.items()} # noqa
Expand Down

0 comments on commit 5f9b517

Please sign in to comment.