Commits

mickael9  committed 2bd77b6

First working version :-)

  • Participants
  • Parent commits 6d7f01b

Comments (0)

Files changed (2)

 import json
 import pprint
 import datetime
+import threading
+import os.path
+
 from urllib.request import urlopen, Request
 from urllib.parse import urlencode
 from urllib.error import HTTPError
+from urllib.parse import urlparse
+
+from http.client import HTTPConnection
 
 API_BASE = 'https://open.ge.tt/1/'
 API_KEY = 't05kormjprb2o6rm8f8wmts2thjjor'
+DEBUG = False
 
 class APIError(Exception):
     pass
     qskeys = {}
     url = API_BASE + path
 
-    for key, value in kwargs.items():
+    for key, value in list(kwargs.items()):
         if key.startswith('_'):
             qskeys[key[1:]] = value
             del kwargs[key]
         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()
+    if DEBUG:
+        print(req.full_url + " -->")
+        pprint.pprint(result)
+        print()
 
     return result
 
              share._load(share_result)
              yield share
 
+    def get_share(self, name):
+        result = _get_request('shares/' + self.name)
+
+        share = UserShare(self)
+        share._load(result)
+
+        return share
+
     def create_share(self, title=None):
         if title is not None:
             result = _post_request('shares/create', _accesstoken=self.atoken, title=title)
         return share
 
 class Share(object):
+    def __init__(self, name):
+        self.name = name
+        self.refresh()
+
     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)
 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)
+        result = _post_request('shares/' + self.name + '/update', _accesstoken=self.user.atoken, **fields)
         self._load(result)
 
     def destroy(self):
-        _post_request('shares/' + self.name + '/destroy', _accesstoken=self.atoken)
+        _post_request('shares/' + self.name + '/destroy', _accesstoken=self.user.atoken)
 
     def create_file(self, filename):
-        result = _post_request('files/' + self.name + '/create', _accesstoken=self.atoken, filename=filename)
+        result = _post_request('files/' + self.name + '/create', _accesstoken=self.user.atoken, filename=filename)
         file = File(self)
         file._load(result)
         return file
         else:
             self.put_url = None
 
+    def refresh(self):
+        result = _get_request('files/' + self.share.name + '/' + str(self.id))
+        self._load(result)
+
+class FileUploader(threading.Thread):
+    def __init__(self, file, fp):
+        super().__init__()
+
+        self.file = file
+        self.fp = fp
+        self.file_size = os.path.getsize(fp.name)
+        self.percent_done = 0
+
+    def run(self):
+        parsed = urlparse(self.file.put_url)
+        conn = HTTPConnection(parsed.netloc)
+        conn.connect()
+        conn.putrequest('PUT', parsed.path + (('?' + parsed.query) if parsed.query else ''))
+        conn.putheader('Content-Length', str(self.file_size))
+        conn.endheaders()
+
+        bytes_written = 0
+
+        while bytes_written != self.file_size:
+            data = self.fp.read(4096)
+            conn.sock.sendall(data)
+            bytes_written += len(data)
+
+            self.percent_done = bytes_written * 100 / self.file_size
+
+        resp = conn.getresponse()
+
+        print(resp)
+        print(resp.read())
+#!/usr/bin/env python
+
+import sys, os, os.path
+import argparse
+
+from gett import *
+from time import sleep
+
+home = os.getenv('USERPROFILE') or os.getenv('HOME')
+
+parser = argparse.ArgumentParser(description="A simple ge.tt uploader")
+parser.add_argument('file', nargs='+', type=argparse.FileType('rb'), help="Name of the file to upload")
+parser.add_argument('-t', dest='title', help='Title of the share (defaults to first file name)')
+parser.add_argument('-s', dest='share', help='Name of the share to upload to (defaults to a newly created one)')
+parser.add_argument('-e', dest='email', help='Email to login with')
+parser.add_argument('-p', dest='password', help='Password to login with')
+parser.add_argument('-k', dest='tokenfile', help='Ge.tt token file path (~/.gett-token)', default=os.path.join(home, '.gett-token'))
+
+args = parser.parse_args()
+
+
+user = User()
+try:
+    # Try to log-in with the token
+
+    token = open(args.tokenfile, 'r').read()
+    user.login_token(token)
+except:
+    # If it doesn't work, ask the user its email and password
+
+    if not args.email:
+        args.email = input('Please enter your Ge.tt email : ')
+
+    if not args.password:
+        args.password = input('Please enter your Ge.tt password : ')
+
+    try:
+        user.login_auth(args.email, args.password)
+    except Exception as ex:
+        print('Unable to login : %s' % ex.args[0])
+        sys.exit(1)
+
+with open(args.tokenfile, 'w') as file:
+    file.write(user.rtoken)
+
+if args.share:
+    share = user.get_share(args.share)
+else:
+    if args.title:
+        share = user.create_share(args.title)
+    else:
+        share = user.create_share(os.path.basename(args.file[0].name))
+
+uploaders = []
+
+for fp in args.file:
+    name = os.path.basename(fp.name)
+    file = share.create_file(name)
+
+    print('%s : %s' % (name, file.url))
+
+    uploader = FileUploader(file, fp)
+    uploader.start()
+    uploaders.append(uploader)
+
+finished = False
+
+while not finished:
+    finished = True
+
+    for upl in uploaders:
+        if not upl.is_alive():
+            continue
+
+        finished = False
+
+        print('%s : %d %%' % (upl.file.name, upl.percent_done))
+
+    sleep(1)
+
+for upl in uploaders:
+    upl.join()
+
+print('Done !')