Unify user management and add reviewed identity repairs
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
"""Admin-reviewed account links. Live IDs are authoritative; names only suggest candidates."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
import httpx
|
||||
from collections import defaultdict
|
||||
from contextlib import closing
|
||||
from datetime import datetime, timezone
|
||||
@@ -116,8 +119,17 @@ async def seerr_directory(runtime):
|
||||
return {"state": "unavailable", "users": []}
|
||||
|
||||
|
||||
def build_report(local, jellyfin, seerr, jellystat, runtime, selections=None):
|
||||
def build_report(local, jellyfin, seerr, jellystat, runtime, selections=None, repair=False):
|
||||
original = local
|
||||
selections = selections or {}
|
||||
if repair:
|
||||
local = copy.deepcopy(local)
|
||||
for user in local['users']:
|
||||
if user['id'] in selections:
|
||||
user['jellyseerr_user_id'] = None
|
||||
local['links'] = [link for link in local['links'] if not (
|
||||
link['local_user_id'] in selections and link['source'] == source_key(runtime.jellyfin_base_url))]
|
||||
local['confirmations'] = [item for item in local['confirmations'] if item['local_user_id'] not in selections]
|
||||
if any(user_id not in {user['id'] for user in local['users']} for user_id in selections):
|
||||
raise HTTPException(404, "This Magent account no longer exists. Run the check again.")
|
||||
jf_by_id = {row["id"]: row for row in jellyfin["users"]}
|
||||
@@ -158,6 +170,10 @@ def build_report(local, jellyfin, seerr, jellystat, runtime, selections=None):
|
||||
candidate, basis = stored_seerr["jellyfin_id"], "stored_seerr_id"
|
||||
elif user["auth_provider"] == "jellyfin" and len(by_name) == 1:
|
||||
candidate, basis = by_name[0], "suggested_username"
|
||||
if repair and user['id'] in selections and any(
|
||||
item['local_user_id'] == user['id'] and item['jellyfin_server_id'] != jellyfin.get('server_id')
|
||||
for item in original['confirmations']):
|
||||
issues.append('The Jellyfin server changed. A server migration requires separate review.')
|
||||
if user["id"] in selections:
|
||||
chosen = selections[user["id"]]
|
||||
if saved and chosen != saved["jellyfin_user_id"]:
|
||||
@@ -225,16 +241,16 @@ def build_report(local, jellyfin, seerr, jellystat, runtime, selections=None):
|
||||
"not_checked" if not jellystat else
|
||||
"unavailable" if any(r["state"] == "unavailable" for r in jellystat.values()) else "available"}
|
||||
report = {"server_id": jellyfin.get("server_id"), "services": services, "rows": rows, "upstream": upstream,
|
||||
"jellyfin_users": jellyfin["users"],
|
||||
"jellyfin_users": jellyfin["users"], "seerr_users": seerr["users"],
|
||||
"counts": {"magent": len(rows), "jellyfin": len(jellyfin["users"]), "seerr": len(seerr["users"]),
|
||||
"jellystat_checked": sum(r["state"] in {"matched", "missing"} for r in jellystat.values()),
|
||||
**{state: sum(row["state"] == state for row in rows) for state in ("ready", "confirmed", "conflict", "unlinked", "unavailable")}}}
|
||||
report["revision"] = digest([report, digest(local), config_digest(runtime)])
|
||||
report["revision"] = digest([report, digest(original), config_digest(runtime), repair])
|
||||
report["checked_at"] = datetime.now(timezone.utc).isoformat()
|
||||
return report
|
||||
|
||||
|
||||
async def review_identities(selections=None):
|
||||
async def review_identities(selections=None, repair=False):
|
||||
runtime = await asyncio.to_thread(get_runtime_settings)
|
||||
local, jf, seerr = await asyncio.gather(asyncio.to_thread(read_snapshot), jellyfin_directory(runtime), seerr_directory(runtime))
|
||||
if len(local["users"]) > MAX_USERS:
|
||||
@@ -247,10 +263,10 @@ async def review_identities(selections=None):
|
||||
raise HTTPException(422, "There are too many upstream IDs for one identity check.")
|
||||
stats_client = JellystatClient(runtime.jellystat_base_url, runtime.jellystat_api_key)
|
||||
js = await stats_client.check_user_ids(sorted(ids)) if stats_client.configured() else {key: {"state": "not_configured"} for key in ids}
|
||||
return build_report(local, jf, seerr, js, runtime, selections), local, runtime
|
||||
return build_report(local, jf, seerr, js, runtime, selections, repair), local, runtime
|
||||
|
||||
|
||||
def save_confirmations(report, local, runtime, user_ids, admin):
|
||||
def save_confirmations(report, local, runtime, user_ids, admin, repair=False):
|
||||
rows = {row["user"]["id"]: row for row in report["rows"]}
|
||||
if any(user_id not in rows or not rows[user_id]["can_confirm"] for user_id in user_ids):
|
||||
raise HTTPException(409, "Some selected accounts cannot be confirmed. Run the check again and review the conflicts.")
|
||||
@@ -274,6 +290,20 @@ def save_confirmations(report, local, runtime, user_ids, admin):
|
||||
jellyfin_source=excluded.jellyfin_source,confirmed_at=excluded.confirmed_at,confirmed_by=excluded.confirmed_by""",
|
||||
(user_id, report["server_id"], jf_id, source_key(runtime.jellyfin_base_url), source_key(runtime.jellyseerr_base_url),
|
||||
seerr_id, now, admin["username"]))
|
||||
if repair:
|
||||
before_user = next(user for user in local['users'] if user['id'] == user_id)
|
||||
before = {'seerr_user_id': before_user['jellyseerr_user_id'],
|
||||
'links': [link for link in local['links'] if link['local_user_id'] == user_id],
|
||||
'confirmation': next((item for item in local['confirmations'] if item['local_user_id'] == user_id), None)}
|
||||
conn.execute("""UPDATE user_identity_confirmations SET jellyfin_server_id=?,jellyfin_user_id=?,
|
||||
jellyfin_source=?,seerr_source=?,seerr_user_id=? WHERE local_user_id=?""",
|
||||
(report['server_id'], jf_id, source_key(runtime.jellyfin_base_url),
|
||||
source_key(runtime.jellyseerr_base_url), seerr_id, user_id))
|
||||
conn.execute("""INSERT INTO user_identity_repairs
|
||||
(local_user_id,before_json,after_json,repaired_at,repaired_by) VALUES (?,?,?,?,?)""",
|
||||
(user_id, json.dumps(before, sort_keys=True), json.dumps({
|
||||
'jellyfin_server_id': report['server_id'], 'jellyfin_user_id': jf_id,
|
||||
'seerr_user_id': seerr_id}, sort_keys=True), now, admin['username']))
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise HTTPException(409, "An identity is already linked to another account. Run the check again.") from exc
|
||||
return {"confirmed": len(user_ids), "confirmed_at": now}
|
||||
@@ -294,3 +324,46 @@ async def resolve_identity(user_id, jellyfin_user_id, revision=None, admin=None)
|
||||
return await asyncio.to_thread(save_confirmations, report, local, runtime, [user_id], admin)
|
||||
return {"revision": report["revision"], "server_id": report["server_id"],
|
||||
"row": next(row for row in report["rows"] if row["user"]["id"] == user_id)}
|
||||
|
||||
|
||||
async def repair_identity(user_id, jellyfin_user_id, revision=None, admin=None, create_seerr=False):
|
||||
report, local, runtime = await review_identities({user_id: jellyfin_user_id}, repair=True)
|
||||
row = next(row for row in report['rows'] if row['user']['id'] == user_id)
|
||||
importing = bool(create_seerr and row['state'] == 'unlinked' and row['jellyfin']
|
||||
and not row['seerr'] and row['jellystat']['state'] == 'matched'
|
||||
and report['services']['seerr'] == 'available')
|
||||
if importing and any(name_key(account['name']) == name_key(row['jellyfin']['name'])
|
||||
for account in report['seerr_users']):
|
||||
importing = False
|
||||
row['issues'].append('A Seerr account already has this name. Review its existing link before importing.')
|
||||
report['revision'] = digest([report['revision'], create_seerr])
|
||||
if revision is not None:
|
||||
if report['revision'] != revision:
|
||||
raise HTTPException(409, 'The repair preview changed. Check the selected account again.')
|
||||
if importing:
|
||||
if digest(await asyncio.to_thread(read_snapshot)) != digest(local) or config_digest(get_runtime_settings()) != config_digest(runtime):
|
||||
raise HTTPException(409, 'Accounts or settings changed. Preview the repair again.')
|
||||
client = JellyseerrClient(runtime.jellyseerr_base_url, runtime.jellyseerr_api_key)
|
||||
try:
|
||||
await client.post('/api/v1/user/import-from-jellyfin', payload={'jellyfinUserIds': [jellyfin_user_id]})
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
raise HTTPException(502, 'The Seerr import could not be verified. Run a fresh check before trying again; an account may already have been imported.') from exc
|
||||
# Upstream and SQLite cannot share a transaction. Reconcile using live IDs;
|
||||
# never delete an imported account if the local save is blocked or interrupted.
|
||||
refreshed, _, fresh_runtime = await review_identities({user_id: jellyfin_user_id}, repair=True)
|
||||
if config_digest(fresh_runtime) != config_digest(runtime):
|
||||
raise HTTPException(409, 'Seerr import completed but settings changed. Check accounts again before saving Magent links.')
|
||||
try:
|
||||
return await asyncio.to_thread(save_confirmations, refreshed, local, runtime, [user_id], admin, True)
|
||||
except HTTPException as exc:
|
||||
raise HTTPException(409, 'Seerr import completed, but Magent links could not be saved. Run another check to review the imported account. No account was deleted.') from exc
|
||||
return await asyncio.to_thread(save_confirmations, report, local, runtime, [user_id], admin, True)
|
||||
before = next(user for user in local['users'] if user['id'] == user_id)
|
||||
linked = next((link['jellyfin_user_id'] for link in local['links'] if link['local_user_id'] == user_id
|
||||
and link['source'] == source_key(runtime.jellyfin_base_url)), None)
|
||||
row['can_confirm'] = row['can_confirm'] or importing
|
||||
return {'revision': report['revision'], 'server_id': report['server_id'], 'row': row,
|
||||
'action': 'import_seerr' if importing else 'repair_magent',
|
||||
'before': {'jellyfin_user_id': linked, 'seerr_user_id': before['jellyseerr_user_id']},
|
||||
'seerr_users': report['seerr_users'],
|
||||
'scope': ('Import this single Jellyfin account into Seerr, then verify and save Magent links. Existing Seerr accounts stay unchanged.' if importing else 'Repair Magent links only. Jellyfin and Jellystat IDs and Seerr accounts stay unchanged.')}
|
||||
|
||||
Reference in New Issue
Block a user