refactor: delete unreferenced title cache, log, template, provider and http vault helpers

This commit is contained in:
imSp4rky
2026-11-26 13:40:07 -07:00
parent 3c90346ae4
commit 98717fda43
5 changed files with 0 additions and 214 deletions
-23
View File
@@ -210,29 +210,6 @@ def get_year_by_id(
return result.year return result.year
def get_language_by_id(
tmdb_id: int,
kind: str,
title_cacher: TitleCacher | None = None,
cache_title_id: str | None = None,
cache_region: str | None = None,
cache_account_hash: str | None = None,
) -> str | None:
"""Get original language by TMDB ID."""
if title_cacher and cache_title_id:
cached = title_cacher.get_cached_provider("tmdb", cache_title_id, kind, cache_region, cache_account_hash)
language = ((cached or {}).get("detail") or {}).get("original_language")
if language:
log.debug("Using cached TMDB original language: %s", language)
return language
tmdb = get_provider("tmdb")
if not tmdb:
return None
result = tmdb.get_by_id(tmdb_id, kind)
return result.original_language if result else None
def fetch_external_ids( def fetch_external_ids(
tmdb_id: int, tmdb_id: int,
kind: str, kind: str,
-23
View File
@@ -139,29 +139,6 @@ class TitleCacher:
raise raise
def clear_all_title_cache(self) -> None:
"""Clear all title caches for this service."""
cache_dir = config.directories.cache / self.service_name
if cache_dir.exists():
for cache_file in cache_dir.glob("titles_*.json"):
cache_file.unlink()
self.log.info(f"Cleared cache file: {cache_file.name}")
def get_cache_stats(self) -> dict:
"""Get cache statistics."""
total = sum(self.stats.values())
if total > 0:
hit_rate = (self.stats["hits"] / total) * 100
else:
hit_rate = 0
return {
"hits": self.stats["hits"],
"misses": self.stats["misses"],
"fallbacks": self.stats["fallbacks"],
"hit_rate": f"{hit_rate:.1f}%",
}
def get_cached_provider( def get_cached_provider(
self, self,
provider_name: str, provider_name: str,
-79
View File
@@ -14,7 +14,6 @@ import time
import traceback import traceback
import unicodedata import unicodedata
import zlib import zlib
from collections import defaultdict
from collections.abc import Callable, Iterator, Mapping, Sequence from collections.abc import Callable, Iterator, Mapping, Sequence
from datetime import UTC, datetime from datetime import UTC, datetime
from fractions import Fraction from fractions import Fraction
@@ -44,7 +43,6 @@ Utility functions for the unshackle media archival tool.
This module provides various utility functions including: This module provides various utility functions including:
- Font discovery and fallback system for subtitle rendering - Font discovery and fallback system for subtitle rendering
- Cross-platform system font scanning with Windows → Linux font family mapping - Cross-platform system font scanning with Windows → Linux font family mapping
- Log file management and rotation
- IP geolocation with caching and provider rotation - IP geolocation with caching and provider rotation
- Language matching utilities - Language matching utilities
- MP4/ISOBMFF box parsing - MP4/ISOBMFF box parsing
@@ -63,34 +61,6 @@ Main Font Functions:
""" """
def rotate_log_file(log_path: Path, keep: int = 20) -> Path:
"""
Update Log Filename and delete old log files.
It keeps only the 20 newest logs by default.
"""
if not log_path:
raise ValueError("A log path must be provided")
try:
log_path.relative_to(Path("")) # file name only
except ValueError:
pass
else:
log_path = config.directories.logs / log_path
log_path = log_path.parent / log_path.name.format_map(
defaultdict(str, name="root", time=datetime.now().strftime("%Y%m%d-%H%M%S"))
)
if log_path.parent.exists():
log_files = [x for x in log_path.parent.iterdir() if x.suffix == log_path.suffix]
for log_file in log_files[::-1][keep - 1 :]:
log_file.unlink()
log_path.parent.mkdir(parents=True, exist_ok=True)
return log_path
def import_module_by_path(path: Path) -> ModuleType: def import_module_by_path(path: Path) -> ModuleType:
"""Import a Python file by Path as a Module.""" """Import a Python file by Path as a Module."""
if not path: if not path:
@@ -1273,55 +1243,6 @@ class DebugLogger:
except Exception: except Exception:
return f"[{type(data).__name__}]" return f"[{type(data).__name__}]"
def log_operation_start(self, operation: str, **kwargs: Any) -> str:
"""
Log the start of an operation and return an operation ID.
Args:
operation: Name of the operation
**kwargs: Additional context
Returns:
Operation ID you can use to log the end of the operation
"""
op_id = str(uuid4())[:8]
self.log(
level="DEBUG",
operation=f"{operation}_start",
message=f"Starting operation: {operation}",
operation_id=op_id,
**kwargs,
)
return op_id
def log_operation_end(
self,
operation: str,
operation_id: str,
success: bool = True,
duration_ms: float | None = None,
**kwargs: Any,
) -> None:
"""
Log the end of an operation.
Args:
operation: Name of the operation
operation_id: Operation ID from log_operation_start
success: Whether the operation succeeded
duration_ms: Operation duration in milliseconds
**kwargs: Additional context
"""
self.log(
level="INFO" if success else "ERROR",
operation=f"{operation}_end",
message=f"Finished operation: {operation}",
operation_id=operation_id,
success=success,
duration_ms=duration_ms,
**kwargs,
)
def log_service_call(self, method: str, url: str, **kwargs: Any) -> None: def log_service_call(self, method: str, url: str, **kwargs: Any) -> None:
""" """
Log a service API call. Log a service API call.
@@ -150,19 +150,3 @@ class TemplateFormatter:
missing.append(var_name) missing.append(var_name)
return len(missing) == 0, missing return len(missing) == 0, missing
def get_required_variables(self) -> list[str]:
"""Get list of required (non-conditional) variables."""
required = []
for variable in self.variables:
if not variable.endswith("?"):
required.append(variable)
return required
def get_optional_variables(self) -> list[str]:
"""Get list of optional (conditional) variables."""
optional = []
for variable in self.variables:
if variable.endswith("?"):
optional.append(variable[:-1]) # Remove the ?
return optional
-73
View File
@@ -1,17 +1,10 @@
import json import json
from collections.abc import Iterator from collections.abc import Iterator
from enum import Enum
from uuid import UUID from uuid import UUID
from unshackle.core.vault import RateLimited, Vault, is_null_key, vault_session from unshackle.core.vault import RateLimited, Vault, is_null_key, vault_session
class InsertResult(Enum):
FAILURE = 0
SUCCESS = 1
ALREADY_EXISTS = 2
class HTTP(Vault): class HTTP(Vault):
""" """
Key Vault using HTTP API that can operate in several API modes. Key Vault using HTTP API that can operate in several API modes.
@@ -365,69 +358,3 @@ class HTTP(Vault):
This is optional and will be sent with add_key requests if available. This is optional and will be sent with add_key requests if available.
""" """
self.current_title = title self.current_title = title
def insert_key_with_result(self, service: str, kid: UUID | str, key: str, title: str | None = None) -> InsertResult:
"""
Insert a content key and return detailed result information.
This method provides more granular feedback than the standard add_key method.
Available in both API modes.
"""
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
if self.api_mode == "decrypt_labs":
return InsertResult.FAILURE
if isinstance(kid, UUID):
kid = kid.hex
if title is None:
title = getattr(self, "current_title", None)
if self.api_mode == "json":
try:
res = self.request(
"InsertKey",
{
"kid": kid,
"key": key,
"service": service.lower(),
"title": title,
},
)
if res.get("status") == "not_found":
return InsertResult.FAILURE
if res.get("inserted", False):
return InsertResult.SUCCESS
else:
return InsertResult.ALREADY_EXISTS
except Exception:
return InsertResult.FAILURE
else:
response = self.session.get(
self.url,
params={
"service": service.lower(),
"username": self.username,
"password": self.password,
"kid": kid,
"key": key,
"title": title,
},
timeout=self.timeout,
)
try:
data = response.json()
if data.get("status_code") == 200:
if data.get("inserted", True):
return InsertResult.SUCCESS
else:
return InsertResult.ALREADY_EXISTS
else:
return InsertResult.FAILURE
except Exception:
return InsertResult.FAILURE