"""Logic for top traffic sources by channel.""" from typing import Any, Mapping from analytics.constants import cache from analytics.handler_utils import user_has_full_access from analytics.logic.stores import add_outage_error_to_stores from analytics.queries.format import format_row from analytics.queries.videos import TopChannelTrafficSources from analytics.schemas.channel_traffic_sources import ChannelTrafficSourcesSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis @cache_in_redis(ttl=cache.ONE_DAY) def get_top_channel_traffic_sources( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return top traffic sources for channel_id.""" response_body = { "channel_id": query_params["channel_id"], "top_channel_traffic_sources": [], "sources": add_outage_error_to_stores(store_availability.get_video_sources()), } # channels are visible only to employees and vendors if ( not user_has_full_access(permissions) and not permissions["permission_label_ids"] ): return ChannelTrafficSourcesSchema.normalized_response(response_body) # store_ids are used only for the YouTube-availability short-circuit; # the channel-level SQL view is already filtered to YouTube. store_ids = ( query_params.get("store_ids") or store_availability.get_video_store_ids() ) store_ids = list( set(store_ids).intersection(store_availability.get_video_store_ids()) ) if not store_ids: return ChannelTrafficSourcesSchema.normalized_response(response_body) all_time = not (query_params.get("start_date") and query_params.get("end_date")) query_params["all_time"] = all_time if all_time: if query_params.get("country_ids"): query_params[ "table_name" ] = "VIEWS_BY_CHANNEL_SOURCE_COUNTRY_FEED_DISTRIBUTOR_ROLLUP" else: query_params[ "table_name" ] = "VIEWS_BY_CHANNEL_SOURCE_FEED_DISTRIBUTOR_ROLLUP" else: if query_params.get("country_ids"): query_params[ "table_name" ] = "VIEWS_BY_CHANNEL_SOURCE_COUNTRY_FEED_DISTRIBUTOR_DAILY" else: query_params[ "table_name" ] = "VIEWS_BY_CHANNEL_SOURCE_FEED_DISTRIBUTOR_DAILY" response_body["top_channel_traffic_sources"] = [ format_row(row) for row in TopChannelTrafficSources({**query_params, **permissions}).execute() ] return ChannelTrafficSourcesSchema.normalized_response(response_body)