from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse from fansifter_common.legal_info.constants import ( DEFAULT_COUNTRY_CODE, EXTRA_COUNTRY_MAPPINGS, PRIVACY_LINK_TEMPLATE, RESTRICTED_DATE_OF_BIRTH_COUNTRIES, ) from fansifter_common.legal_info.loaders import get_legal_entities, get_privacy_links from fansifter_common.legal_info.types import LegalEntity, PrivacyLink class LegalInfoService: default_country_code = DEFAULT_COUNTRY_CODE extra_country_mapping = EXTRA_COUNTRY_MAPPINGS privacy_link_template = PRIVACY_LINK_TEMPLATE def __init__( self, restricted_date_of_birth_countries: list[str] | None = None, privacy_links: dict[str, dict[str, list[PrivacyLink]]] | None = None, legal_entities: dict[str, LegalEntity] | None = None, ) -> None: self.restricted_date_of_birth_countries = ( restricted_date_of_birth_countries or RESTRICTED_DATE_OF_BIRTH_COUNTRIES ) self.privacy_links = privacy_links or get_privacy_links() self.legal_entities = legal_entities or get_legal_entities() def _get_country_code(self, country_code: str) -> str: """Get the country code from the extra country mapping.""" return self.extra_country_mapping.get(country_code, country_code) def is_date_of_birth_allowed(self, country_code: str) -> bool: """Check if date of birth is allowed for the given country code.""" return country_code not in self.restricted_date_of_birth_countries @staticmethod def _add_url_utm_source(url: str, utm_source: str) -> str: """Add utm_source query parameter to the given url.""" url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query["utm_source"] = utm_source url_parts[4] = urlencode(query) return urlunparse(url_parts) def get_privacy_links(self, country_code: str) -> dict[str, list[PrivacyLink]]: """Get the privacy links for the given country code.""" country_code = self._get_country_code(country_code) if country_code not in self.privacy_links: return self.privacy_links[self.default_country_code] return self.privacy_links[country_code] def get_legal_entity(self, country_code: str) -> LegalEntity: """Get the legal entity for the given country code.""" country_code = self._get_country_code(country_code) if country_code not in self.legal_entities: return self.legal_entities[self.default_country_code] return self.legal_entities[country_code] def prepare_privacy_links_for_country( self, country_code: str, utm_source: str | None = None ) -> str: privacy_links_languages = self.get_privacy_links(country_code) prepared_privacy_links = [] for privacy_links in privacy_links_languages.values(): privacy_links_list = [] for privacy_link in privacy_links: privacy_link_url = privacy_link.url if utm_source: privacy_link_url = self._add_url_utm_source( privacy_link_url, utm_source ) privacy_links_list.append( self.privacy_link_template.format( privacy_link=privacy_link_url, privacy_title=privacy_link.name ) ) prepared_privacy_links.append(" | ".join(privacy_links_list)) return "
".join(prepared_privacy_links) service = LegalInfoService()