def lambda_handler()

in source/lambdafunctions/lambdaedge/lambda_function.py [0:0]


def lambda_handler(event, context):
    
    start_processtime_lambda = time.time()
    request = event['Records'][0]['cf']['request'].copy()
    custom_headers = request['origin']['custom'].pop('customHeaders')
    untouched_request = request.copy()
    if request['method'] != 'PUT':
        print("INFO Request Method is: {} skipping...".format(request['method']))
        return untouched_request
    ## Check for environment variables in customHeader
    if not get_environment_variables(custom_headers):
        print("ERROR GLOBALS not set sending request untouched")
        put_count_metrics('error_lambda', 1, 'unknown', 'unknown')
        return untouched_request
    
    try:
        if DEBUG:
            print("DEBUG CF Request: {}".format(request))
        request['headers']['user-agent'][0]['value'] = "AWS Lambda"
        ## Decode .vtt contents
        try: 
            og_body = base64.b64decode(request['body']['data']).decode("utf-8")
        except Exception as e:
            print("ERROR base64decode: %s" % e)
            put_count_metrics('error_lambda', 1, PIPE_ID, 'unknown')
            return untouched_request
        if DEBUG:
            print("DEBUG CF body raw: {}".format(request['body']['data']))
            print("DEBUG CF Body base64 decoded: {}".format(og_body))

        if CAPTION_PASSTHROUGH:
            print("INFO CAPTION_PASSTHROUGH Global is TRUE, skipping autocaptions")
            put_count_metrics('caption_passthrough', 1, PIPE_ID, 'unknown')
            return untouched_request
        
        if CAPTION_REPLACE:
            new_body = []
            caption_detected = False
            for this_line in og_body.splitlines():
                if re.search(r'\d{2,}:\d{2}:\d{2}\.\d{3} --> \d{2,}:\d{2}:\d{2}\.\d{3}', this_line):
                    print("WARNING Caption Detected!")
                    put_count_metrics('caption_detected', 1, PIPE_ID, 'unknown')
                    caption_detected = True
                    break
                else:
                    new_body.append(this_line)
            new_body.append('')
            if caption_detected:
                print("WARNING Caption Scrubbed")
                put_count_metrics('caption_scrubbed', 1, PIPE_ID, 'unknown')
                og_body = "\n".join(new_body)
        else:
            print("WARNING CAPTION_REPLACE Global is FALSE, skipping autocaptions")
            put_count_metrics('caption_skipped', 1, PIPE_ID, 'unknown')
            return untouched_request
        ## CAPTION
        r = re.search(r'channel_(\w{2})_\d{1,}\.vtt', request['uri'])
        if not r: 
            print("ERROR REGEX for lang_id failed, skipping autocaptions")
            put_count_metrics('error_lambda', 1, PIPE_ID, 'unknown')
            return untouched_request
        lang_id = r.group(1)
        if DEBUG: 
            print("DEBUG lang_id: {}".format(lang_id))
        # Get caption text from dynamo
        latest_caption_text = caption_latest(PIPE_ID, lang_id)
        if latest_caption_text == False:
            print("ERROR Caption is False, passthrough unmodified request ")
            put_duration_metrics('processtime_lambda', start_processtime_lambda, time.time(), PIPE_ID, lang_id)
            return untouched_request

        ## Append new caption to vtt file
        try:
            vtt = og_body.splitlines()
            vtt.append("00:00:00.000 --> 1000000:00:00.000 line:13 position:5% align:left size:90%")
            vtt.append(latest_caption_text)
            vtt.append('')
            vtt_file = "\n".join(vtt)
            request['body']['action'] = 'replace'
            request['body']['encoding'] = 'text'
            request['body']['data'] = str(vtt_file)
            if DEBUG:
                print("DEBUG after body: {}".format(request['body']['data']))
            put_duration_metrics('processtime_lambda', start_processtime_lambda, time.time(), PIPE_ID, lang_id)
            return request
        except:
            print("ERROR cannot combine og_body with new captions")
            put_count_metrics('error_lambda', 1, PIPE_ID, lang_id)
            print_exception()
            put_duration_metrics('processtime_lambda', start_processtime_lambda, time.time(), PIPE_ID, lang_id)
            return untouched_request
    except: 
        print("ERROR Outer Lambda Exception")
        put_count_metrics('error_lambda', 1, PIPE_ID, lang_id)
        print_exception()
        put_duration_metrics('processtime_lambda', start_processtime_lambda, time.time(), PIPE_ID, lang_id)
        return untouched_request
    return untouched_request