"""Boto3 s3 file operations.""" from botocore.exceptions import ClientError from podcast.connectors import s3 from podcast.utils.exc import OwsError def check_s3_file_exists(bucket_name, file_key): """Check the file exists in provided s3 bucket. Args: bucket_name (str): name of bucket where file is stored. file_key (str): path to file for which url should be generated. Returns: Response: Response with success or error. """ try: s3_client = s3.get_s3_client() s3_client.head_object(Bucket=bucket_name, Key=file_key) except ClientError as e: error_message = 'error looking for {key} in bucket {bucket}'.format(key=file_key, bucket=bucket_name) raise OwsError.from_boto3_client_error(e, error_message) def copy_s3_file(source_bucket, source_key, destination_bucket, destination_key): """Copy S3 object from one bucket to another. This is a managed transfer which will perform a multipart copy in multiple threads if necessary. Document: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.copy Args: source_bucket (str): Bucket name for source S3 object. source_key (str): Key name of the source S3 object. destination_bucket (str):Bucket name for destination S3 object. destination_key (str): Key name of the destination S3 object. Returns: dict: Response from S3. """ try: s3_client = s3.get_s3_client() s3_client.copy( CopySource={'Bucket': source_bucket, 'Key': source_key}, Bucket=destination_bucket, Key=destination_key ) except ClientError as e: error_message = 'error while copying file: {} from input bucket: {} to output bucket: {}'.format( source_key, source_bucket, destination_bucket) raise OwsError.from_boto3_client_error(e, error_message)