"""Model for ows-track.""" from typing import Any, Dict import config import requests import sentry_sdk from lambdacommon.common_config import logger from src.constants import urls from src.utils.document import cleanup_unicode def get_track_artist_info(tuid: int) -> dict[str, Any]: """Get information about track from ows-track microservice. Args: tuid (int): track unique id Returns: dict: information about track """ result = {"artist_id": 0, "artist_name": ""} response = _fetch_from_ows_track(tuid, "track_id", urls.OWS_TRACK_ENDPOINT) if response.status_code == 200: info = response.json() artist = next((a for a in info["artists"] if a["type"] == "performer"), None) if artist: result["artist_id"] = artist["track_artist_id"] result["artist_name"] = cleanup_unicode(artist["name"]) return result def get_all_tracks_by_product_id(pid: int) -> list[Dict[str, Any]]: """Get information about track from ows-track microservice. Args: pid (int): product id Returns: list: information about tracks """ result = [] response = _fetch_from_ows_track(pid, "product_id", urls.OWS_TRACK_PRODUCT_ENDPOINT) if response.status_code == 200: tracks = response.json()["items"] for track in tracks: artist = next((a for a in track["artists"] if a["type"] == "performer"), None) if artist: track["artist_id"] = artist["track_artist_id"] track["artist_name"] = cleanup_unicode(artist["name"]) else: track["artist_id"] = 0 track["artist_name"] = "" result = tracks return result def get_track_by_tuid(tuid: int) -> Dict[str, Any]: """Get information about track from ows-track microservice. Args: tuid (int): track id Returns: dict: information about a track """ response = _fetch_from_ows_track(tuid, "track_id", urls.OWS_TRACK_ENDPOINT) if response.status_code == 200: track = response.json() artist = next((a for a in track["artists"] if a["type"] == "performer"), None) if artist: track["artist_id"] = artist["track_artist_id"] track["artist_name"] = cleanup_unicode(artist["name"]) else: track["artist_id"] = 0 track["artist_name"] = "" return track return {} def _fetch_from_ows_track(tuid: int, id_type: str, endpoint: str) -> requests.Response: url = urls.SERVICE_URL.format( environment=config.ENVIRONMENT, service_name=urls.OWS_TRACK_SERVICE_NAME, path=endpoint.format(tuid), ) retry = 2 response = requests.get(url) while retry: if response.status_code not in (200, 404): retry -= 1 if retry: logger.info(f"Retrying to get track info for {id_type}: {tuid}") response = requests.get(url) else: retry = 0 if response.status_code not in (200, 404): try: error_msg = response.json() except Exception: error_msg = response.content.decode() error = "Failed to get info from ows-track. {}: {} error_code: {} error_message: {}".format( id_type, tuid, response.status_code, error_msg ) sentry_sdk.capture_message(error) raise Exception(urls.OWS_TRACK_ERROR) return response