# Sample code, software libraries, command line tools, proofs of concept, templates, or other related technology are provided as AWS Content or Third-Party Content under the AWS Customer Agreement, or the relevant written agreement between you and AWS (whichever applies). You should not use this AWS Content or Third-Party Content in your production accounts, or on production or other critical data. You are responsible for testing, securing, and optimizing the AWS Content or Third-Party Content, such as sample code, as appropriate for production grade use based on your specific quality control practices and standards. Deploying AWS Content or Third-Party Content may incur AWS charges for creating or using AWS chargeable resources, such as running Amazon EC2 instances or using Amazon S3 storage.

import boto3, os, shutil, tempfile, urllib.request

ipfs_gw_endpoint = os.environ["IPFS_GW_ENDPOINT"]
s3_target_bucket = os.environ["S3_TARGET_BUCKET"]

def handler(event, context):

    try:
        # IPFS CID and Filename must be passed to the function
        filename = event['queryStringParameters']['filename']
        cid = event['queryStringParameters']['cid']
        url = ipfs_gw_endpoint+"/ipfs/"+cid

        print("Downloading file with CID "+cid+" from "+url)
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req) as response:
            with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
                shutil.copyfileobj(response, tmp_file)
                print("Successfully saved file locally")
                print("Uploading "+filename+" to S3 bucket "+s3_target_bucket)
                s3_client = boto3.client('s3')
                s3_client.upload_file(tmp_file.name, s3_target_bucket, filename)

        msg = "Successfully uploaded "+filename+" from CID "+cid+" to S3 bucket "+s3_target_bucket
        print(msg)
        return msg

    except Exception as e:
        print(e)
        raise e


