#!/usr/bin/env python
# NukeFS2: simplest shortener-based file cloud storage for Python 2.6+
# Chain storage version
# by Multiversum
# Note: it gets damn slow on large files so plz don't upload >1M files

from requests import get
from json import dumps, loads
from urllib import quote_plus, unquote_plus

CHUNKLEN=22000 #current TinyURL effective chunk length limitation

def upload(localpath):
	'Upload a file from localpath to cloud and get its access key'
	chunks = []
	with open(localpath, 'rb') as fileobj:
		while 1:
			data = fileobj.read(CHUNKLEN)
			if not data: break
			chunks.append(''.join(data.encode('base64').splitlines()))
		fileobj.close()
	baseurl = 'http://tinyurl.com/api-create.php?url='
	key = None
	for i in xrange(len(chunks),0,-1):
		chunkobj = {'data' : chunks[i-1], 'next' : key}
		encoded = quote_plus(dumps(chunkobj))
		key = get(baseurl+encoded).text[19:]
	return key
    
def download(key, localpath):
	'Download a file to localpath by its access key'
	with open(localpath, 'wb') as fileobj:
		while 1:
			data = get('http://tinyurl.com/'+key, allow_redirects=False).headers['location']
			if not data: break
			chunkobj = loads(unquote_plus(data))
			if not chunkobj['data']: break
			fileobj.write(chunkobj['data'].decode('base64'))
			if not chunkobj['next']: break
			key = chunkobj['next']
		fileobj.close()

if __name__ == '__main__': #usage example
	megakey = upload('uploaded.zip')
	print 'File access key: ', megakey
	download(megakey, 'downloaded.zip')
	print 'Downloaded.'
