diff --git a/core/clients/whatsapp.py b/core/clients/whatsapp.py index 1d6eb28..1ff58ee 100644 --- a/core/clients/whatsapp.py +++ b/core/clients/whatsapp.py @@ -749,6 +749,68 @@ class WhatsAppClient(ClientBase): "SELECT name FROM sqlite_master WHERE type='table'" ).fetchall() table_names = [str(row[0]) for row in table_rows if row and row[0]] + # Prefer the canonical contacts table when available. + if "whatsmeow_contacts" in table_names: + own_ids = set() + for value in ( + transport.get_runtime_state(self.service).get("accounts") or [] + ): + base = str(value or "").strip().split("@", 1)[0] + base = base.split(":", 1)[0] + if base: + own_ids.add(base.lower()) + try: + for row in cur.execute( + 'SELECT DISTINCT "our_jid" FROM "whatsmeow_contacts"' + ).fetchall(): + base = str((row or [None])[0] or "").strip().split("@", 1)[0] + base = base.split(":", 1)[0] + if base: + own_ids.add(base.lower()) + except Exception: + pass + + out = [] + seen = set() + try: + rows = cur.execute( + 'SELECT "their_jid", "first_name", "full_name", "push_name", "business_name" ' + 'FROM "whatsmeow_contacts" LIMIT 5000' + ).fetchall() + except Exception: + rows = [] + for their_jid, first_name, full_name, push_name, business_name in rows: + jid_value = str(their_jid or "").strip() + if "@s.whatsapp.net" not in jid_value and "@lid" not in jid_value: + continue + identifier = jid_value.split("@", 1)[0].strip().split(":", 1)[0] + if not identifier: + continue + if identifier.lower() in own_ids: + continue + if identifier in seen: + continue + seen.add(identifier) + display_name = ( + str(push_name or "").strip() + or str(full_name or "").strip() + or str(business_name or "").strip() + or str(first_name or "").strip() + ) + out.append( + { + "identifier": identifier, + "jid": jid_value, + "name": display_name, + "chat": "", + "seen_at": int(time.time()), + } + ) + if len(out) >= 500: + break + if out: + return out, "sqlite_contacts" + account_keys = { str(value or "").strip().split("@", 1)[0].lower() for value in (