"""Source of Streams model.""" from ddtrace import tracer 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 STREAMS_BREAKDOWN_FIELDS = [ "isrc", "streams_passive", "streams_active", "streams_collection", "subscription", "ad_supported", "mid_tier", "streams", ] SQLLoader = snowflake.SQLLoader(__file__) @tracer.wrap(name="get_streams_breakdown") @cache_in_redis(ttl=cache.SECONDS_PER_HOUR) def get_streams_breakdown( permissions_filter, isrc, distributors, countries=[], store_ids=[], start_date=None, end_date=None, ): """Get streams by subscription type breakdown for given ISRC. Args: permissions_filter (dict): dict containing resources users can access isrc (str): ISRC of track to fetch breakdown for distributors (list): List of distributors names countries (list): List of country codes to filter by store_ids (list): List of store ids to filter by start_date (datetime.date): Start date end_date (datetime.date): End date Returns: dict: SST breakdown """ if len(store_ids) == 0: store_ids = store_availability.get_store_ids() else: store_ids = list( set(store_ids).intersection(store_availability.get_store_ids()) ) params = { **permissions_filter, "isrc": isrc, "store_ids": store_ids, "start_date": start_date, "end_date": end_date, "distributors": distributors, } if len(countries) > 0: params["country_codes"] = countries query_table = "streams_breakdown_by_country" else: query_table = "streams_breakdown" sql = SQLLoader.load_query(query_table) sql = format_sql.format_with_permissions_filter( sql, permissions_filter, start_date=start_date, end_date=end_date ) breakdown = snowflake.fetchone(sql, params) if not breakdown: return None return dict(zip(STREAMS_BREAKDOWN_FIELDS, breakdown))