"""Logic layer for the work with Apple Music data.""" from owsresponse import response from participant.models.service import apple_music as apple_music_model def artist_search(query, limit, offset, localization): """Search artists by passed query. Args: query (str): Search term. limit (int): Max number of matched artists. offset (int): Offset from the beginning of the result. localization (str): Localization for the search. Returns: List: List of matched artists. """ result = apple_music_model.search_artist(query, limit, offset, localization) return response.Response(_format_search_response(result)) def get_artist_by_id(artist_id): """Search artist by ID. Args: artist_id (str): Artist ID to search. Returns: dict: Matched artist. """ result = apple_music_model.get_artist_by_id(artist_id) return response.Response(_format_artist_response(result)) def _format_search_response(artists): """Format Apple Music search response.""" if ( not isinstance(artists, dict) or 'results' not in artists or 'artists' not in artists['results'] ): return [] return [ { 'identifier': r['id'], 'name': r['attributes']['name'], 'genres': r['attributes']['genreNames'], 'url': r['attributes']['url'], } for r in artists['results']['artists']['data'] ] def _format_artist_response(artist): """Format Apple Music artist response.""" if not isinstance(artist, dict) or 'data' not in artist or not artist['data']: return {} artist_data = artist['data'][0] return { 'identifier': artist_data['id'], 'name': artist_data['attributes']['name'], 'genres': artist_data['attributes']['genreNames'], 'url': artist_data['attributes']['url'], }