"""Logic for top countries by channel 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 TopCountriesChannels from analytics.schemas.top_countries_channels import TopCountriesChannelsSchema 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_channels( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return top countries by views for channel_id.""" response_body = { "channel_id": query_params["channel_id"], "top_countries_channels": [], "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 TopCountriesChannelsSchema.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 = sorted( set(store_ids).intersection(store_availability.get_video_store_ids()) ) if not store_ids: return TopCountriesChannelsSchema.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 TopCountriesChannels({**query_params, **permissions}).execute() ] if top_countries: response_body["top_countries_channels"] = top_countries return TopCountriesChannelsSchema.normalized_response(response_body)