|
| 1 | +import json |
| 2 | + |
| 3 | +from uid2_client import IdentityType, normalize_email_string, get_base64_encoded_hash, is_phone_number_normalized |
| 4 | + |
| 5 | + |
| 6 | +class IdentityMapInput: |
| 7 | + """input for IdentityMapClient, such as email addresses or phone numbers""" |
| 8 | + |
| 9 | + def __init__(self, identity_type, emails_or_phones, already_hashed): |
| 10 | + self.hashed_dii_to_raw_diis = {} |
| 11 | + self.hashed_normalized_emails = [] |
| 12 | + self.hashed_normalized_phones = [] |
| 13 | + if identity_type == IdentityType.Email: |
| 14 | + for email in emails_or_phones: |
| 15 | + if already_hashed: |
| 16 | + self.hashed_normalized_emails.append(email) |
| 17 | + else: |
| 18 | + normalized_email = normalize_email_string(email) |
| 19 | + if normalized_email is None: |
| 20 | + raise ValueError("invalid email address") |
| 21 | + hashed_normalized_email = get_base64_encoded_hash(normalized_email) |
| 22 | + self.hashed_normalized_emails.append(hashed_normalized_email) |
| 23 | + self._add_hashed_to_raw_dii_mapping(hashed_normalized_email, email) |
| 24 | + else: # phone |
| 25 | + for phone in emails_or_phones: |
| 26 | + if already_hashed: |
| 27 | + self.hashed_normalized_phones.append(phone) |
| 28 | + else: |
| 29 | + if not is_phone_number_normalized(phone): |
| 30 | + raise ValueError("phone number is not normalized: " + phone) |
| 31 | + hashed_normalized_phone = get_base64_encoded_hash(phone) |
| 32 | + self._add_hashed_to_raw_dii_mapping(hashed_normalized_phone, phone) |
| 33 | + self.hashed_normalized_phones.append(hashed_normalized_phone) |
| 34 | + |
| 35 | + @staticmethod |
| 36 | + def from_emails(emails): |
| 37 | + return IdentityMapInput(IdentityType.Email, emails, False) |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def from_phones(phones): |
| 41 | + return IdentityMapInput(IdentityType.Phone, phones, False) |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def from_hashed_emails(hashed_emails): |
| 45 | + return IdentityMapInput(IdentityType.Email, hashed_emails, True) |
| 46 | + |
| 47 | + @staticmethod |
| 48 | + def from_hashed_phones(hashed_phones): |
| 49 | + return IdentityMapInput(IdentityType.Phone, hashed_phones, True) |
| 50 | + |
| 51 | + def _add_hashed_to_raw_dii_mapping(self, hashed_dii, raw_dii): |
| 52 | + self.hashed_dii_to_raw_diis.setdefault(hashed_dii, []).append(raw_dii) |
| 53 | + |
| 54 | + def get_identity_map_input_as_json_string(self): |
| 55 | + json_object = { |
| 56 | + "email_hash": self.hashed_normalized_emails, |
| 57 | + "phone_hash": self.hashed_normalized_phones |
| 58 | + } |
| 59 | + return json.dumps({k: v for k, v in json_object.items() if v is not None and len(v) > 0}) |
0 commit comments