def get_videos(event, context): table = get_table() try: response = table.scan() result = { "statusCode": 200, "body": json.dumps(response['Items'], indent=4, cls=DecimalEncoder), "headers": { "Access-Control-Allow-Origin": "*", } } except Exception as ex: print(ex) result = { 'statusCode': 501, 'body': { "Exception": str(ex) }, "headers": { "Access-Control-Allow-Origin": "*", } } return result
def edit_video(event, context): table = get_table() vid = event['pathParameters']['id'] s3 = boto3.client('s3') try: response = table.get_item(Key={ 'id': vid, }) old_metadata = response['Item'] metadata = json.loads(event['body']) locked_keys = ['id', 'name'] for key in locked_keys: metadata[key] = old_metadata[key] if not 'status' in metadata: metadata['status'] = old_metadata['status'] metadata['last_update'] = int(time.time()) tags = [] if 'tags' in metadata: tags = format_tags(metadata['tags']) s3.put_object_tagging(Bucket=get_config("videos", "inputBucket"), Key=metadata['id'], Tagging={"TagSet": tags}) response = s3.list_objects(Bucket=get_config("videos", "outputBucket"), Prefix=metadata['id']) for object in response['Contents']: response = s3.put_object_tagging(Bucket=get_config( "videos", "outputBucket"), Key=object['Key'], Tagging={"TagSet": tags}) res = table.put_item(Item=metadata) result = { "statusCode": 200, "body": json.dumps(metadata, indent=4, cls=DecimalEncoder), "headers": { "Access-Control-Allow-Origin": "*", } } except Exception as ex: print(ex) result = { 'statusCode': 501, 'body': json.dumps({"Exception": str(ex)}, indent=4), "headers": { "Access-Control-Allow-Origin": "*", } } return result
def get_video(event, context): table = get_table() vid = event['pathParameters']['id'] s3 = boto3.client('s3') try: response = table.get_item(Key={ 'id': vid, }) item = response['Item'] if item['status'] == "Ready": content = {} content['mp4'] = generate_cf_presigned_url(vid + '/' + vid + '.mp4') content['thumbnails'] = [] response = s3.list_objects(Bucket=get_config( "videos", "outputBucket"), Prefix=vid + '/thumbnails') for object in response['Contents']: content['thumbnails'].append( generate_cf_presigned_url(object['Key'])) content['hls'] = {} response = s3.list_objects(Bucket=get_config( "videos", "outputBucket"), Prefix=vid + '/hls1') for object in response['Contents']: if object['Key'].endswith(".m3u8"): filename = object['Key'].split('/')[-1] if filename.startswith("master_"): content['hls'][filename] = generate_cf_presigned_url( object['Key']) item['content'] = content result = { "statusCode": 200, "body": json.dumps(item, indent=4, cls=DecimalEncoder), "headers": { "Access-Control-Allow-Origin": "*", } } except Exception as ex: print(ex) result = { 'statusCode': 501, 'body': { "Exception": str(ex) }, "headers": { "Access-Control-Allow-Origin": "*", } } return result
def delete_video(event, context): table = get_table() s3 = boto3.client('s3') vid = event['pathParameters']['id'] try: response = table.get_item(Key={ 'id': vid, }) metadata = response['Item'] if metadata['status'] != "Uploading": response = s3.delete_object(Bucket=get_config( "videos", "inputBucket"), Key=metadata['id']) response = s3.list_objects(Bucket=get_config( "videos", "outputBucket"), Prefix=metadata['id']) for object in response['Contents']: response = s3.delete_object(Bucket=get_config( "videos", "outputBucket"), Key=object['Key']) response = table.delete_item(Key={ 'id': vid, }) metadata['status'] = "Removed" result = { "statusCode": 200, "body": json.dumps(metadata, indent=4, cls=DecimalEncoder), "headers": { "Access-Control-Allow-Origin": "*", } } except Exception as ex: print(ex) result = { 'statusCode': 501, 'body': { "Exception": str(ex) }, "headers": { "Access-Control-Allow-Origin": "*", } } return result
def update_video_status(event, context): table = get_table() job_id = event['detail']['jobId'] job_status = event['detail']['status'] statusCode = 200 body = {} try: response = table.scan(FilterExpression=Key('job_id').eq(job_id)) for item in response['Items']: if job_status == "COMPLETE": item['status'] = "Ready" elif job_status == "ERROR": item['status'] = "Error while transcoding" item['last_update'] = int(time.time()) result = table.put_item(Item=item) body = {'success': True} except Exception as ex: print(ex) statusCode = 500 body = {'error': str(ex)} raise finally: return { 'statusCode': statusCode, 'body': json.dumps(body), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
def upload_video(event, context): table = get_table() s3 = boto3.client('s3') try: upload_key = uuid.uuid4().hex metadata = json.loads(event['body']) if not 'name' in metadata: raise Exception("Missing name value") metadata['id'] = upload_key metadata['status'] = "Uploading" metadata['last_update'] = int(time.time()) res = table.put_item(Item=metadata) presigned_url = generate_s3_presigned_url( 'put_object', get_config("videos", "inputBucket"), upload_key) body = {"upload_url": presigned_url} return { "statusCode": 200, "body": json.dumps(body, indent=4), "headers": { "Access-Control-Allow-Origin": "*", } } except Exception as ex: print(ex) return { "statusCode": 500, 'body': json.dumps({"Exception": str(ex)}, indent=4), "headers": { "Access-Control-Allow-Origin": "*", } }
def convert_video(event, context): table = get_table() print('event', json.dumps(event)) sourceS3Bucket = event['Records'][0]['s3']['bucket']['name'] sourceS3Key = event['Records'][0]['s3']['object']['key'] sourceS3Key = urllib.parse.unquote(sourceS3Key) # mediaConvertRole = get_mediaconvert_role() mediaConvertRole = 'arn:aws:iam::129219767314:role/artclip-mediaconvert-job-role' region = 'ap-northeast-2' print('sourceS3Bucket', sourceS3Bucket) print('sourceS3Key', sourceS3Key) print('mediaConvertRole', mediaConvertRole) print('region', region) statusCode = 200 body = {} item = job = None mediainfo = None try: response = table.scan(FilterExpression=Key('title').eq(sourceS3Key)) print('Items', response['Items']) for item in response['Items']: item['status'] = "transcoding" # mediainfo = # # out_cnt = float(mediainfo[1]['Duration'])) / 30000.0 duration = int( float(item['mediainfo']['media']['track'][1]['Duration'])) cntJob = duration / 30 remain = duration % 30 create_job(sourceS3Bucket=sourceS3Bucket, sourceS3Key=sourceS3Key, mediaConvertRole=mediaConvertRole, region=region, table=table, item=item) # else: # resize_image(sourceS3Bucket=sourceS3Bucket, # sourceS3Key=sourceS3Key, # size='120x120') body = {'success': True} except Exception as ex: print('Exception', traceback.format_exc()) print('item', item) try: item['status'] = "error while transcoding" item['message'] = traceback.format_exc() result = table.put_item(Item=item) except Exception as ex: print('table Exception', ex) statusCode = 500 body = {'error': str(ex)} raise finally: return { 'statusCode': statusCode, 'body': json.dumps(body), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
def update_video_status(event, context): table = get_table() job_id = event['detail']['jobId'] job_status = event['detail']['status'] print('event', event) print('job_id', job_id) print('job_status', job_status) statusCode = 200 body = {} item = None try: response = table.scan(FilterExpression=Key('job_id').eq(job_id)) for item in response['Items']: if job_status == "COMPLETE": item['status'] = "ready" elif job_status == "ERROR": item['status'] = "error while transcoding" item['updated_at'] = int(time.time()) if job_status == "COMPLETE": bucket = 'artclip-output' item['event'] = event filePath = item['event']['detail']['outputGroupDetails'][2][ 'outputDetails'][0]['outputFilePaths'][0] path = filePath.replace('s3://{}/'.format(bucket), '') item['thumbnail'] = path content_id = item['id'] # update_member(content_id, path) print(content_id, path) print('item', item) result = table.put_item(Item=item) body = {'success': True} except Exception as ex: print('Exception', traceback.format_exc()) print('item', item) try: item['status'] = "error while transcoding" item['message'] = traceback.format_exc() result = table.put_item(Item=item) except Exception as ex: print('table Exception', ex) statusCode = 500 body = {'error': str(ex)} raise finally: return { 'statusCode': statusCode, 'body': json.dumps(body), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
def convert_video(event, context): table = get_table() sourceS3Bucket = event['Records'][0]['s3']['bucket']['name'] sourceS3Key = event['Records'][0]['s3']['object']['key'] destinationS3 = 's3://' + get_config( "videos", "outputBucket") + '/' + sourceS3Key + '/' mediaConvertRole = get_mediaconvert_role() region = get_config("deployment", "region") statusCode = 200 body = {} try: response = table.get_item(Key={ 'id': sourceS3Key, }) item = response['Item'] item['status'] = "Transcoding" # Use MediaConvert SDK UserMetadata to tag jobs with the assetID # Events from MediaConvert will have the assetID in UserMedata jobMetadata = {'assetID': sourceS3Key} # get the account-specific mediaconvert endpoint for this region mc_client = boto3.client('mediaconvert', region_name=region) endpoints = mc_client.describe_endpoints() # add the account-specific endpoint to the client session client = boto3.client('mediaconvert', region_name=region, endpoint_url=endpoints['Endpoints'][0]['Url'], verify=False) # Job settings are in the lambda zip file in the current working directory with open('job.json') as json_data: jobSettings = json.load(json_data) # Update the job settings with the source video from the S3 event and destination # paths for converted videos jobSettings['Inputs'][0][ 'FileInput'] = 's3://' + sourceS3Bucket + '/' + sourceS3Key jobSettings['OutputGroups'][0]['OutputGroupSettings'][ 'FileGroupSettings']['Destination'] = destinationS3 jobSettings['OutputGroups'][1]['OutputGroupSettings'][ 'HlsGroupSettings']['Destination'] = destinationS3 + 'hls1/master' jobSettings['OutputGroups'][2]['OutputGroupSettings'][ 'FileGroupSettings']['Destination'] = destinationS3 + 'thumbnails/' print('jobSettings:') print(json.dumps(jobSettings)) # Convert the video using AWS Elemental MediaConvert job = client.create_job(Role=mediaConvertRole, UserMetadata=jobMetadata, Settings=jobSettings) print(json.dumps(job, default=str)) item['job_id'] = job['Job']['Id'] item['last_update'] = int(time.time()) result = table.put_item(Item=item) body = {'success': True} except Exception as ex: print(ex) statusCode = 500 body = {'error': str(ex)} raise finally: return { 'statusCode': statusCode, 'body': json.dumps(body), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }