"""Set custom markets to playlists.""" import csv from http.client import HTTPSConnection import json from typing import Any, Dict import config def make_filter_admin_request( method: str, relative_uri: str, additional_headers: dict or None = None, body: dict or None = None) -> Any: """Make filter admin API request. Args: method (str): HTTP method. relative_uri (str): Relative URI. additional_headers (dict or None): HTTP headers. body (dict or None): HTTP body. Returns: Any: Response body. """ connection = HTTPSConnection(config.FILTER_ADMIN_HOST) headers = {'authorization': config.FILTER_ADMIN_KEY} if body: headers.update({'Content-type': 'application/json'}) if additional_headers: headers.update(additional_headers) connection.request(method, relative_uri, body=json.dumps(body) if body else None, headers=headers) response = connection.getresponse() data = json.loads(response.read()) return data def get_markets() -> Dict[str, str]: """Get market name to code mapping. Returns: Dict[str, str]: Market name to code mapping. """ data = make_filter_admin_request('GET', '/markets') return {m['name'].lower(): m['spotifyRegionCode'] for m in data} def set_playlist_market(playlist_id: str, market_code: str): """Set custom market to playlist. Args: playlist_id (str): Playlist ID. market_code (str): Market code. """ return make_filter_admin_request( 'PUT', '/playlistmarket', body={'playlistId': playlist_id, 'musicServiceId': 1, 'marketCode': market_code}) def read_playlist_market() -> Dict[str, str]: """Read csv file with playlist ID and custom market to set. Returns: Dict[str, str]: Playlist ID to custom market mapping. """ with open(config.PLAYLIST_MARKET_FILE_PATH) as csv_file: csv_reader = csv.reader(csv_file) return {row[0].replace('spotify:track:', ''): row[1].lower() for row in csv_reader} def set_markets(): """Main func. """ market_mapping = get_markets() if config.GET_MARKET_CODE_BY_NAME else {} playlist_market_mapping = read_playlist_market() incorrect_markets = [] for playlist_id, market in playlist_market_mapping.items(): if len(market) != 2: if config.GET_MARKET_CODE_BY_NAME and market in market_mapping: market = market_mapping[market] else: incorrect_markets.append((playlist_id, market)) continue print(f'Setting {market} for {playlist_id}') result = set_playlist_market(playlist_id, market) if 'message' in result: print(result) break print(incorrect_markets) if __name__ == '__main__': set_markets()