File: //home/arjun/projects/buyercall_forms/buyercall/buyercall/lib/util_boto3_s3.py
import logging
import boto3
from botocore.exceptions import ClientError
from urllib.parse import unquote
from flask import (
make_response,
request,
jsonify,
current_app)
log = logging.getLogger(__name__)
# Retrieves the key and bucket from the url passed to it
def get_recording_url_details(url):
details = {}
bucket = None
key = None
pos = 0
url = unquote(url)
if 'http' in url and '.com' in url:
split_string = url.split('.com')
if len(split_string) == 2:
draft_bucket = split_string[0].replace("https://", "").replace("http://", "")
bucket_split = draft_bucket.split(".s3.")
if len(draft_bucket) >= 2:
bucket = bucket_split[0]
if ':' in split_string[1]:
pos = split_string[1].index('/')
key = split_string[1]
key = key[pos+1:]
elif '::' in url:
split_string = url.split("::")
if len(split_string) == 2:
bucket = split_string[0]
key = split_string[1]
if not key and not bucket:
log.error('No bucket or key found.')
return None
else:
details['key'] = key
details['bucket'] = bucket
log.error('Key: ' + str(key) + ' Bucket: ' + str(bucket))
return details
def generate_presigned_aws_url(key, bucket, frontend=None, expiration=None):
default_expiry = 300
try:
s3_client = boto3.client(
's3',
aws_access_key_id=current_app.config['AMAZON_ACCESS_KEY'],
aws_secret_access_key=current_app.config['AMAZON_SECRET_KEY']
)
if frontend:
if isinstance(current_app.config['AMAZON_PRESIGNED_URL_FRONTEND_EXPIRY'], int):
default_expiry = current_app.config['AMAZON_PRESIGNED_URL_FRONTEND_EXPIRY']
else:
if isinstance(current_app.config['AMAZON_PRESIGNED_URL_WEBHOOK_EXPIRY'], int):
default_expiry = current_app.config['AMAZON_PRESIGNED_URL_WEBHOOK_EXPIRY']
if expiration:
default_expiry = expiration
return s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket,
'Key': key},
ExpiresIn=default_expiry)
except ClientError as e:
log.error("Error generating presigned url. Error: {}".format(e))
return ''
def upload_file(file_path, bucket, key_name, content_type=None):
try:
s3_client = boto3.client(
's3',
aws_access_key_id=current_app.config['AMAZON_ACCESS_KEY'],
aws_secret_access_key=current_app.config['AMAZON_SECRET_KEY']
)
bucket = bucket
file_name = file_path
key_name = key_name
if content_type:
s3_client.upload_file(file_name, bucket, key_name, ExtraArgs={'ContentType': content_type})
# Optionally if the file needs to be pulic, we can set the ACL as args as well
# s3_client.upload_file(file_name, bucket, key_name,
# ExtraArgs={'ContentType': "application/json", 'ACL': "public-read"})
else:
s3_client.upload_file(file_name, bucket, key_name)
file_url = generate_presigned_aws_url(key_name, bucket, expiration=432000)
return file_url
except ClientError as e:
log.error("Error uploading file to S3. Error: {}".format(e))
return ''