from dataclasses import asdict from typing import List, Dict, Any from apollo_utils.core.utils.to_object import FromDictObject from charts_push_messages.constants import TTL, PUSH_MESSAGE_TOPIC from charts_push_messages.utils.push_message import PushMessageMetaNested, PushMessageDataNested, PushMessage class PushMessageFactory(FromDictObject): def _get_message_id(self): return self.data.message_id def _get_devices(self): return self.data.recipient.devices def _get_meta(self): return self.meta def _get_content(self): return self.data.content def _get_push_nested_meta(self): meta = self._get_meta() return PushMessageMetaNested( dsp=meta.dsp, country_code=meta.country_code, type=meta.type, subject=meta.subject ) def _get_artists(self): return self.data.content.track.artists def _get_artists_as_string(self): """As we have a list of artists we need to handle situation when there are more than one artist for the track""" artists = self._get_artists() artists = " & ".join(artist.name for artist in artists) if len(artists) > 1 else artists[0].name return artists def _get_topic(self): return PUSH_MESSAGE_TOPIC[self.meta.type] def _get_change(self): result = None if self.meta.type == "starred_track_top_chart_move": result = self.data.content.current_position - self.data.content.previous_position return result def _get_push_nested_data(self): meta = self._get_meta() content = self._get_content() return PushMessageDataNested( artist_name=self._get_artists_as_string(), isrc=content.track.isrc, track_id=content.track.id, track_name=content.track.name, topic=self._get_topic(), position=self.data.content.current_position or self.data.content.previous_position, vendor=meta.dsp, country_code=meta.country_code, change=self._get_change(), chart_name=content.chart.name, ) def _create_push_message(self, device: FromDictObject) -> Dict[str, Any]: content = self._get_content() push_message = PushMessage( ttl=TTL, event_id=self.event_id, account_id=self.account_id, device_id=device.id, message_id=self.message_id, meta=self._get_push_nested_meta(), to=device.expo_token, title=content.title, body=content.body, data=self._get_push_nested_data() ) return asdict(push_message) def get_push_messages(self) -> List[Dict[str, Any]]: result = [] for item in self._get_devices(): result.append(self._create_push_message(item)) return result def get_push_messages(feed_messages: List[Dict[str, Any]]): result = [] for message in feed_messages: result += PushMessageFactory(**message).get_push_messages() return result