import json from dataclasses import dataclass from datetime import UTC, datetime from anydi import singleton from cachelib import BaseCache as Cache from fansifter_common.encrypter import Encrypter from preference_center.adapters.kafka import KafkaProducer from preference_center.config import Settings from preference_center.songwhip.exceptions import ( SongwhipFanDoubleOptInConsentIdCheckError, ) @dataclass(kw_only=True) class SongwhipFanDoubleOptInConsentConfirmRequest: fan_consent_id: str country: str @singleton class SongwhipFanDoubleOptInConsentConfirmHandler: cache_prefix: str = "songwhip_fan_consent_confirm" cache_timeout: int = 86400 def __init__( self, encrypter: Encrypter, kafka_producer: KafkaProducer, cache: Cache, settings: Settings, ) -> None: self.encrypter = encrypter self.kafka_producer = kafka_producer self.cache = cache self.settings = settings def handle(self, request: SongwhipFanDoubleOptInConsentConfirmRequest) -> None: try: fan_consent_id = self.encrypter.decrypt(request.fan_consent_id).decode() except Exception as exc: raise SongwhipFanDoubleOptInConsentIdCheckError from exc if self.cache.get(key=f"{self.cache_prefix}:{fan_consent_id}"): return self.cache.add( key=f"{self.cache_prefix}:{fan_consent_id}", value=fan_consent_id, timeout=self.cache_timeout, ) self.kafka_producer.publish( topic=self.settings.kafka_topic_songwhip_fan_consent_double_opt_in, value=json.dumps( { "timestamp": datetime.now(UTC).isoformat(), "country": request.country, }, ), key=fan_consent_id, )