def setup_audio_recording()

in sam-app/lambda_functions/sfExecuteAWSService.py [0:0]


def setup_audio_recording(CloudfrontPublicKey):
    s3_client = boto3.client("s3")
    bucket_name = os.environ["RECORDING_BUCKET_NAME"]
    bucket_cors_rules = []
    try:
        bucket_cors_rules = s3_client.get_bucket_cors(Bucket=bucket_name)["CORSRules"]
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] != 'NoSuchCORSConfiguration':
            raise e
    
    sf_host = os.environ["SALESFORCE_HOST"]
    lightning_url = sf_host[:sf_host.index(".my.salesforce.com")] + ".lightning.force.com"
    visualforce_url = sf_host[:sf_host.index(".my.salesforce.com")]
    if os.environ["NAMESPACE"]:
        visualforce_url = visualforce_url + "--" + os.environ["NAMESPACE"] + ".visualforce.com"
    else:
        visualforce_url = visualforce_url + "--c.visualforce.com"

    for rule in bucket_cors_rules:
        if lightning_url in rule["AllowedOrigins"]:
            bucket_cors_rules.remove(rule)

    bucket_cors_rules.append({
        "AllowedHeaders": ["Access-Control-Allow-Origin"],
        "AllowedMethods": ["GET"],
        "AllowedOrigins": [lightning_url, visualforce_url]
    })
    s3_client.put_bucket_cors(
        Bucket=bucket_name,
        CORSConfiguration={
            "CORSRules": bucket_cors_rules
        }
    )

    cloudfront_client = boto3.client("cloudfront")
    create_public_key_response = cloudfront_client.create_public_key(
        PublicKeyConfig={
            'CallerReference': str(uuid.uuid4()),
            'Name': 'AmazonConnectSalesforceCTIAdapterContactLens',
            'EncodedKey': CloudfrontPublicKey
        }
    )
    create_key_group_response = cloudfront_client.create_key_group(
        KeyGroupConfig={
            'Name': 'AmazonConnectSalesforceCTIAdapterContactLens',
            'Items': [
                create_public_key_response["PublicKey"]["Id"]
            ]
        }
    )

    # edge lambdas must be created in us-east-1
    lambda_client = boto3.client("lambda", region_name='us-east-1')
    cloudformation_stack_name = os.environ["CLOUDFORMATION_STACK_NAME"]
    MAX_LAMBDA_NAME_LENGTH = 64
    function_name_end = '-sfSig4RequestToS3'
    function_name_start = cloudformation_stack_name[:MAX_LAMBDA_NAME_LENGTH - len(function_name_end)]
    function_name =  function_name_start + function_name_end
    create_function_response = lambda_client.create_function(
        FunctionName=function_name,
        Runtime='nodejs12.x',
        Role=os.environ["SIG4_LAMBDA_ROLE_ARN"],
        Handler='sfSig4RequestToS3.handler',
        Code={
            'ZipFile': open('./sfSig4RequestToS3.zip', 'rb').read()
        }
    )
    publish_version_response = lambda_client.publish_version(
        FunctionName=function_name
    )

    get_distribution_config_response = cloudfront_client.get_distribution_config(
        Id=os.environ["CLOUDFRONT_DISTRIBUTION_ID"]
    )

    distribution_config = get_distribution_config_response["DistributionConfig"]
    distribution_config["DefaultCacheBehavior"]["LambdaFunctionAssociations"] = {
        'Quantity': 1,
        'Items': [
            {
                'LambdaFunctionARN': publish_version_response["FunctionArn"],
                'EventType': 'origin-request',
                'IncludeBody': False
            },
        ]
    }
    distribution_config["DefaultCacheBehavior"]["TrustedSigners"] = {
        'Enabled': False,
        'Quantity': 0
    }
    distribution_config["DefaultCacheBehavior"]["TrustedKeyGroups"] = {
        'Enabled': True,
        'Quantity': 1,
        'Items': [ create_key_group_response["KeyGroup"]["Id"] ]
    }

    return format_datetime_values(cloudfront_client.update_distribution(
        DistributionConfig=distribution_config, 
        Id=os.environ["CLOUDFRONT_DISTRIBUTION_ID"], 
        IfMatch=get_distribution_config_response["ETag"]
    ))