# MIT license # Created by Steven Smith (blha303) 2013 import urllib2, urllib import json import base64 API_URL = "https://mediacru.sh/api/" def info(hash): """ Returns dict: * compression: float representing amount of compression achieved * files: list containing dicts: * file: string, url of file * type: string, mime type of file. can be "video/mp4", "video/ogg", "image/gif" * original: string, url of original file * type: string, mime type of original file """ return json.loads(urllib2.urlopen(API_URL + hash).read()) def info_list(hashlist): """ Returns dict: * : dict of info, or None if hash isn't valid. see info() docs """ return json.loads(urllib2.urlopen(API_URL + "info?list=" + ",".join(hashlist)).read()) def exists(hash): """ Returns boolean """ return json.loads(urllib2.urlopen(API_URL + hash + "/exists").read())["exists"] def delete(hash): """ Returns dict: Either * status: string, always "success", meaning: The IP matches the stored hash and the file was deleted. or * error: integer, error code. 401 = The IP does not match the stored hash. 404 = There is no file with that hash. """ try: return json.loads(urllib2.urlopen(API_URL + hash + "/delete").read())["status"] except urllib2.HTTPError as e: return json.loads(e.read()) def status(hash): """ Returns dict: Either * status: string, one of four values: "done": The file has been processed. "processing": The file is being processed or in the processing queue. "error": The processing step finished early with an abnormal return code. "timeout": The file took too long to process. or * error: integer, error code. 404 = There is no file with that hash. """ try: return json.loads(urllib2.urlopen(API_URL + hash + "/status").read()) except urllib2.HTTPError as e: return json.loads(e.read()) def upload(address, url=True): """ Returns dict: Either * hash: string, resulting image hash or * error: integer, error code 409 = The file was already uploaded. 420 = The rate limit was exceeded. Enhance your calm. 415 = The file extension is not acceptable. * hash: string, resulting image hash, if error code is 409 """ if url: try: return json.loads(urllib2.urlopen(API_URL + "upload/url", urllib.urlencode({'url': address})).read()) except urllib2.HTTPError as e: return json.loads(e.read()) else: # untested with open(address, "rb") as f: encoded_file = base64.b64encode(f.read()) params = urllib.urlencode({'file': encoded_file}) request = urllib2.Request(API_URL + "upload/file", params) request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8") try: return json.loads(urllib2.urlopen(request).read()) except urllib2.HTTPError as e: return json.loads(e.read())