import asyncio from apollo_utils.core.constants.dsp import DSP from typing import Dict, List, Optional, Tuple, Union from server import config as config from server.cache.utils import cached from server.client import services @cached(ttl=config.AMAZON_PLAYLIST_ID_COUNTRY_CODES_TTL, noself=True) async def get_amazon_playlist_str_id_country_code_pairs(playlist_id: str) -> List[Tuple[str, str]]: """Get dict of amazon str playlist_id to country_code mappings by provided int_id Args: playlist_id: amazon integer playlist_id with prefix -> amazon_120 """ playlists = await services.dsp.get_track_positions_playlists( playlist_id=playlist_id, dsp=DSP.AMAZON.value, include=["playlists"] ) playlist_id_country_code_pairs = list( set((pl["playlist"]["amazon_playlist_id"], pl["playlist"]["country_code"]) for pl in playlists) ) return playlist_id_country_code_pairs async def get_amazon_playlist_country_codes( playlist_id: str, ) -> List[str]: """Get amazon playlist id list of countries by provided int_id with prefix Args: playlist_id: Amazon int playlist id with prefix -> amazon_120 Returns: List of string country_code(s) """ delphi_data = await get_amazon_playlist_str_id_country_code_pairs( playlist_id=playlist_id, ) return [item[1] for item in delphi_data] async def get_amazon_playlist_available_markets( playlist_id: str, sort_by: Optional[str] = None ) -> List[Dict[str, Union[int, str]]]: """Get amazon playlist available markets Args: playlist_id: Amazon int playlist id with prefix -> amazon_120 sort_by: Field name to sort items by Returns: List of Dict with market(s) information ex: [ { "name": "Brazil", "full_name": "Brazil", "id": 19, "code": "br" }, ... ] """ delphi_markets, apollo_markets = await asyncio.gather( get_amazon_playlist_country_codes( playlist_id=playlist_id, ), services.apollo.get_markets(extended=True), ) merged_markets = [i for i in apollo_markets if i["code"] in delphi_markets] if sort_by: return sorted(merged_markets, key=lambda d: sort_by) return merged_markets