Compare commits

..

4 Commits

19 changed files with 2170 additions and 795 deletions

View File

@@ -1 +1 @@
2502262257
2602262059

View File

@@ -48,6 +48,7 @@ def get_current_user(token: str = Depends(oauth2_scheme), request: Request = Non
"role": user["role"],
"auth_provider": user.get("auth_provider", "local"),
"jellyseerr_user_id": user.get("jellyseerr_user_id"),
"auto_search_enabled": bool(user.get("auto_search_enabled", True)),
}

View File

@@ -1,2 +1,3 @@
BUILD_NUMBER = "2502262257"
BUILD_NUMBER = "2602262059"
CHANGELOG = '2026-01-22\\n- Initial commit\\n- Ignore build artifacts\\n- Update README\\n- Update README with Docker-first guide\\n\\n2026-01-23\\n- Fix cache titles via Jellyseerr media lookup\\n- Split search actions and improve download options\\n- Fallback manual grab to qBittorrent\\n- Hide header actions when signed out\\n- Add feedback form and webhook\\n- Fix cache titles and move feedback link\\n- Show available status on landing when in Jellyfin\\n- Add default branding assets when missing\\n- Use bundled branding assets\\n- Remove password fields from users page\\n- Add Docker Hub compose override\\n- Fix backend Dockerfile paths for root context\\n- Copy public assets into frontend image\\n- Use backend branding assets for logo and favicon\\n\\n2026-01-24\\n- Route grabs through Sonarr/Radarr only\\n- Document fix buttons in how-it-works\\n- Clarify how-it-works steps and fixes\\n- Map Prowlarr releases to Arr indexers for manual grab\\n- Improve request handling and qBittorrent categories\\n\\n2026-01-25\\n- Add site banner, build number, and changelog\\n- Automate build number tagging and sync\\n- Improve mobile header layout\\n- Move account actions into avatar menu\\n- Add user stats and activity tracking\\n- Add Jellyfin login cache and admin-only stats\\n- Tidy request sync controls\\n- Seed branding logo from bundled assets\\n- Serve bundled branding assets by default\\n- Harden request cache titles and cache-only reads\\n- Build 2501262041\\n\\n2026-01-26\\n- Fix cache title hydration\\n- Fix sync progress bar animation\\n\\n2026-01-27\\n- Add cache control artwork stats\\n- Improve cache stats performance (build 271261145)\\n- Fix backend cache stats import (build 271261149)\\n- Clarify request sync settings (build 271261159)\\n- Bump build number to 271261202\\n- Fix request titles in snapshots (build 271261219)\\n- Fix snapshot title fallback (build 271261228)\\n- Add cache load spinner (build 271261238)\\n- Bump build number (process 2) 271261322\\n- Add service test buttons (build 271261335)\\n- Fallback to TMDB when artwork cache fails (build 271261524)\\n- Hydrate missing artwork from Jellyseerr (build 271261539)\\n\\n2026-01-29\\n- release: 2901262036\\n- release: 2901262044\\n- release: 2901262102\\n- Hardcode build number in backend\\n- Bake build number and changelog\\n- Update full changelog\\n- Tidy full changelog\\n- Build 2901262240: cache users\n\n2026-01-30\n- Merge backend and frontend into one container'

View File

@@ -30,3 +30,14 @@ class ApiClient:
response = await client.post(url, headers=self.headers(), json=payload)
response.raise_for_status()
return response.json()
async def put(self, path: str, payload: Optional[Dict[str, Any]] = None) -> Optional[Any]:
if not self.base_url:
return None
url = f"{self.base_url}{path}"
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.put(url, headers=self.headers(), json=payload)
response.raise_for_status()
if not response.content:
return None
return response.json()

View File

@@ -9,6 +9,9 @@ class RadarrClient(ApiClient):
async def get_movie_by_tmdb_id(self, tmdb_id: int) -> Optional[Dict[str, Any]]:
return await self.get("/api/v3/movie", params={"tmdbId": tmdb_id})
async def get_movie(self, movie_id: int) -> Optional[Dict[str, Any]]:
return await self.get(f"/api/v3/movie/{movie_id}")
async def get_movies(self) -> Optional[Dict[str, Any]]:
return await self.get("/api/v3/movie")
@@ -44,6 +47,9 @@ class RadarrClient(ApiClient):
}
return await self.post("/api/v3/movie", payload=payload)
async def update_movie(self, payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
return await self.put("/api/v3/movie", payload=payload)
async def grab_release(self, guid: str, indexer_id: int) -> Optional[Dict[str, Any]]:
return await self.post("/api/v3/release", payload={"guid": guid, "indexerId": indexer_id})

View File

@@ -9,6 +9,9 @@ class SonarrClient(ApiClient):
async def get_series_by_tvdb_id(self, tvdb_id: int) -> Optional[Dict[str, Any]]:
return await self.get("/api/v3/series", params={"tvdbId": tvdb_id})
async def get_series(self, series_id: int) -> Optional[Dict[str, Any]]:
return await self.get(f"/api/v3/series/{series_id}")
async def get_root_folders(self) -> Optional[Dict[str, Any]]:
return await self.get("/api/v3/rootfolder")
@@ -51,6 +54,9 @@ class SonarrClient(ApiClient):
payload["title"] = title
return await self.post("/api/v3/series", payload=payload)
async def update_series(self, payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
return await self.put("/api/v3/series", payload=payload)
async def grab_release(self, guid: str, indexer_id: int) -> Optional[Dict[str, Any]]:
return await self.post("/api/v3/release", payload={"guid": guid, "indexerId": indexer_id})

View File

@@ -50,12 +50,6 @@ class Settings(BaseSettings):
default="info", validation_alias=AliasChoices("SITE_BANNER_TONE")
)
site_changelog: Optional[str] = Field(default=CHANGELOG)
apprise_base_url: Optional[str] = Field(
default=None, validation_alias=AliasChoices("APPRISE_URL", "APPRISE_BASE_URL")
)
apprise_api_key: Optional[str] = Field(
default=None, validation_alias=AliasChoices("APPRISE_API_KEY")
)
jellyseerr_base_url: Optional[str] = Field(
default=None, validation_alias=AliasChoices("JELLYSEERR_URL", "JELLYSEERR_BASE_URL")

View File

@@ -149,11 +149,9 @@ def init_db() -> None:
created_at TEXT NOT NULL,
last_login_at TEXT,
is_blocked INTEGER NOT NULL DEFAULT 0,
auto_search_enabled INTEGER NOT NULL DEFAULT 1,
jellyfin_password_hash TEXT,
last_jellyfin_auth_at TEXT,
notify_enabled INTEGER NOT NULL DEFAULT 0,
notify_urls TEXT,
notify_updated_at TEXT
last_jellyfin_auth_at TEXT
)
"""
)
@@ -268,17 +266,7 @@ def init_db() -> None:
except sqlite3.OperationalError:
pass
try:
conn.execute(
"ALTER TABLE users ADD COLUMN notify_enabled INTEGER NOT NULL DEFAULT 0"
)
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE users ADD COLUMN notify_urls TEXT")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE users ADD COLUMN notify_updated_at TEXT")
conn.execute("ALTER TABLE users ADD COLUMN auto_search_enabled INTEGER NOT NULL DEFAULT 1")
except sqlite3.OperationalError:
pass
try:
@@ -441,7 +429,7 @@ def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
row = conn.execute(
"""
SELECT id, username, password_hash, role, auth_provider, jellyseerr_user_id,
created_at, last_login_at, is_blocked, jellyfin_password_hash, last_jellyfin_auth_at
created_at, last_login_at, is_blocked, auto_search_enabled, jellyfin_password_hash, last_jellyfin_auth_at
FROM users
WHERE username = ? COLLATE NOCASE
""",
@@ -459,8 +447,9 @@ def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
"created_at": row[6],
"last_login_at": row[7],
"is_blocked": bool(row[8]),
"jellyfin_password_hash": row[9],
"last_jellyfin_auth_at": row[10],
"auto_search_enabled": bool(row[9]),
"jellyfin_password_hash": row[10],
"last_jellyfin_auth_at": row[11],
}
@@ -469,7 +458,7 @@ def get_user_by_id(user_id: int) -> Optional[Dict[str, Any]]:
row = conn.execute(
"""
SELECT id, username, password_hash, role, auth_provider, jellyseerr_user_id,
created_at, last_login_at, is_blocked, jellyfin_password_hash, last_jellyfin_auth_at
created_at, last_login_at, is_blocked, auto_search_enabled, jellyfin_password_hash, last_jellyfin_auth_at
FROM users
WHERE id = ?
""",
@@ -487,84 +476,16 @@ def get_user_by_id(user_id: int) -> Optional[Dict[str, Any]]:
"created_at": row[6],
"last_login_at": row[7],
"is_blocked": bool(row[8]),
"jellyfin_password_hash": row[9],
"last_jellyfin_auth_at": row[10],
"auto_search_enabled": bool(row[9]),
"jellyfin_password_hash": row[10],
"last_jellyfin_auth_at": row[11],
}
def get_user_notification_settings(username: str) -> Dict[str, Any]:
if not username:
return {"enabled": False, "urls": []}
with _connect() as conn:
row = conn.execute(
"""
SELECT notify_enabled, notify_urls
FROM users
WHERE username = ? COLLATE NOCASE
""",
(username,),
).fetchone()
if not row:
return {"enabled": False, "urls": []}
enabled = bool(row[0])
urls_raw = row[1]
urls: list[str] = []
if isinstance(urls_raw, str) and urls_raw.strip():
try:
parsed = json.loads(urls_raw)
if isinstance(parsed, list):
urls = [str(item).strip() for item in parsed if str(item).strip()]
except json.JSONDecodeError:
urls = [urls_raw.strip()]
return {"enabled": enabled, "urls": urls}
def set_user_notification_settings(username: str, enabled: bool, urls: list[str]) -> None:
if not username:
return
urls_payload = json.dumps(urls, ensure_ascii=True)
updated_at = datetime.now(timezone.utc).isoformat()
with _connect() as conn:
conn.execute(
"""
UPDATE users
SET notify_enabled = ?, notify_urls = ?, notify_updated_at = ?
WHERE username = ? COLLATE NOCASE
""",
(1 if enabled else 0, urls_payload, updated_at, username),
)
def get_admin_notification_targets() -> list[Dict[str, Any]]:
with _connect() as conn:
rows = conn.execute(
"""
SELECT username, notify_urls
FROM users
WHERE role = 'admin' AND notify_enabled = 1
ORDER BY username COLLATE NOCASE
"""
).fetchall()
results: list[Dict[str, Any]] = []
for row in rows:
username, urls_raw = row
urls: list[str] = []
if isinstance(urls_raw, str) and urls_raw.strip():
try:
parsed = json.loads(urls_raw)
if isinstance(parsed, list):
urls = [str(item).strip() for item in parsed if str(item).strip()]
except json.JSONDecodeError:
urls = [urls_raw.strip()]
if urls:
results.append({"username": username, "urls": urls})
return results
def get_all_users() -> list[Dict[str, Any]]:
with _connect() as conn:
rows = conn.execute(
"""
SELECT id, username, role, auth_provider, jellyseerr_user_id, created_at, last_login_at, is_blocked
SELECT id, username, role, auth_provider, jellyseerr_user_id, created_at, last_login_at, is_blocked, auto_search_enabled
FROM users
ORDER BY username COLLATE NOCASE
"""
@@ -581,10 +502,12 @@ def get_all_users() -> list[Dict[str, Any]]:
"created_at": row[5],
"last_login_at": row[6],
"is_blocked": bool(row[7]),
"auto_search_enabled": bool(row[8]),
}
)
return results
def delete_non_admin_users() -> int:
with _connect() as conn:
cursor = conn.execute(
@@ -636,13 +559,102 @@ def set_user_role(username: str, role: str) -> None:
)
def set_user_auto_search_enabled(username: str, enabled: bool) -> None:
with _connect() as conn:
conn.execute(
"""
UPDATE users SET auto_search_enabled = ? WHERE username = ?
""",
(1 if enabled else 0, username),
)
def set_auto_search_enabled_for_non_admin_users(enabled: bool) -> int:
with _connect() as conn:
cursor = conn.execute(
"""
UPDATE users SET auto_search_enabled = ? WHERE role != 'admin'
""",
(1 if enabled else 0,),
)
return cursor.rowcount
def verify_user_password(username: str, password: str) -> Optional[Dict[str, Any]]:
user = get_user_by_username(username)
if not user:
# Resolve case-insensitive duplicates safely by only considering local-provider rows.
with _connect() as conn:
rows = conn.execute(
"""
SELECT id, username, password_hash, role, auth_provider, jellyseerr_user_id,
created_at, last_login_at, is_blocked, auto_search_enabled,
jellyfin_password_hash, last_jellyfin_auth_at
FROM users
WHERE username = ? COLLATE NOCASE
ORDER BY
CASE WHEN username = ? THEN 0 ELSE 1 END,
id ASC
""",
(username, username),
).fetchall()
if not rows:
return None
if not verify_password(password, user["password_hash"]):
return None
return user
for row in rows:
provider = str(row[4] or "local").lower()
if provider != "local":
continue
if not verify_password(password, row[2]):
continue
return {
"id": row[0],
"username": row[1],
"password_hash": row[2],
"role": row[3],
"auth_provider": row[4],
"jellyseerr_user_id": row[5],
"created_at": row[6],
"last_login_at": row[7],
"is_blocked": bool(row[8]),
"auto_search_enabled": bool(row[9]),
"jellyfin_password_hash": row[10],
"last_jellyfin_auth_at": row[11],
}
return None
def get_users_by_username_ci(username: str) -> list[Dict[str, Any]]:
with _connect() as conn:
rows = conn.execute(
"""
SELECT id, username, password_hash, role, auth_provider, jellyseerr_user_id,
created_at, last_login_at, is_blocked, auto_search_enabled,
jellyfin_password_hash, last_jellyfin_auth_at
FROM users
WHERE username = ? COLLATE NOCASE
ORDER BY
CASE WHEN username = ? THEN 0 ELSE 1 END,
id ASC
""",
(username, username),
).fetchall()
results: list[Dict[str, Any]] = []
for row in rows:
results.append(
{
"id": row[0],
"username": row[1],
"password_hash": row[2],
"role": row[3],
"auth_provider": row[4],
"jellyseerr_user_id": row[5],
"created_at": row[6],
"last_login_at": row[7],
"is_blocked": bool(row[8]),
"auto_search_enabled": bool(row[9]),
"jellyfin_password_hash": row[10],
"last_jellyfin_auth_at": row[11],
}
)
return results
def set_user_password(username: str, password: str) -> None:

View File

@@ -24,6 +24,8 @@ from ..db import (
set_user_jellyseerr_id,
set_setting,
set_user_blocked,
set_user_auto_search_enabled,
set_auto_search_enabled_for_non_admin_users,
set_user_password,
set_user_role,
run_integrity_check,
@@ -34,7 +36,6 @@ from ..db import (
update_request_cache_title,
repair_request_cache_titles,
delete_non_admin_users,
get_user_notification_settings,
)
from ..runtime import get_runtime_settings
from ..clients.sonarr import SonarrClient
@@ -50,7 +51,6 @@ from ..services.user_cache import (
save_jellyfin_users_cache,
save_jellyseerr_users_cache,
)
from ..services.notifications import send_apprise_notification
import logging
from ..logging_config import configure_logging
from ..routers import requests as requests_router
@@ -66,7 +66,6 @@ SENSITIVE_KEYS = {
"radarr_api_key",
"prowlarr_api_key",
"qbittorrent_password",
"apprise_api_key",
}
URL_SETTING_KEYS = {
@@ -77,7 +76,6 @@ URL_SETTING_KEYS = {
"radarr_base_url",
"prowlarr_base_url",
"qbittorrent_base_url",
"apprise_base_url",
}
SETTING_KEYS: List[str] = [
@@ -105,8 +103,6 @@ SETTING_KEYS: List[str] = [
"qbittorrent_password",
"log_level",
"log_file",
"apprise_base_url",
"apprise_api_key",
"requests_sync_ttl_minutes",
"requests_poll_interval_seconds",
"requests_delta_sync_interval_minutes",
@@ -614,72 +610,6 @@ async def list_users() -> Dict[str, Any]:
users = [user for user in get_all_users() if user.get("role") == "admin" or user.get("auth_provider") == "jellyseerr"]
return {"users": users}
@router.get("/notifications/users")
async def list_notification_users() -> Dict[str, Any]:
users = get_all_users()
results: list[Dict[str, Any]] = []
for user in users:
username = user.get("username") or ""
settings = get_user_notification_settings(username)
results.append(
{
"username": username,
"role": user.get("role"),
"authProvider": user.get("auth_provider"),
"jellyseerrUserId": user.get("jellyseerr_user_id"),
"isBlocked": bool(user.get("is_blocked")),
"notifyEnabled": bool(settings.get("enabled")),
"notifyCount": len(settings.get("urls") or []),
}
)
return {"users": results}
@router.post("/notifications/send")
async def send_notifications(payload: Dict[str, Any]) -> Dict[str, Any]:
usernames = payload.get("usernames")
message = payload.get("message")
title = payload.get("title") or "Magent admin message"
if not isinstance(usernames, list) or not usernames:
raise HTTPException(status_code=400, detail="Select at least one user.")
if not isinstance(message, str) or not message.strip():
raise HTTPException(status_code=400, detail="Message cannot be empty.")
results: list[Dict[str, Any]] = []
counts = {"sent": 0, "skipped": 0, "failed": 0}
for raw_username in usernames:
if not isinstance(raw_username, str) or not raw_username.strip():
results.append({"username": str(raw_username), "status": "invalid"})
counts["failed"] += 1
continue
username = raw_username.strip()
user = get_user_by_username(username)
if not user:
results.append({"username": username, "status": "not_found"})
counts["failed"] += 1
continue
if user.get("is_blocked"):
results.append({"username": username, "status": "blocked"})
counts["skipped"] += 1
continue
settings = get_user_notification_settings(username)
if not settings.get("enabled"):
results.append({"username": username, "status": "disabled"})
counts["skipped"] += 1
continue
urls = settings.get("urls") or []
if not urls:
results.append({"username": username, "status": "no_targets"})
counts["skipped"] += 1
continue
ok = send_apprise_notification(urls, str(title).strip() or "Magent admin message", message.strip())
if ok:
results.append({"username": username, "status": "sent"})
counts["sent"] += 1
else:
results.append({"username": username, "status": "failed"})
counts["failed"] += 1
return {"results": results, **counts}
@router.get("/users/summary")
async def list_users_summary() -> Dict[str, Any]:
users = [user for user in get_all_users() if user.get("role") == "admin" or user.get("auth_provider") == "jellyseerr"]
@@ -732,6 +662,32 @@ async def update_user_role(username: str, payload: Dict[str, Any]) -> Dict[str,
return {"status": "ok", "username": username, "role": role}
@router.post("/users/{username}/auto-search")
async def update_user_auto_search(username: str, payload: Dict[str, Any]) -> Dict[str, Any]:
enabled = payload.get("enabled") if isinstance(payload, dict) else None
if not isinstance(enabled, bool):
raise HTTPException(status_code=400, detail="enabled must be true or false")
user = get_user_by_username(username)
if not user:
raise HTTPException(status_code=404, detail="User not found")
set_user_auto_search_enabled(username, enabled)
return {"status": "ok", "username": username, "auto_search_enabled": enabled}
@router.post("/users/auto-search/bulk")
async def update_users_auto_search_bulk(payload: Dict[str, Any]) -> Dict[str, Any]:
enabled = payload.get("enabled") if isinstance(payload, dict) else None
if not isinstance(enabled, bool):
raise HTTPException(status_code=400, detail="enabled must be true or false")
updated = set_auto_search_enabled_for_non_admin_users(enabled)
return {
"status": "ok",
"enabled": enabled,
"updated": updated,
"scope": "non-admin-users",
}
@router.post("/users/{username}/password")
async def update_user_password(username: str, payload: Dict[str, Any]) -> Dict[str, Any]:
new_password = payload.get("password") if isinstance(payload, dict) else None

View File

@@ -1,5 +1,4 @@
from datetime import datetime, timedelta, timezone
import asyncio
from fastapi import APIRouter, HTTPException, status, Depends
from fastapi.security import OAuth2PasswordRequestForm
@@ -9,6 +8,7 @@ from ..db import (
create_user_if_missing,
set_last_login,
get_user_by_username,
get_users_by_username_ci,
set_user_password,
set_jellyfin_auth_cache,
set_user_jellyseerr_id,
@@ -17,8 +17,6 @@ from ..db import (
get_user_request_stats,
get_global_request_leader,
get_global_request_total,
get_user_notification_settings,
set_user_notification_settings,
)
from ..runtime import get_runtime_settings
from ..clients.jellyfin import JellyfinClient
@@ -31,11 +29,6 @@ from ..services.user_cache import (
match_jellyseerr_user_id,
save_jellyfin_users_cache,
)
from ..services.notifications import (
notify_admins_new_signup,
send_apprise_notification,
validate_apprise_urls,
)
router = APIRouter(prefix="/auth", tags=["auth"])
@@ -90,9 +83,26 @@ def _extract_jellyseerr_user_id(response: dict) -> int | None:
@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()) -> dict:
# Provider placeholder passwords must never be accepted by the local-login endpoint.
if form_data.password in {"jellyfin-user", "jellyseerr-user"}:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
matching_users = get_users_by_username_ci(form_data.username)
has_external_match = any(
str(user.get("auth_provider") or "local").lower() != "local" for user in matching_users
)
if has_external_match:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="This account uses external sign-in. Use the external sign-in option.",
)
user = verify_user_password(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
if str(user.get("auth_provider") or "local").lower() != "local":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="This account uses external sign-in. Use the external sign-in option.",
)
if user.get("is_blocked"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
token = create_access_token(user["username"], user["role"])
@@ -127,14 +137,10 @@ async def jellyfin_login(form_data: OAuth2PasswordRequestForm = Depends()) -> di
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
if not isinstance(response, dict) or not response.get("User"):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Jellyfin credentials")
created = create_user_if_missing(username, "jellyfin-user", role="user", auth_provider="jellyfin")
create_user_if_missing(username, "jellyfin-user", role="user", auth_provider="jellyfin")
user = get_user_by_username(username)
if user and user.get("is_blocked"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
if created:
asyncio.create_task(
asyncio.to_thread(notify_admins_new_signup, username, "jellyfin")
)
try:
users = await client.get_users()
if isinstance(users, list):
@@ -171,7 +177,7 @@ async def jellyseerr_login(form_data: OAuth2PasswordRequestForm = Depends()) ->
if not isinstance(response, dict):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Jellyseerr credentials")
jellyseerr_user_id = _extract_jellyseerr_user_id(response)
created = create_user_if_missing(
create_user_if_missing(
form_data.username,
"jellyseerr-user",
role="user",
@@ -183,10 +189,6 @@ async def jellyseerr_login(form_data: OAuth2PasswordRequestForm = Depends()) ->
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
if jellyseerr_user_id is not None:
set_user_jellyseerr_id(form_data.username, jellyseerr_user_id)
if created:
asyncio.create_task(
asyncio.to_thread(notify_admins_new_signup, form_data.username, "jellyseerr")
)
token = create_access_token(form_data.username, "user")
set_last_login(form_data.username)
return {"access_token": token, "token_type": "bearer", "user": {"username": form_data.username, "role": "user"}}
@@ -223,48 +225,6 @@ async def profile(current_user: dict = Depends(get_current_user)) -> dict:
}
@router.get("/notifications")
async def get_notifications(current_user: dict = Depends(get_current_user)) -> dict:
settings = get_user_notification_settings(current_user.get("username") or "")
return settings
@router.put("/notifications")
async def update_notifications(payload: dict, current_user: dict = Depends(get_current_user)) -> dict:
if not isinstance(payload, dict):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid payload")
enabled = bool(payload.get("enabled"))
urls_raw = payload.get("urls") or []
if isinstance(urls_raw, str):
urls = [line.strip() for line in urls_raw.splitlines() if line.strip()]
elif isinstance(urls_raw, list):
urls = [str(item).strip() for item in urls_raw if str(item).strip()]
else:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid URLs")
try:
validated = validate_apprise_urls(urls)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
set_user_notification_settings(current_user.get("username") or "", enabled, validated)
return {"status": "ok", "enabled": enabled, "urls": validated}
@router.post("/notifications/test")
async def test_notifications(current_user: dict = Depends(get_current_user)) -> dict:
settings = get_user_notification_settings(current_user.get("username") or "")
if not settings.get("enabled"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Notifications are disabled")
urls = settings.get("urls") or []
if not urls:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No Apprise URLs configured")
title = "Magent notification test"
body = f"Hello {current_user.get('username')}, your Apprise notifications are working."
sent = await asyncio.to_thread(send_apprise_notification, urls, title, body)
if not sent:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Notification failed")
return {"status": "ok"}
@router.post("/password")
async def change_password(payload: dict, current_user: dict = Depends(get_current_user)) -> dict:
if current_user.get("auth_provider") != "local":

View File

@@ -120,6 +120,27 @@ def _normalize_username(value: Any) -> Optional[str]:
return normalized if normalized else None
def _user_can_use_search_auto(user: Dict[str, Any]) -> bool:
if user.get("role") == "admin":
return True
return bool(user.get("auto_search_enabled", True))
def _filter_snapshot_actions_for_user(snapshot: Snapshot, user: Dict[str, Any]) -> Snapshot:
if _user_can_use_search_auto(user):
return snapshot
snapshot.actions = [action for action in snapshot.actions if action.id != "search_auto"]
return snapshot
def _quality_profile_id(value: Any) -> Optional[int]:
if isinstance(value, int):
return value
if isinstance(value, str) and value.strip().isdigit():
return int(value.strip())
return None
def _request_matches_user(request_data: Any, username: str) -> bool:
requested_by = None
if isinstance(request_data, dict):
@@ -1476,7 +1497,8 @@ async def get_snapshot(request_id: str, user: Dict[str, str] = Depends(get_curre
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
if client.configured():
await _ensure_request_access(client, int(request_id), user)
return await build_snapshot(request_id)
snapshot = await build_snapshot(request_id)
return _filter_snapshot_actions_for_user(snapshot, user)
@router.get("/recent")
@@ -1747,7 +1769,7 @@ async def ai_triage(request_id: str, user: Dict[str, str] = Depends(get_current_
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
if client.configured():
await _ensure_request_access(client, int(request_id), user)
snapshot = await build_snapshot(request_id)
snapshot = _filter_snapshot_actions_for_user(await build_snapshot(request_id), user)
return triage_snapshot(snapshot)
@@ -1784,6 +1806,8 @@ async def action_search(request_id: str, user: Dict[str, str] = Depends(get_curr
@router.post("/{request_id}/actions/search_auto")
async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get_current_user)) -> dict:
if not _user_can_use_search_auto(user):
raise HTTPException(status_code=403, detail="Auto search and download is disabled for this user")
runtime = get_runtime_settings()
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
if client.configured():
@@ -1797,10 +1821,23 @@ async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get
client = SonarrClient(runtime.sonarr_base_url, runtime.sonarr_api_key)
if not client.configured():
raise HTTPException(status_code=400, detail="Sonarr not configured")
target_profile_id = _quality_profile_id(runtime.sonarr_quality_profile_id)
current_profile_id = _quality_profile_id(arr_item.get("qualityProfileId"))
profile_message = None
series_id = _quality_profile_id(arr_item.get("id"))
if target_profile_id and series_id and current_profile_id != target_profile_id:
series = await client.get_series(series_id)
if not isinstance(series, dict):
raise HTTPException(status_code=502, detail="Could not load Sonarr series before search")
series["qualityProfileId"] = target_profile_id
await client.update_series(series)
profile_message = f"Sonarr quality profile updated to {target_profile_id} before search."
episodes = await client.get_episodes(int(arr_item["id"]))
missing_by_season = _missing_episode_ids_by_season(episodes)
if not missing_by_season:
message = "No missing monitored episodes found."
if profile_message:
message = f"{profile_message} {message}"
await asyncio.to_thread(
save_action, request_id, "search_auto", "Search and auto-download", "ok", message
)
@@ -1814,6 +1851,8 @@ async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get
{"season": season_number, "episodeCount": len(episode_ids), "response": response}
)
message = "Search sent to Sonarr."
if profile_message:
message = f"{profile_message} {message}"
await asyncio.to_thread(
save_action, request_id, "search_auto", "Search and auto-download", "ok", message
)
@@ -1822,8 +1861,21 @@ async def action_search_auto(request_id: str, user: Dict[str, str] = Depends(get
client = RadarrClient(runtime.radarr_base_url, runtime.radarr_api_key)
if not client.configured():
raise HTTPException(status_code=400, detail="Radarr not configured")
target_profile_id = _quality_profile_id(runtime.radarr_quality_profile_id)
current_profile_id = _quality_profile_id(arr_item.get("qualityProfileId"))
profile_message = None
movie_id = _quality_profile_id(arr_item.get("id"))
if target_profile_id and movie_id and current_profile_id != target_profile_id:
movie = await client.get_movie(movie_id)
if not isinstance(movie, dict):
raise HTTPException(status_code=502, detail="Could not load Radarr movie before search")
movie["qualityProfileId"] = target_profile_id
await client.update_movie(movie)
profile_message = f"Radarr quality profile updated to {target_profile_id} before search."
response = await client.search(int(arr_item["id"]))
message = "Search sent to Radarr."
if profile_message:
message = f"{profile_message} {message}"
await asyncio.to_thread(
save_action, request_id, "search_auto", "Search and auto-download", "ok", message
)

View File

@@ -1,125 +0,0 @@
from __future__ import annotations
import logging
from datetime import datetime, timezone
from typing import Iterable, List
import httpx
from ..db import get_admin_notification_targets
from ..runtime import get_runtime_settings
logger = logging.getLogger(__name__)
def _normalize_urls(urls: Iterable[str]) -> List[str]:
normalized: list[str] = []
seen: set[str] = set()
for entry in urls:
if not isinstance(entry, str):
continue
value = entry.strip()
if value and value not in seen:
normalized.append(value)
seen.add(value)
return normalized
def validate_apprise_urls(urls: Iterable[str]) -> List[str]:
normalized = _normalize_urls(urls)
if not normalized:
return []
invalid: list[str] = []
for url in normalized:
if "://" not in url:
invalid.append(url)
if invalid:
raise ValueError(
"Invalid Apprise URL(s): "
+ ", ".join(invalid)
+ " (each URL must include a scheme like discord:// or mailto://)"
)
return normalized
def _get_apprise_notify_url() -> str | None:
runtime = get_runtime_settings()
base_url = (runtime.apprise_base_url or "").strip()
if not base_url:
return None
if "://" not in base_url:
base_url = f"http://{base_url}"
base_url = base_url.rstrip("/")
if base_url.endswith("/notify"):
return base_url
return f"{base_url}/notify"
def _get_apprise_headers() -> dict[str, str]:
runtime = get_runtime_settings()
headers = {"Content-Type": "application/json"}
api_key = (runtime.apprise_api_key or "").strip()
if api_key:
headers["X-API-Key"] = api_key
headers["Authorization"] = f"Bearer {api_key}"
return headers
def send_apprise_notification(urls: Iterable[str], title: str, body: str) -> bool:
try:
normalized = validate_apprise_urls(urls)
except ValueError as exc:
logger.warning("Apprise notification skipped due to invalid URL(s): %s", exc)
return False
if not normalized:
return False
notify_url = _get_apprise_notify_url()
if not notify_url:
logger.warning("Apprise notification skipped: APPRISE_BASE_URL is not configured.")
return False
payload = {
"urls": normalized,
"title": str(title or "Magent notification").strip() or "Magent notification",
"body": str(body or "").strip(),
}
if not payload["body"]:
return False
try:
with httpx.Client(timeout=10.0) as client:
response = client.post(notify_url, headers=_get_apprise_headers(), json=payload)
response.raise_for_status()
except httpx.HTTPError as exc:
logger.warning("Apprise sidecar notify failed: %s", exc)
return False
try:
data = response.json()
except ValueError:
return True
if isinstance(data, dict):
if data.get("status") in {"error", "failed"}:
return False
if "sent" in data:
return bool(data.get("sent"))
return True
def notify_admins_new_signup(username: str, provider: str) -> int:
targets = get_admin_notification_targets()
if not targets:
return 0
timestamp = datetime.now(timezone.utc).isoformat()
title = "New Magent user signup"
body = f"User {username} signed in via {provider} at {timestamp}."
sent = 0
for target in targets:
urls = target.get("urls") or []
if send_apprise_notification(urls, title, body):
sent += 1
if sent == 0:
logger.info("Apprise signup notification skipped (no valid admin targets).")
return sent

View File

@@ -27,7 +27,6 @@ const SECTION_LABELS: Record<string, string> = {
radarr: 'Radarr',
prowlarr: 'Prowlarr',
qbittorrent: 'qBittorrent',
apprise: 'Apprise',
log: 'Activity log',
requests: 'Request sync',
site: 'Site',
@@ -43,7 +42,6 @@ const URL_SETTINGS = new Set([
'radarr_base_url',
'prowlarr_base_url',
'qbittorrent_base_url',
'apprise_base_url',
])
const BANNER_TONES = ['info', 'warning', 'error', 'maintenance']
@@ -56,7 +54,6 @@ const SECTION_DESCRIPTIONS: Record<string, string> = {
radarr: 'Movie automation settings.',
prowlarr: 'Indexer search settings.',
qbittorrent: 'Downloader connection settings.',
apprise: 'Configure the external Apprise sidecar used for notifications.',
requests: 'Control how often requests are refreshed and cleaned up.',
log: 'Activity log for troubleshooting.',
site: 'Sitewide banner, version, and changelog details.',
@@ -70,7 +67,6 @@ const SETTINGS_SECTION_MAP: Record<string, string | null> = {
radarr: 'radarr',
prowlarr: 'prowlarr',
qbittorrent: 'qbittorrent',
apprise: 'apprise',
requests: 'requests',
cache: null,
logs: 'log',
@@ -370,10 +366,6 @@ export default function SettingsPage({ section }: SettingsPageProps) {
'qBittorrent server URL for download status (FQDN or IP). Scheme is optional.',
qbittorrent_username: 'qBittorrent login username.',
qbittorrent_password: 'qBittorrent login password.',
apprise_base_url:
'External Apprise API base URL for notifications (for example http://apprise:8000).',
apprise_api_key:
'Optional API key Magent uses when calling your external Apprise service.',
requests_sync_ttl_minutes: 'How long saved requests stay fresh before a refresh is needed.',
requests_poll_interval_seconds:
'How often Magent checks if a full refresh should run.',
@@ -401,7 +393,6 @@ export default function SettingsPage({ section }: SettingsPageProps) {
radarr_base_url: 'https://radarr.example.com or 10.30.1.81:7878',
prowlarr_base_url: 'https://prowlarr.example.com or 10.30.1.81:9696',
qbittorrent_base_url: 'https://qb.example.com or 10.30.1.81:8080',
apprise_base_url: 'http://apprise:8000 or https://notify.example.com',
}
const buildSelectOptions = (

View File

@@ -1,281 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { authFetch, clearToken, getApiBase, getToken } from '../../lib/auth'
import AdminShell from '../../ui/AdminShell'
type NotificationUser = {
username: string
role?: string | null
authProvider?: string | null
jellyseerrUserId?: number | null
isBlocked?: boolean
notifyEnabled?: boolean
notifyCount?: number
}
type SendResult = {
username: string
status: string
}
const formatStatus = (user: NotificationUser) => {
if (user.isBlocked) return 'Blocked'
if (!user.notifyEnabled) return 'Disabled'
if (user.notifyCount && user.notifyCount > 0) return `Enabled (${user.notifyCount})`
return 'No targets'
}
export default function AdminNotificationsPage() {
const router = useRouter()
const [users, setUsers] = useState<NotificationUser[]>([])
const [selected, setSelected] = useState<Set<string>>(new Set())
const [title, setTitle] = useState('')
const [message, setMessage] = useState('')
const [loading, setLoading] = useState(false)
const [sending, setSending] = useState(false)
const [status, setStatus] = useState<string | null>(null)
const [sendResults, setSendResults] = useState<SendResult[]>([])
const selectedCount = selected.size
const selectableUsers = useMemo(
() => users.filter((user) => user.username && !user.isBlocked),
[users]
)
const load = async () => {
if (!getToken()) {
router.push('/login')
return
}
setLoading(true)
setStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/notifications/users`)
if (!response.ok) {
if (response.status === 401) {
clearToken()
router.push('/login')
return
}
if (response.status === 403) {
router.push('/')
return
}
throw new Error('Load failed')
}
const data = await response.json()
const fetched = Array.isArray(data?.users) ? data.users : []
setUsers(fetched)
setSelected(new Set())
} catch (err) {
console.error(err)
setStatus('Unable to load notification targets.')
} finally {
setLoading(false)
}
}
useEffect(() => {
void load()
}, [])
const toggleUser = (username: string) => {
setSelected((current) => {
const next = new Set(current)
if (next.has(username)) {
next.delete(username)
} else {
next.add(username)
}
return next
})
}
const selectAll = () => {
const next = new Set<string>()
for (const user of selectableUsers) {
if (user.username) {
next.add(user.username)
}
}
setSelected(next)
}
const selectEnabled = () => {
const next = new Set<string>()
for (const user of selectableUsers) {
if (user.username && user.notifyEnabled && (user.notifyCount ?? 0) > 0) {
next.add(user.username)
}
}
setSelected(next)
}
const clearSelection = () => {
setSelected(new Set())
}
const send = async () => {
setStatus(null)
setSendResults([])
if (selectedCount === 0) {
setStatus('Select at least one user.')
return
}
if (!message.trim()) {
setStatus('Message cannot be empty.')
return
}
setSending(true)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/notifications/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
usernames: Array.from(selected),
title: title.trim() || 'Magent admin message',
message: message.trim(),
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Send failed')
}
const data = await response.json()
const results = Array.isArray(data?.results) ? data.results : []
setSendResults(results)
setStatus(
`Sent ${data?.sent ?? 0}. Skipped ${data?.skipped ?? 0}. Failed ${data?.failed ?? 0}.`
)
} catch (err) {
console.error(err)
const message =
err instanceof Error && err.message
? err.message.replace(/^\\{\"detail\":\"|\"\\}$/g, '')
: 'Send failed.'
setStatus(message)
} finally {
setSending(false)
}
}
return (
<AdminShell
title="User notifications"
subtitle="Send admin messages to users via their Apprise targets."
actions={
<button type="button" onClick={() => router.push('/admin')}>
Back to settings
</button>
}
>
<section className="admin-section">
<div className="admin-toolbar">
<div className="admin-toolbar-info">
<span>{users.length.toLocaleString()} users</span>
<span>{selectedCount.toLocaleString()} selected</span>
</div>
<div className="admin-toolbar-actions">
<button type="button" onClick={selectAll} disabled={loading}>
Select all
</button>
<button type="button" onClick={selectEnabled} disabled={loading}>
Select enabled
</button>
<button type="button" className="ghost-button" onClick={clearSelection}>
Clear
</button>
</div>
</div>
{loading ? (
<div className="status-banner">Loading notification targets</div>
) : users.length === 0 ? (
<div className="status-banner">No users found.</div>
) : (
<div className="admin-table">
<div className="admin-table-head">
<span>Select</span>
<span>User</span>
<span>Role</span>
<span>Status</span>
</div>
{users.map((user) => {
const username = user.username || 'Unknown'
const isChecked = selected.has(username)
return (
<div key={username} className="admin-table-row">
<span>
<input
type="checkbox"
checked={isChecked}
onChange={() => toggleUser(username)}
disabled={!username || user.isBlocked}
/>
</span>
<span>{username}</span>
<span>{user.role || 'user'}</span>
<span>{formatStatus(user)}</span>
</div>
)
})}
</div>
)}
</section>
<section className="admin-section">
<div className="section-header">
<h2>Message</h2>
</div>
<div className="admin-form">
<label>
<span className="label-row">
<span>Title</span>
<span className="meta">Optional</span>
</span>
<input
type="text"
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder="Magent admin message"
/>
</label>
<label>
<span className="label-row">
<span>Message</span>
<span className="meta">Required</span>
</span>
<textarea
rows={4}
value={message}
onChange={(event) => setMessage(event.target.value)}
placeholder="Write the message you want to send."
/>
</label>
</div>
{status && <div className="status-banner">{status}</div>}
<div className="admin-actions">
<button type="button" onClick={send} disabled={sending}>
{sending ? 'Sending…' : 'Send message'}
</button>
</div>
{sendResults.length > 0 && (
<div className="admin-table">
<div className="admin-table-head">
<span>User</span>
<span>Result</span>
</div>
{sendResults.map((result) => (
<div key={`${result.username}-${result.status}`} className="admin-table-row">
<span>{result.username}</span>
<span>{result.status}</span>
</div>
))}
</div>
)}
</section>
</AdminShell>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -72,10 +72,6 @@ export default function ProfilePage() {
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [status, setStatus] = useState<string | null>(null)
const [notifyEnabled, setNotifyEnabled] = useState(false)
const [notifyUrls, setNotifyUrls] = useState('')
const [notifyStatus, setNotifyStatus] = useState<string | null>(null)
const [notifySaving, setNotifySaving] = useState(false)
const [loading, setLoading] = useState(true)
useEffect(() => {
@@ -101,14 +97,6 @@ export default function ProfilePage() {
})
setStats(data?.stats ?? null)
setActivity(data?.activity ?? null)
const notifyResponse = await authFetch(`${baseUrl}/auth/notifications`)
if (notifyResponse.ok) {
const notifyData = await notifyResponse.json()
setNotifyEnabled(Boolean(notifyData?.enabled))
const urls = Array.isArray(notifyData?.urls) ? notifyData.urls : []
setNotifyUrls(urls.join('\n'))
}
} catch (err) {
console.error(err)
setStatus('Could not load your profile.')
@@ -149,59 +137,6 @@ export default function ProfilePage() {
}
}
const saveNotifications = async (event: React.FormEvent) => {
event.preventDefault()
setNotifyStatus(null)
setNotifySaving(true)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/auth/notifications`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
enabled: notifyEnabled,
urls: notifyUrls,
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Update failed')
}
setNotifyStatus('Notification settings saved.')
} catch (err) {
console.error(err)
const message =
err instanceof Error && err.message
? err.message.replace(/^\\{\"detail\":\"|\"\\}$/g, '')
: 'Could not save notification settings.'
setNotifyStatus(message)
} finally {
setNotifySaving(false)
}
}
const sendTest = async () => {
setNotifyStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/auth/notifications/test`, {
method: 'POST',
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Test failed')
}
setNotifyStatus('Test notification sent.')
} catch (err) {
console.error(err)
const message =
err instanceof Error && err.message
? err.message.replace(/^\\{\"detail\":\"|\"\\}$/g, '')
: 'Could not send test notification.'
setNotifyStatus(message)
}
}
if (loading) {
return <main className="card">Loading profile...</main>
}
@@ -287,42 +222,6 @@ export default function ProfilePage() {
</div>
</section>
</div>
<section className="profile-section">
<h2>Notifications</h2>
<div className="status-banner">
Add Apprise URLs to receive notifications (one URL per line).
</div>
<form onSubmit={saveNotifications} className="auth-form">
<label>
Enable notifications
<select
value={notifyEnabled ? 'true' : 'false'}
onChange={(event) => setNotifyEnabled(event.target.value === 'true')}
>
<option value="true">Enabled</option>
<option value="false">Disabled</option>
</select>
</label>
<label>
Apprise URLs
<textarea
rows={4}
placeholder="discord://token@webhook_id\nmailto://user:pass@server"
value={notifyUrls}
onChange={(event) => setNotifyUrls(event.target.value)}
/>
</label>
{notifyStatus && <div className="status-banner">{notifyStatus}</div>}
<div className="auth-actions">
<button type="submit" disabled={notifySaving}>
{notifySaving ? 'Saving...' : 'Save notifications'}
</button>
<button type="button" className="ghost-button" onClick={sendTest}>
Send test
</button>
</div>
</form>
</section>
{profile?.auth_provider !== 'local' ? (
<div className="status-banner">
Password changes are only available for local Magent accounts.

View File

@@ -22,13 +22,6 @@ const NAV_GROUPS = [
{ href: '/admin/cache', label: 'Cache Control' },
],
},
{
title: 'Notifications',
items: [
{ href: '/admin/notifications', label: 'Notifications' },
{ href: '/admin/apprise', label: 'Apprise' },
],
},
{
title: 'Admin',
items: [

View File

@@ -24,6 +24,7 @@ type AdminUser = {
auth_provider?: string | null
last_login_at?: string | null
is_blocked?: boolean
auto_search_enabled?: boolean
jellyseerr_user_id?: number | null
}
@@ -130,6 +131,28 @@ export default function UserDetailPage() {
}
}
const updateAutoSearchEnabled = async (enabled: boolean) => {
if (!user) return
try {
const baseUrl = getApiBase()
const response = await authFetch(
`${baseUrl}/admin/users/${encodeURIComponent(user.username)}/auto-search`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled }),
}
)
if (!response.ok) {
throw new Error('Update failed')
}
await loadUser()
} catch (err) {
console.error(err)
setError('Could not update auto search access.')
}
}
useEffect(() => {
if (!getToken()) {
router.push('/login')
@@ -159,68 +182,92 @@ export default function UserDetailPage() {
) : (
<>
<div className="user-detail-card">
<div className="user-detail-header">
<div>
<strong>{user.username}</strong>
<div className="user-detail-meta">
<span className="meta">Jellyseerr ID: {user.jellyseerr_user_id ?? user.id ?? 'Unknown'}</span>
<span className="meta">Role: {user.role}</span>
<span className="meta">Login type: {user.auth_provider || 'local'}</span>
<span className="meta">Last login: {formatDateTime(user.last_login_at)}</span>
<div className="user-detail-layout">
<div className="user-detail-identity">
<div className="user-detail-title-row">
<strong className="user-detail-name">{user.username}</strong>
<span className={`user-grid-pill ${user.is_blocked ? 'is-blocked' : ''}`}>
{user.is_blocked ? 'Blocked' : 'Active'}
</span>
</div>
<div className="user-detail-meta-pills">
<span className="user-detail-chip">
Jellyseerr ID: {user.jellyseerr_user_id ?? user.id ?? 'Unknown'}
</span>
<span className="user-detail-chip">Role: {user.role}</span>
<span className="user-detail-chip">Login type: {user.auth_provider || 'local'}</span>
<span className="user-detail-chip">Last login: {formatDateTime(user.last_login_at)}</span>
</div>
</div>
<div className="user-actions">
<label className="toggle">
<input
type="checkbox"
checked={user.role === 'admin'}
onChange={(event) => updateUserRole(event.target.checked ? 'admin' : 'user')}
/>
<span>Make admin</span>
</label>
<button
type="button"
className="ghost-button"
onClick={() => toggleUserBlock(!user.is_blocked)}
>
{user.is_blocked ? 'Allow access' : 'Block access'}
</button>
<div className="user-detail-controls">
<div className="user-detail-controls-title">User controls</div>
<div className="user-detail-actions">
<label className="toggle">
<input
type="checkbox"
checked={user.role === 'admin'}
onChange={(event) => updateUserRole(event.target.checked ? 'admin' : 'user')}
/>
<span>Make admin</span>
</label>
<label className="toggle">
<input
type="checkbox"
checked={Boolean(user.auto_search_enabled ?? true)}
disabled={user.role === 'admin'}
onChange={(event) => updateAutoSearchEnabled(event.target.checked)}
/>
<span>Allow auto search/download</span>
</label>
<button
type="button"
className="ghost-button"
onClick={() => toggleUserBlock(!user.is_blocked)}
>
{user.is_blocked ? 'Allow access' : 'Block access'}
</button>
</div>
{user.role === 'admin' && (
<div className="user-detail-helper">
Admins always have auto search/download access.
</div>
)}
</div>
</div>
<div className="user-detail-grid">
<div>
<div className="user-detail-stat">
<span className="label">Total</span>
<span className="value">{stats?.total ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Ready</span>
<span className="value">{stats?.ready ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Pending</span>
<span className="value">{stats?.pending ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Approved</span>
<span className="value">{stats?.approved ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Working</span>
<span className="value">{stats?.working ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Partial</span>
<span className="value">{stats?.partial ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">Declined</span>
<span className="value">{stats?.declined ?? 0}</span>
</div>
<div>
<div className="user-detail-stat">
<span className="label">In progress</span>
<span className="value">{stats?.in_progress ?? 0}</span>
</div>
<div>
<div className="user-detail-stat user-detail-stat--wide">
<span className="label">Last request</span>
<span className="value">{formatDateTime(stats?.last_request_at)}</span>
</div>

View File

@@ -13,6 +13,7 @@ type AdminUser = {
authProvider?: string | null
lastLoginAt?: string | null
isBlocked?: boolean
autoSearchEnabled?: boolean
stats?: UserStats
}
@@ -74,6 +75,7 @@ export default function UsersPage() {
const [jellyseerrSyncStatus, setJellyseerrSyncStatus] = useState<string | null>(null)
const [jellyseerrSyncBusy, setJellyseerrSyncBusy] = useState(false)
const [jellyseerrResyncBusy, setJellyseerrResyncBusy] = useState(false)
const [bulkAutoSearchBusy, setBulkAutoSearchBusy] = useState(false)
const loadUsers = async () => {
try {
@@ -100,6 +102,7 @@ export default function UsersPage() {
authProvider: user.auth_provider ?? 'local',
lastLoginAt: user.last_login_at ?? null,
isBlocked: Boolean(user.is_blocked),
autoSearchEnabled: Boolean(user.auto_search_enabled ?? true),
id: Number(user.id ?? 0),
stats: normalizeStats(user.stats ?? emptyStats),
}))
@@ -208,6 +211,33 @@ export default function UsersPage() {
}
}
const bulkUpdateAutoSearch = async (enabled: boolean) => {
setBulkAutoSearchBusy(true)
setJellyseerrSyncStatus(null)
try {
const baseUrl = getApiBase()
const response = await authFetch(`${baseUrl}/admin/users/auto-search/bulk`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled }),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text || 'Bulk update failed')
}
const data = await response.json()
setJellyseerrSyncStatus(
`${enabled ? 'Enabled' : 'Disabled'} auto search/download for ${data?.updated ?? 0} non-admin users.`
)
await loadUsers()
} catch (err) {
console.error(err)
setError('Could not update auto search/download for all users.')
} finally {
setBulkAutoSearchBusy(false)
}
}
useEffect(() => {
if (!getToken()) {
router.push('/login')
@@ -220,6 +250,9 @@ export default function UsersPage() {
return <main className="card">Loading users...</main>
}
const nonAdminUsers = users.filter((user) => user.role !== 'admin')
const autoSearchEnabledCount = nonAdminUsers.filter((user) => user.autoSearchEnabled !== false).length
return (
<AdminShell
title="Users"
@@ -241,6 +274,31 @@ export default function UsersPage() {
<section className="admin-section">
{error && <div className="error-banner">{error}</div>}
{jellyseerrSyncStatus && <div className="status-banner">{jellyseerrSyncStatus}</div>}
<div className="user-bulk-toolbar">
<div className="user-bulk-summary">
<strong>Auto search/download</strong>
<span>
{autoSearchEnabledCount} of {nonAdminUsers.length} non-admin users enabled
</span>
</div>
<div className="user-bulk-actions">
<button
type="button"
onClick={() => bulkUpdateAutoSearch(true)}
disabled={bulkAutoSearchBusy}
>
{bulkAutoSearchBusy ? 'Working...' : 'Enable for all users'}
</button>
<button
type="button"
className="ghost-button"
onClick={() => bulkUpdateAutoSearch(false)}
disabled={bulkAutoSearchBusy}
>
{bulkAutoSearchBusy ? 'Working...' : 'Disable for all users'}
</button>
</div>
</div>
{users.length === 0 ? (
<div className="status-banner">No users found yet.</div>
) : (
@@ -260,6 +318,11 @@ export default function UsersPage() {
{user.isBlocked ? 'Blocked' : 'Active'}
</span>
</div>
<div className="user-grid-subpills">
<span className={`user-grid-pill ${user.autoSearchEnabled === false ? 'is-disabled' : ''}`}>
Auto search {user.autoSearchEnabled === false ? 'Off' : 'On'}
</span>
</div>
<div className="user-grid-stats">
<div>
<span className="label">Total</span>