"""Top Sound_recordings Model.""" from sound_recordings.connectors import snowflake from sound_recordings.constants import cache from sound_recordings.utils import format_sql, store_availability from sound_recordings.utils.cache import cache_in_redis TOP_SOUND_RECORDINGS_FIELDS = ["isrc", "streams", "growth_percentage"] TOP_SOUND_RECORDINGS_METRICS = [ "streams_1_day", "streams_7_days", "streams_28_days", "streams_all_time", ] SQLLoader = snowflake.SQLLoader(__file__) @cache_in_redis(ttl=cache.SECONDS_PER_HOUR) def get_top_sound_recordings( permissions_filter, distributors, limit, offset, countries=[], order_by="streams_7_days", ): """Get the top sound_recordings for an account. Args: permissions_filter (dict): dict containing resources users can access distributors (str[]): list of distributors names limit (int): max number of results offset (int): starting index of results countries (str[]): list of country codes to filter by order_by (str): selector column of interest Returns: list of top sound_recordings """ if order_by not in TOP_SOUND_RECORDINGS_METRICS: raise Exception("Invalid order_by field") store_ids = store_availability.get_store_ids() params = { **permissions_filter, "limit": limit, "offset": offset, "store_ids": store_ids, "distributors": distributors, } if len(countries) > 0: params["country_codes"] = countries query_table = "get_top_sound_recordings_by_country" else: query_table = "get_top_sound_recordings" if order_by == "streams_all_time": query_table += "_all_time" sql = SQLLoader.load_query(query_table) sql = format_sql.format_with_permissions_filter(sql, permissions_filter) sql = sql.format(order_by=order_by) top_sound_recordings = snowflake.fetchall(sql, params) return [ dict(zip(TOP_SOUND_RECORDINGS_FIELDS, sound_recording)) for sound_recording in top_sound_recordings ]