refactor: switch to a class approach

This commit is contained in:
2025-11-17 17:17:12 +01:00
parent a33e2997aa
commit 9b317e20cb

29
main.py
View File

@@ -11,15 +11,19 @@ except ImportError:
sys.exit(1)
def login_to_audible():
class Auditui:
def __init__(self):
self.auth = None
def login_to_audible(self):
auth_file = Path.home() / ".config" / "auditui" / "auth.json"
auth_file.parent.mkdir(parents=True, exist_ok=True)
if auth_file.exists():
try:
auth = audible.Authenticator.from_file(str(auth_file))
self.auth = audible.Authenticator.from_file(str(auth_file))
print("Loaded existing authentication.")
return auth
return
except Exception as e:
print(f"Failed to load existing auth: {e}")
print("Please re-authenticate.")
@@ -36,23 +40,22 @@ def login_to_audible():
"Marketplace locale (default: US): ").strip().upper() or "US"
try:
auth = audible.Authenticator.from_login(
self.auth = audible.Authenticator.from_login(
username=email,
password=password,
locale=marketplace
)
auth_file.parent.mkdir(parents=True, exist_ok=True)
auth.to_file(str(auth_file))
self.auth.to_file(str(auth_file))
print("Authentication successful! Credentials saved.")
return auth
except Exception as e:
print(f"Authentication failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
@staticmethod
def format_runtime(minutes):
if minutes is None or minutes == 0:
return "Unknown length"
@@ -67,9 +70,8 @@ def format_runtime(minutes):
return f"{hours} hour{'s' if hours != 1 else ''}"
return f"{hours} hour{'s' if hours != 1 else ''} {mins} minute{'s' if mins != 1 else ''}"
def list_library(auth):
client = audible.Client(auth=auth)
def list_library(self):
client = audible.Client(auth=self.auth)
try:
print("\nFetching your library...")
@@ -147,7 +149,7 @@ def list_library(auth):
elif isinstance(runtime, (int, float)):
minutes = int(runtime)
runtime_str = format_runtime(minutes)
runtime_str = self.format_runtime(minutes)
asin = product.get("asin") or item.get("asin", "")
@@ -170,8 +172,9 @@ def list_library(auth):
def main():
auth = login_to_audible()
list_library(auth)
client = Auditui()
client.login_to_audible()
client.list_library()
if __name__ == "__main__":