From 0f3083d0602abbc67ef457bfeddff3f3f74f2ccc Mon Sep 17 00:00:00 2001 From: jasonMPM Date: Wed, 4 Mar 2026 22:16:36 -0600 Subject: [PATCH] Update app.py --- app.py | 64 ++++++++++++++++++++++++++++++---------------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/app.py b/app.py index 051bc88..05c7a0c 100644 --- a/app.py +++ b/app.py @@ -30,21 +30,25 @@ def get_db(): def init_db(): with get_db() as db: - db.execute(""" + db.execute( + """ CREATE TABLE IF NOT EXISTS badge_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id TEXT NOT NULL, ts TEXT NOT NULL, date TEXT NOT NULL ) - """) - db.execute(""" + """ + ) + db.execute( + """ CREATE TABLE IF NOT EXISTS user_cache ( actor_id TEXT PRIMARY KEY, full_name TEXT NOT NULL, updated_at TEXT NOT NULL ) - """) + """ + ) db.commit() @@ -62,35 +66,33 @@ def sync_unifi_users(): users = r.json().get("data", []) with get_db() as db: for u in users: - # Prefer the same ID used in webhooks (identity ID) - actor_id = ( - u.get("id") or - u.get("identity_id") or - u.get("user_id") - ) + # Prefer the same ID used in webhooks (identity ID / id) + actor_id = ( + u.get("id") + or u.get("identity_id") + or u.get("user_id") + ) + if not actor_id: + continue # skip malformed entries - if not actor_id: - continue # skip malformed entries - - full_name = (u.get("full_name") or "").strip() - if not full_name: - full_name = f"{u.get('first_name','')} {u.get('last_name','')}".strip() - - db.execute( - """ - INSERT INTO user_cache (actor_id, full_name, updated_at) - VALUES (?, ?, ?) - ON CONFLICT(actor_id) DO UPDATE SET - full_name = excluded.full_name, - updated_at = excluded.updated_at - """, - ( - actor_id, - full_name or f"User {actor_id[:8]}", - datetime.utcnow().isoformat(), - ), - ) + full_name = (u.get("full_name") or "").strip() + if not full_name: + full_name = f"{u.get('first_name','')} {u.get('last_name','')}".strip() + db.execute( + """ + INSERT INTO user_cache (actor_id, full_name, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(actor_id) DO UPDATE SET + full_name = excluded.full_name, + updated_at = excluded.updated_at + """, + ( + actor_id, + full_name or f"User {actor_id[:8]}", + datetime.utcnow().isoformat(), + ), + ) db.commit() log.info("Synced %d users from UniFi Access", len(users)) except Exception as e: