"""Logic for top videos by channel.""" from typing import Any, Dict, Mapping from analytics.constants import cache from analytics.logic.permissions import has_full_access_on_permissions from analytics.logic.stores import add_outage_error_to_stores from analytics.queries.format import format_row from analytics.queries.videos import ChannelTopVideos from analytics.schemas.channel_top_videos import ChannelTopVideosSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis @cache_in_redis(ttl=cache.ONE_DAY) def get_channel_top_videos( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ) -> Dict: """Return top videos for channel_id.""" # an empty response, but with sources response_body = { "channel_id": query_params["channel_id"], "top_channel_videos": [], "sources": add_outage_error_to_stores(store_availability.get_video_sources()), } # channels are visible only to employees and vendors if ( not has_full_access_on_permissions(permissions) and not permissions["permission_label_ids"] ): return ChannelTopVideosSchema.normalized_response(response_body) if not query_params["store_ids"]: query_params["store_ids"] = store_availability.get_video_store_ids() else: query_params["store_ids"] = list( set(query_params["store_ids"]).intersection( store_availability.get_video_store_ids() ) ) if query_params.get("all_time"): if query_params.get("country_ids"): query_params[ "table_name" ] = "VIEWS_BY_VIDEO_COUNTRY_FEED_DISTRIBUTOR_ROLLUP" else: query_params["table_name"] = "VIEWS_BY_VIDEO_FEED_DISTRIBUTOR_ROLLUP" else: if query_params.get("country_ids"): query_params[ "table_name" ] = "V_VIEWS_BY_VIDEO_COUNTRY_FEED_DISTRIBUTOR_DAILY" else: query_params["table_name"] = "VIEWS_BY_VIDEO_FEED_DISTRIBUTOR_DAILY" result = ChannelTopVideos({**query_params, **permissions}).execute() top_channel_videos = [format_row(data_point) for data_point in result] response_body["top_channel_videos"] = top_channel_videos return ChannelTopVideosSchema.normalized_response(response_body)