"""Logic for top countries by video views.""" 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 TopVideoTrafficSources from analytics.schemas.top_video_traffic_sources import TopVideoTrafficSourcesSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis @cache_in_redis(ttl=cache.ONE_DAY) def get_top_video_traffic_sources( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return top traffic sources for video_id. Returns: Response with top traffic sources payload """ # an empty response, but with sources response_body = { "video_id": query_params["video_id"], "top_video_traffic_sources": [], "sources": add_outage_error_to_stores(store_availability.get_video_sources()), } # if user's permissions are to subaccounts only, return an empty response if ( not user_has_full_access(permissions) and not permissions["permission_label_ids"] ): return TopVideoTrafficSourcesSchema.normalized_response(response_body) # for now, it's always only one: 453 for YouTube, but let's keep in just in case if len(query_params["store_ids"]) == 0: store_ids = store_availability.get_video_store_ids() else: store_ids = list( set(query_params["store_ids"]).intersection( store_availability.get_video_store_ids() ) ) query_params["store_ids"] = store_ids if len(store_ids) == 0: return TopVideoTrafficSourcesSchema.normalized_response(response_body) if query_params["country_ids"]: query_params[ "table_name" ] = "V_VIEWS_BY_VIDEO_SOURCE_COUNTRY_FEED_DISTRIBUTOR_DAILY" else: # this table is not split yet, so no V_ prefix query_params["table_name"] = "V_VIEWS_BY_VIDEO_SOURCE_FEED_DISTRIBUTOR_DAILY" query = TopVideoTrafficSources({**query_params, **permissions}) response_body["top_video_traffic_sources"] = [ format_row(data_point) for data_point in query.execute() ] return TopVideoTrafficSourcesSchema.normalized_response(response_body)