from apollo_utils.core.constants.dsp import DSP from apollo_utils.core.constants.market import Market from datetime import date from typing import List from server.client import services from server.constants.artists import TracksTopInclude from server.constants.common import SortOrder from server.domains.artists.tracks import fill_meta_data async def get_artist_top_tracks( gras_artist_id: str, start_date: date, end_date: date, dsp_list: List[str], country_code_list: List[str], limit: int, meta_country_code: str, include_list: List[TracksTopInclude], ) -> List[dict]: """Get top tracks by streams count for an artist. Args: gras_artist_id: GRAS artist ID. start_date: Interval date from. end_date: Interval date to. dsp_list: Streams DSP codes. country_code_list: Streams country codes. limit: Top count. meta_country_code: Metadata country code. include_list: Include additional data. Returns: Top tracks list. """ # Ignore streams country codes as there is no possibility to get top tracks by streams sum for all country codes, # but not for each separately. TODO: need to try to work with random country code list. country_code_list = [Market.WORLDWIDE] result = await services.dsp.get_streams( artist_id=gras_artist_id, start_date=start_date, end_date=end_date, dsp=dsp_list, country_code=country_code_list, agg_by="isrc", sort_by="streams", sort_order=SortOrder.DESC.value, limit=limit, request_per_dsp=False, ) if not result or not include_list: return result result_map = {i["isrc"]: i for i in result} response = await services.vendor.get_tracks(DSP.SPOTIFY, isrc=list(result_map.keys()), market=meta_country_code) found_isrc_list = fill_meta_data( result_map, response, include_list, lambda i: i.get("external_ids", {}).get("isrc"), lambda i: i.get("name") ) missing_isrc_list = list(set(result_map.keys()) - set(found_isrc_list)) if missing_isrc_list: response = await services.vendor.get_tracks(DSP.APPLE, isrc=missing_isrc_list, market=meta_country_code) fill_meta_data( result_map, response, include_list, lambda i: i.get("attributes", {}).get("isrc"), lambda i: i.get("attributes", {}).get("name"), ) return result