"""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 import data_availability from analytics.logic.stores import add_outage_error_to_stores from analytics.queries.format import format_row from analytics.queries.videos import TopCountriesVideos from analytics.schemas.top_countries_videos import TopCountriesVideosSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis @cache_in_redis(ttl=cache.ONE_DAY) def get_top_countries_videos( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return top countries by views for video_id.""" response_body = { "video_id": query_params["video_id"], "top_countries_videos": [], "sources": add_outage_error_to_stores(store_availability.get_video_sources()), } # videos are visible only to employees and vendors if ( not user_has_full_access(permissions) and not permissions["permission_label_ids"] ): return TopCountriesVideosSchema.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"] = sorted( set(query_params["store_ids"]).intersection( store_availability.get_video_store_ids() ) ) if not query_params["store_ids"]: return TopCountriesVideosSchema.normalized_response(response_body) if not (query_params.get("start_date") and query_params.get("end_date")): start_date, end_date = data_availability.get_date_range( data_availability.HIGHWATERMARK_DATE, days=28, downloads=False, videos=True, ) query_params["start_date"] = start_date.strftime("%Y-%m-%d") query_params["end_date"] = end_date.strftime("%Y-%m-%d") top_countries = [ format_row(row) for row in TopCountriesVideos({**query_params, **permissions}).execute() ] if top_countries: response_body["top_countries_videos"] = top_countries return TopCountriesVideosSchema.normalized_response(response_body)