"""Backfill season number for all episodes for migrated show. run this in dev with command docker compose run --build backfill-season-number-for-episodes --api_key=megaphone_token --env=dev --podcast_id=31126 --season_number=1 """ import argparse import logging import sys import time from flask import g from podcast import config from podcast.api import app from podcast.connectors import mysql from podcast.logic import megaphone as megaphone_logic from podcast.models import episode as episode_model from podcast.models import podcast as podcast_model from podcast.utils import api_utils log = logging.getLogger('main') log.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') sh = logging.StreamHandler(sys.stdout) sh.setFormatter(fmt) log.addHandler(sh) users = { 'dev': '366', 'qa': '1298', 'prod': '88' } request_headers = None def get_episodes(podcast_id): """Return episodes of a podcast. Args: podcast_id(int): Id of the podcast """ with mysql.pod_db_session(read_only=True) as session: rows = session.query(episode_model.Episode).filter( episode_model.Episode.podcast_id == podcast_id, episode_model.Episode.is_deleted.isnot(True) ).all() return [row.to_dict() for row in rows] def update_episode_details_in_megaphone(mp_podcast_id, network_id, updated_episode): """Update season number in megaphone. Args: mp_podcast_id (str): The podcast unique identifier in megaphone. network_id (str): The network unique identifier. updated_episode (dict): The updated_episode data from episode table/model. Returns: dict: the megaphone api response. """ megaphone_data = { 'seasonNumber': updated_episode['season_number'], 'retainAdLocations': True } megaphone_response = megaphone_logic.call_episode_api( megaphone_data, mp_podcast_id, updated_episode['megaphone_id'], network_id, updated_episode['id'] ) return megaphone_response def backfill_season_number(podcast_id, season_number): """Backfill season number in podcast DB and megaphone. Args: podcast_id(int): Id of the podcast. season_number(int): Season Number. """ ep_count = 0 error_count = 0 errored_episodes = [] podcast = podcast_model.get_podcast_by_id(podcast_id) episodes = get_episodes(podcast_id) for episode in episodes: try: episode_id = episode['id'] print(f'Running for episode_id: {episode_id}') updated_season_number = {'season_number': season_number} updated_episode = episode_model.update_episode(episode_id, updated_season_number) print(f'Database updated for episode: {episode_id} with season number {season_number}') update_episode_details_in_megaphone( podcast['megaphone_id'], podcast['network_id'], updated_episode) print(f'Megaphone updated for episode: {episode_id} with season number {season_number}') except Exception as e: errored_episodes.append(episode_id) error_count += 1 log.info( f'Got an exception for episode_id: {episode_id}\n' f'Exception trace: {e}\n' ) ep_count += 1 if ep_count % 10 == 0: print(f'\n sleep time 10 secs and episode count: {ep_count}\n') time.sleep(10) def main(): """Extract shell arguments and start backfilling episode season number in podcast DB and megaphone.""" global request_headers argparser = argparse.ArgumentParser(prog='Backfill season_number for all episodes in a show') argparser.add_argument('--api_key', required=True, help='Megaphone API Key') argparser.add_argument('--env', required=True, help='env', default='qa') argparser.add_argument('--podcast_id', required=True, help='podcast_id') argparser.add_argument('--season_number', required=True, help='season_number') args = argparser.parse_args() config.MEGAPHONE_API_TOKEN = args.api_key env = args.env podcast_id = int(args.podcast_id) season_number = int(args.season_number) def get_user_id(): """Mock get user id return value.""" return users[env] api_utils.get_user_id = get_user_id request_headers = { 'Grass-Account-Type': 'vendor', 'Grass-Account-Id': '1', 'Correlation-Id': '12', 'Orchard-Identity-UUID': 'podcast-admin', 'Content-Type': 'application/json' } log.info( f'Running backfill with season number {season_number} for {env} Environment. for podcast id {podcast_id}\n') with app.app_context(): g.log = log backfill_season_number(podcast_id, season_number) if __name__ == '__main__': main()