Add library push to website from the content editor

This commit is contained in:
SirBlob committed 2026-11-03 00:39:33 -05:00
1 parent ec57bd73b3
commit 0f90babb7a
13 files changed
+281 -20

No files matched your search

+30 -10
View File
@@ -14,15 +14,30 @@ class LibraryError(ValueError):
pass
class Site:
def __init__(self, url: str, key: str | None):
self.url = url.rstrip("/")
self.key = key
def require_key(self) -> str:
if not self.key:
raise LibraryError(f"Set an API key in .env to change the library at {self.url}")
return self.key
def api_url() -> str:
return (env_value("LIBRARY_API_URL") or DEFAULT_API_URL).rstrip("/")
def api_key() -> str:
key = env_value("LIBRARY_API_KEY")
if not key:
raise LibraryError("Set LIBRARY_API_KEY in .env to change the library")
return key
def local_site() -> Site:
return Site(api_url(), env_value("LIBRARY_API_KEY"))
def push_site() -> Site:
url = env_value("LIBRARY_PUSH_URL")
if not url:
raise LibraryError("Set LIBRARY_PUSH_URL in .env to the website to push to, for example https://dev.sirblob.co")
return Site(url, env_value("LIBRARY_PUSH_KEY") or env_value("LIBRARY_API_KEY"))
def error_message(error: urllib.error.HTTPError) -> str:
@@ -32,22 +47,23 @@ def error_message(error: urllib.error.HTTPError) -> str:
return str(error.reason)
def send(method: str, path: str, body: dict | None = None, signed: bool = True):
def send(method: str, path: str, body: dict | None = None, signed: bool = True, site: Site | None = None):
site = site or local_site()
headers = {"Accept": "application/json"}
data = None
if signed:
headers["Authorization"] = f"Bearer {api_key()}"
headers["Authorization"] = f"Bearer {site.require_key()}"
if body is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(body).encode("utf-8")
request = urllib.request.Request(f"{api_url()}{path}", data=data, headers=headers, method=method)
request = urllib.request.Request(f"{site.url}{path}", data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
text = response.read().decode("utf-8")
except urllib.error.HTTPError as error:
raise LibraryError(f"{api_url()} said {error.code}: {error_message(error)}") from error
raise LibraryError(f"{site.url} said {error.code}: {error_message(error)}") from error
except urllib.error.URLError as error:
raise LibraryError(f"Could not reach {api_url()}: {error.reason}") from error
raise LibraryError(f"Could not reach {site.url}: {error.reason}") from error
return json.loads(text) if text else None
@@ -59,6 +75,10 @@ def fetch_library() -> dict:
return send("GET", "/api/library", signed=False)
def fetch_export(site: Site) -> dict:
return send("GET", "/api/library/export", site=site)
def save_media(imdb_id: str, fields: dict) -> dict:
return send("PUT", f"/api/library/media/{quoted(imdb_id)}", fields)