from typing import List, Optional from artists.schemas import LabelArtistResponse from external_api.base.analytics_models import ArtistsQuery from shared.schemas import ArtistSchema, ArtistImageSchema from external_api.base.clients.delphi_client import DelphiClient, DelphiArtistModel from external_api.base.clients.client_factory import ApiClientFactory from services.artists_repository import ArtistsRepository class ArtistsService: artists_repository: ArtistsRepository delphi_client: DelphiClient def __init__( self, artists_repository: ArtistsRepository = ArtistsRepository(), delphi_client: DelphiClient = ApiClientFactory.delphi_client(), ): self.artists_repository = artists_repository self.delphi_client = delphi_client async def get_artists_by_name( self, name: Optional[str], limit: int, offset: Optional[int] = None ) -> List[ArtistSchema]: page = offset // limit if offset else None query = ArtistsQuery(query=name, limit=limit, page=page) artists = await self.delphi_client.search_for_artists(query) artist_ids = [artist.artist_id for artist in artists.items] artist_is_unknown_mapping = self.__get_artist_is_unknown_mapping(artist_ids) return [ self.__map_artist( artist, artist_is_unknown_mapping.get(artist.artist_id, False) ) for artist in artists.items ] async def get_artists_by_name_count(self, name: Optional[str], limit: int): query = ArtistsQuery(query=name, limit=limit) count = await self.delphi_client.get_artists_search_count(query) return count.count async def get_artist_by_id(self, artist_external_id: str) -> ArtistSchema: artist = await self.delphi_client.get_artist_details(artist_external_id) decibel_artist = self.__map_artist(artist, self.__artist_is_unknown(artist_external_id)) self.artists_repository.create_artist(decibel_artist) return decibel_artist def __get_artist_is_unknown_mapping(self, external_ids: List[str]): artists_is_unknown = self.artists_repository.get_artists_is_unknown(external_ids) return {artist.external_id: artist.is_unknown for artist in artists_is_unknown} def __artist_is_unknown(self, artist_external_id: str) -> bool: artist = self.artists_repository.get_artist_by_external_id(artist_external_id) is_unknown = False if artist is not None: is_unknown = artist.is_unknown return is_unknown def __map_artist(self, artist: DelphiArtistModel, artist_is_unknown: bool) -> ArtistSchema: artist_schema = ArtistSchema(id=artist.artist_id, name=artist.full_name, isUnknown=artist_is_unknown) if artist.image: artist_schema.image = ArtistImageSchema(artist.image.uri, artist.image.width, artist.image.height) return artist_schema def get_label_artists(self, label_id): artists = self.artists_repository.get_label_artists(label_id) return [LabelArtistResponse(artist) for artist in artists]