"""Module for handling SFTP asset delivery for YouTube.""" import os from src.common.connectors import sftp from src.common import logger import config sftp_connection = None def write_file( file_bytes: bytes, subdir: str, step_function_execution_id: str): """Write file to YouTube via SFTP. Args: file_bytes (bytes): The file content in bytes. subdir (str): The subdirectory to upload the file to. step_function_execution_id (str): The step function execution ID. """ global sftp_connection basepath = os.environ.get('YOUTUBE_SFTP_BASE_DIRNAME', '') basepath = basepath.rstrip('/') + '/' if basepath else '' if sftp_connection is None: sftp_connection = _get_sftp_connection() try: sftp_connection.upload_files( [(file_bytes, basepath + step_function_execution_id + '/' + subdir)] ) except Exception as e: logger.error(f'Error uploading file to YouTube: {e}') raise e def _get_sftp_connection(): """Get SFTP connection.""" global sftp_connection if sftp_connection is None: env = os.environ.get('ENVIRONMENT', 'dev') if env == 'dev': key = config.YOUTUBE_SFTP_PRIVATE_KEY else: key = config.secrets_manager_client.get_cred('YOUTUBE_CMS_FP_PRIVATE_KEY') try: sftp_connection = sftp.Connection( hostname=config.YOUTUBE_SFTP_HOSTNAME, port=config.YOUTUBE_SFTP_PORT, username=config.YOUTUBE_SFTP_USERNAME, pkey=key ) except Exception as e: logger.error(f'Error establishing SFTP connection: {e}') raise e return sftp_connection