"""Interface for managing sound recording delivery audit XML storage in s3.""" import io import os from typing import Optional import boto3 s3_client = boto3.client('s3') ENV_CONFIG = { 'dev': { 'bucket': 'test-orcd-bucket', 'prefix': 'sound_recording_delivery_audit/', 'account_id': '103233932089' }, 'qa': { 'bucket': 'qa-sr-delivery-audit-bucket', 'prefix': '', 'account_id': '437795906767' }, 'prod': { 'bucket': 'prod-sr-delivery-audit-bucket', 'prefix': '', 'account_id': '437795906767' } } def write_sr_delivery_audit_xml( local: bytes, remote: str, step_function_execution_id: str, service: Optional[str] = None): # noqa:E501 """Upload sound recording delivery DDEX XML data for future auditing. Args: local (bytes): The file to transfer remote (str): The subdirectory to store the file in step_function_execution_id (str): uuid representing a delivery attempt service (str | None): The service name (e.g., 'youtube'). This will create a subfolder with the service name. Returns: bool: if files were all successfully put on S3 """ (bucket, prefix) = _config() put_response = s3_client.put_object( Bucket=bucket, Key=f'{prefix}{service + "/" if service else ""}{step_function_execution_id}/{remote}', # noqa:E501 Body=io.BytesIO(local) ) return put_response def download_sr_delivery_audit_xml(file_name: str, service: Optional[str] = None) -> Optional[bytes]: """Download sound recording delivery audit XML data. Args: file_name (str): The S3 location of the file to download Returns: bytes | None: The file data or None if not found """ (bucket, prefix) = _config() try: response = s3_client.get_object( Bucket=bucket, Key=f'{prefix}{service + "/" if service else ""}{file_name}', ExpectedBucketOwner=ENV_CONFIG[os.environ['ENVIRONMENT']]['account_id'] ) return response['Body'].read() except s3_client.exceptions.NoSuchKey: return None def _config(): """Get config based on value of Environment var.""" env = os.environ['ENVIRONMENT'] config = ENV_CONFIG[env] return ( config['bucket'], config['prefix'] )