import boto3, ffmpy, os

s3 = boto3.resource('s3')
s3_client = boto3.client('s3')
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('FT_SegmentState')
sqs = boto3.resource('sqs')
statusqueue = sqs.get_queue_by_name(QueueName='FT_status_queue')

def lambda_handler(event, context):
    # Get the object from the event and show its content type
    # This job is triggered by FT_VideoConversions

    Row = event[0]['dynamodb']['NewImage']
    Bucket = Row['Bucket']
    Filename = Row['Filename']
    Path = Row['Path']
    ConversionID = Row['ConversionID']
    QueueMessageID = Row['QueueMessageID']
    S3Path = "{}{}".format(Path, Filename)
    LocalPath = "/tmp/{}/{}".format(ConversionID, Filename)

    print "Bucket/ConversionID is {}, {}".format(Bucket, ConversionID)
    print "QueueMessageID is {}".format(QueueMessageID)

    if not S3Path.endswith('/'):
        try:
            # Finagle S3 bucket naming conventions so that boto retrieves the correct file
            #global split_key
            #split_key = Key.split('/')
            #global file_name
            #file_name = Key[-1]
            #global file_extension
            #file_extension = os.path.splitext(file_name)[1]
            #print "segmenting {} file".format(file_extension)

            # sqs.put_message(
            # QueueUrl=statusqueue
            # ReceiptHandle=StatusReceipt
            # status='Downloading'
            # )
            # Download the source file from s3
            #s3_client.download_file(bucket, Key, '/tmp/'+file_name)
            s3.Bucket(Bucket).download_file(S3Path, LocalPath)

            # sqs.put_message(
            # QueueUrl=statusqueue
            # ReceiptHandle=StatusReceipt
            # status='Ready to process'
            # )

            # Call ffmpy function
            segment(LocalPath)
            global destination

            # Each chunk is uploaded to s3
            FilePath, Extension = os.path.splitext(LocalPath)
            print "Uploading segments to s3..."
            for filename in os.listdir('/tmp/{}/{}*'.format(ConversionID, FilePath)):
                if !filename.endswith('.mp3'):
                    destination = 'Segmented/{}'.format(filename)
                    s3_client.upload_file('/tmp/'+filename, bucket, destination)
            print "Uploading audio to s3"
            audiodestination = 'Audio/{}'.format(file_name)
            s3_client.upload_file('{}.mp3'.format(FilePath), bucket, audiodestination)

            # Update status queue
            # sqs.put_message(
            # QueueUrl=statusqueue,
            # MessageID=MessageID
            # status='Processing'
            # )

        except Exception as e:
            print(e)
            print('ERROR! Key: {} Bucket: {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
            raise e


# ffmpy invocation that SEGMENTs the video into chunks
def segment(path):
    if path is not None:
        FilePath, Extension = os.path.splitext(path)
        f = ffmpy.FFmpeg(
                executable='./ffmpeg/ffmpeg',
                inputs={path : None},
                outputs={FilePath +'.mp3': '-c copy'}
                )
        ff = ffmpy.FFmpeg(
                executable='./ffmpeg/ffmpeg',
                inputs={path : None},
                outputs={'{}SEGMENT%d{}'.format(FilePath, Extension): '-acodec copy -c:a libfdk_aac -f segment -vcodec copy -reset_timestamps 1 -map 0'}
                )
        f.run()
        ff.run()

@@ -477,19 +477,47 @@
 Filename
- = 
+, Extension = os.path.splitext(
 Row%5B'Fil
@@ -523,16 +523,17 @@
 lename'%5D
+)
 %0A    Pat
@@ -591,16 +591,22 @@
 D'%5D%0A    
+Status
 QueueMes
@@ -654,16 +654,18 @@
  = %22%7B%7D%7B%7D
+%7B%7D
 %22.format
@@ -675,24 +675,35 @@
 th, Filename
+, Extension
 )%0A    LocalP
@@ -719,16 +719,18 @@
 mp/%7B%7D/%7B%7D
+%7B%7D
 %22.format
@@ -752,16 +752,27 @@
 Filename
+, Extension
 )%0A%0A    p
@@ -848,16 +848,22 @@
  print %22
+Status
 QueueMes
@@ -883,16 +883,22 @@
 .format(
+Status
 QueueMes
@@ -1331,25 +1331,24 @@
 _extension)%0A
-%0A
             
@@ -1602,32 +1602,33 @@
 mp/'+file_name)%0A
+%0A
             s3.B
@@ -1908,39 +1908,8 @@
 ath)
-%0A            global destination
 %0A%0A  
@@ -2049,16 +2049,26 @@
 egments 
+and audio 
 to s3...
@@ -2085,47 +2085,28 @@
     
-for filename in os.listdir('/tmp/
+destination = '
 %7B%7D/%7B%7D
-*
 '.fo
@@ -2114,38 +2114,24 @@
 mat(
-ConversionID, FilePath)):%0A    
+Path, Filename)%0A
     
@@ -2142,20 +2142,20 @@
     
-if !
+for 
 filename
 .end
@@ -2154,74 +2154,33 @@
 name
-.endswith('.mp3'):%0A                    destination = 'Segmented
+ in os.listdir('/tmp
 /%7B%7D
+/*
 '.fo
@@ -2188,22 +2188,24 @@
 mat(
-filename)%0A    
+ConversionID)):%0A
     
@@ -2248,201 +2248,44 @@
 tmp/
-'+filename, bucket, destination)%0A            print %22Uploading audio to s3%22%0A            audiodestination = 'Audio/%7B%7D'.format(file_name)%0A            s3_client.upload_file('%7B%7D.mp3'.format(FilePath
+%7B%7D/%7B%7D'.format(ConversionID, filename
 ), b
@@ -2291,21 +2291,16 @@
 bucket, 
-audio
 destinat
@@ -3025,33 +3025,16 @@
 c copy'%7D
-%0A                
 )%0A      
@@ -3290,33 +3290,16 @@
 -map 0'%7D
-%0A                
 )%0A      
@@ -3317,16 +3317,40 @@
        ff.run()%0A
+        os.remove(path)%0A

structure changes