59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
import logging
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from ..clients.jellyfin import JellyfinClient
|
|
from ..db import create_user_if_missing
|
|
from ..runtime import get_runtime_settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def sync_jellyfin_users() -> int:
|
|
runtime = get_runtime_settings()
|
|
client = JellyfinClient(runtime.jellyfin_base_url, runtime.jellyfin_api_key)
|
|
if not client.configured():
|
|
raise HTTPException(status_code=400, detail="Jellyfin not configured")
|
|
users = await client.get_users()
|
|
if not isinstance(users, list):
|
|
return 0
|
|
imported = 0
|
|
for user in users:
|
|
if not isinstance(user, dict):
|
|
continue
|
|
name = user.get("Name")
|
|
if not name:
|
|
continue
|
|
if create_user_if_missing(name, "jellyfin-user", role="user", auth_provider="jellyfin"):
|
|
imported += 1
|
|
return imported
|
|
|
|
|
|
async def run_daily_jellyfin_sync() -> None:
|
|
while True:
|
|
delay = _seconds_until_midnight()
|
|
await _sleep_seconds(delay)
|
|
try:
|
|
imported = await sync_jellyfin_users()
|
|
logger.info("Jellyfin daily sync complete: imported=%s", imported)
|
|
except HTTPException as exc:
|
|
logger.warning("Jellyfin daily sync skipped: %s", exc.detail)
|
|
except Exception:
|
|
logger.exception("Jellyfin daily sync failed")
|
|
|
|
|
|
def _seconds_until_midnight() -> float:
|
|
from datetime import datetime, timedelta
|
|
|
|
now = datetime.now()
|
|
next_midnight = (now + timedelta(days=1)).replace(
|
|
hour=0, minute=0, second=0, microsecond=0
|
|
)
|
|
return max((next_midnight - now).total_seconds(), 0.0)
|
|
|
|
|
|
async def _sleep_seconds(delay: float) -> None:
|
|
import asyncio
|
|
|
|
await asyncio.sleep(delay)
|