"""Collector for Spotify metrics.""" import requests from requests.auth import HTTPBasicAuth from social_analytics.constants import collectors def collect_spotify_metrics(profile_id, spotify_auth_token): """Collect spotify metrics for a given profile id. Args: profile_id (str): The Spotify profile id e.g. 06HL4z0CvFAxyc27GXpf02 spotify_auth_token (str): The spotify oauth token Returns: dict : A dictionary with the spotify data. """ query = collectors.SPOTIFY_ARTIST_INFO url = construct_spotify_url(profile_id, query) headers = { 'Authorization': collectors.SPOTIFY_AUTHORIZATION_HEADER.format( spotify_auth_token=spotify_auth_token)} result = requests.get(url, headers=headers) return result.json() def construct_spotify_url(profile_id, query_params): """Generate a Spotify api url based on a profile id. Args: profile_id (str): The Spotify profile id e.g. 06HL4z0CvFAxyc27GXpf02 query_params (str): The Spotify api route. Returns: string: The spotify url with all authentication params. """ params = query_params + '/' + profile_id url = collectors.SPOTIFY_BASE_URL + params return url def refresh_token(): """Refresh Spotify access token. Returns: dict: A dictionary that contains the oauth token. """ headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'grant_type': collectors.SPOTIFY_GRANT_TYPE, 'refresh_token': collectors.SPOTIFY_REFRESH_TOKEN} r = requests.post( collectors.SPOTIFY_AUTHORIZATION_URL, data=data, auth=HTTPBasicAuth( collectors.SPOTIFY_CLIENT_ID, collectors.SPOTIFY_CLIENT_SECRET), headers=headers) return r.json() def recommend_spotify_profile(profile_name, spotify_access_token): """Recommend spotify profile. Args: profile_name (str): The profile name of the artist e.g. Mastodon spotify_access_token (str): The Spotify access token. Returns: Dict or None: A dictionary with the suggested profile or None when there is not any profile for the given profile name. """ if not spotify_access_token: spotify_auth_token = refresh_token()['access_token'] headers = {'Authorization': 'Bearer {0}'.format(spotify_auth_token)} url = ( collectors.SPOTIFY_BASE_URL + '/search?query={0}&type=artist'.format( profile_name)) result = requests.get(url, headers=headers) result_json = result.json() if 'error' in result_json: return None profiles = result_json['artists']['items'] recommended_spotify_profile = ( max( profiles, key=lambda item: item['popularity'] and item[ 'followers']['total'])) return { 'platform': 'spotify', 'platform_id': recommended_spotify_profile['id'], 'platform_name': recommended_spotify_profile['name'], 'metric_value': recommended_spotify_profile['followers']['total'] } def verify_spotify_profile(platform_id): """Verify spotify profile. Args: platform_id (str): The profile id of the artist e.g. 123444453 Returns: Dict or None: A dictionary with the verified profile or None when there is not any profile for the given profile name. """ spotify_auth_token = refresh_token()['access_token'] query = collectors.SPOTIFY_ARTIST_INFO url = construct_spotify_url(platform_id, query) headers = { 'Authorization': collectors.SPOTIFY_AUTHORIZATION_HEADER.format( spotify_auth_token=spotify_auth_token)} result = requests.get(url, headers=headers) result_json = result.json() if 'error' in result_json: return None return { 'platform': 'spotify', 'platform_id': result_json['id'], 'platform_name': result_json['name'], 'metric_value': result_json['followers']['total'] }