Source

gett-cli / gett.py

import json
import pprint
import datetime
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError

API_BASE = 'https://open.ge.tt/1/'
API_KEY = 't05kormjprb2o6rm8f8wmts2thjjor'

class APIError(Exception):
    pass

def _post_request(path, **kwargs):
    qskeys = {}
    url = API_BASE + path

    for key, value in kwargs.items():
        if key.startswith('_'):
            qskeys[key[1:]] = value
            del kwargs[key]

    if qskeys:
        url += '?' + urlencode(qskeys)

    input_data = json.dumps(kwargs).encode('utf-8')
    request = Request(url, input_data)

    return _request(request)

def _get_request(path, **kwargs):
    url = API_BASE + path

    if kwargs:
        url += '?' + urlencode(kwargs)

    request = Request(url)
    return _request(request)

def _request(req):
    try:
        resp = urlopen(req).read()
    except HTTPError as ex:
        resp = ex.read()
    
    result = json.loads(resp.decode('utf-8'))

    if "error" in result:
        raise APIError(result["error"])


    print(req.full_url + " -->")
    pprint.pprint(result)
    print()

    return result

class User(object):
    def _load(self, result):
        self.atoken = result['accesstoken']
        self.rtoken = result['refreshtoken']
        self.storage_used = result['user']['storage']['used']
        self.storage_limit = result['user']['storage']['limit']

    def login_auth(self, email, password):
        result = _post_request('users/login', apikey=API_KEY, email=email, password=password)
        self._load(result)

    def login_token(self, rtoken):
        result = _post_request('users/login', refreshtoken=rtoken)
        self._load(result)

    def list_shares(self, skip=None, limit=None):
        if skip is not None and limit is not None:
            results = _get_request('shares', accesstoken=self.atoken, skip=str(skip), limit=str(limit))
        else:
            results = _get_request('shares', accesstoken=self.atoken)

        for share_result in results:
             share = UserShare(self)
             share._load(share_result)
             yield share

    def create_share(self, title=None):
        if title is not None:
            result = _post_request('shares/create', _accesstoken=self.atoken, title=title)
        else:
            result = _post_request('shares/create', _accesstoken=self.atoken)

        share = UserShare(self)
        share._load(result)

        return share

class Share(object):
    def _load(self, result):
        self.name = result['sharename']
        self.title = result.get('title')
        self.created = datetime.datetime.fromtimestamp(result['created'])
        self.url = result.get('getturl')
        self.files = []
        
        for file_result in result['files']:
            f = File(self)
            f._load(file_result)

            self.files.append(f)

    def refresh(self):
        result = _get_request('shares/' + self.name)
        self._load(result)

class UserShare(Share):
    def __init__(self, user):
        self.user = user

    def update(self, **fields):
        result = _post_request('shares/' + self.name + '/update', _accesstoken=self.atoken, **fields)
        self._load(result)

    def destroy(self):
        _post_request('shares/' + self.name + '/destroy', _accesstoken=self.atoken)

    def create_file(self, filename):
        result = _post_request('files/' + self.name + '/create', _accesstoken=self.atoken, filename=filename)
        file = File(self)
        file._load(result)
        return file

class File(object):
    def __init__(self, share):
        self.share = share

    def _load(self, result):
        self.name = result['filename']
        self.id = result['fileid']
        self.downloads = result['downloads']
        self.readystate = result['readystate']
        self.created = datetime.datetime.fromtimestamp(result['created'])
        self.url = result.get('getturl')

        if 'upload' in result:
            self.put_url = result['upload']['puturl']
        else:
            self.put_url = None