From 41a762d6a6f02f0733cd8c770ddc02e5846e3273 Mon Sep 17 00:00:00 2001 From: Brad Stein Date: Thu, 8 Jan 2026 12:12:08 -0300 Subject: [PATCH] comms: update numeric guest rename logic --- services/comms/guest-name-job.yaml | 56 ++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/services/comms/guest-name-job.yaml b/services/comms/guest-name-job.yaml index 44d3090..6179967 100644 --- a/services/comms/guest-name-job.yaml +++ b/services/comms/guest-name-job.yaml @@ -257,8 +257,9 @@ spec: return not display or display.isdigit() or display.startswith("guest-") def db_rename_numeric(existing_names): - user_ids = [] - profiles = {} + profile_rows = [] + profile_index = {} + users = [] conn = psycopg2.connect( host=os.environ["PGHOST"], port=int(os.environ["PGPORT"]), @@ -270,19 +271,12 @@ spec: with conn: with conn.cursor() as cur: cur.execute( - "SELECT name FROM users WHERE name ~ %s", + "SELECT user_id, full_user_id, displayname FROM profiles WHERE full_user_id ~ %s", (f"^@\\d+:{SERVER_NAME}$",), ) - user_ids = [row[0] for row in cur.fetchall()] - if not user_ids: - return - cur.execute( - "SELECT user_id, displayname FROM profiles WHERE user_id = ANY(%s)", - (user_ids,), - ) - profiles = {row[0]: row[1] for row in cur.fetchall()} - for user_id in user_ids: - display = profiles.get(user_id) + profile_rows = cur.fetchall() + profile_index = {row[1]: row for row in profile_rows} + for user_id, full_user_id, display in profile_rows: if display and not needs_rename_display(display): continue new = None @@ -295,8 +289,40 @@ spec: if not new: continue cur.execute( - "INSERT INTO profiles (user_id, displayname, full_user_id) VALUES (%s, %s, %s) ON CONFLICT (user_id) DO UPDATE SET displayname = EXCLUDED.displayname", - (user_id, new, user_id), + "UPDATE profiles SET displayname = %s WHERE full_user_id = %s", + (new, full_user_id), + ) + + cur.execute( + "SELECT name FROM users WHERE name ~ %s", + (f"^@\\d+:{SERVER_NAME}$",), + ) + users = [row[0] for row in cur.fetchall()] + if not users: + return + cur.execute( + "SELECT user_id, full_user_id FROM profiles WHERE full_user_id = ANY(%s)", + (users,), + ) + for existing_full in cur.fetchall(): + profile_index.setdefault(existing_full[1], existing_full) + + for full_user_id in users: + if full_user_id in profile_index: + continue + localpart = full_user_id.split(":", 1)[0].lstrip("@") + new = None + for _ in range(30): + candidate = f"{random.choice(ADJ)}-{random.choice(NOUN)}" + if candidate not in existing_names: + new = candidate + existing_names.add(candidate) + break + if not new: + continue + cur.execute( + "INSERT INTO profiles (user_id, displayname, full_user_id) VALUES (%s, %s, %s)", + (localpart, new, full_user_id), ) finally: conn.close()