#!/usr/bin/env python3

import requests
import json
import hashlib

url = 'https://paste.opendev.org/json/'

# read input from stdin
data = '{ "name": "joe", "age": 55}'

def upload(data):
    try:
        content = json.dumps(data)

        # create JSON payload for new paste
        payload = {
            'language': 'text',
            'code': content,
            'private': False
            #'expire': '1day'
        }

        # send request to create new paste
        response = requests.post(url + '?method=pastes.newPaste', json=payload)

        status = response.status_code
        paste_id = response.json()['data']

        if status == 200:
            #print(f'JSON object uploaded to dpaste.com: {dpaste_url}')
            md5sum = hashlib.md5(content.encode('utf-8')).hexdigest()

            return {
                'service': 'url',
                'key': paste_id,
                'md5sum': md5sum,
                'name':  'opendev_' + paste_id + '_' + md5sum[:5]
            }
        else:
            return None
    except requests.exceptions.RequestException:
        return None
# we can get the paste back by:
## $ > curl -d '{"paste_id":819463}' -H 'Content-Type: application/json' https://paste.opendev.org/json/?method=pastes.getPaste  |jq .data.code
