Created
April 7, 2018 07:37
-
-
Save ketankr9/c09fc939ffbca2b21bdf4111ae841bba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import requests | |
import json | |
from time import sleep | |
import sys | |
headers={'x-oc-api-key':'6483389d2fa2802b97196b6b54ff487e', 'Content-Type': 'application/json'} | |
data = {'input': [{'source': '', 'type': 'remote'}], 'conversion': [{'target': 'mobi'}]} | |
response = dict() | |
def download_file(url, filename): | |
filename = "".join(filename.split(".")[:-1]) + ".mobi" | |
print(url, filename.split(".")[:-1]) | |
# NOTE the stream=True parameter | |
try: | |
r = requests.get(url, stream=True) | |
except: | |
print(" Url Error Occured while downloading") | |
return False | |
with open(filename, 'wb') as f: | |
for chunk in r.iter_content(chunk_size=1024): | |
if chunk: # filter out keep-alive new chunks | |
f.write(chunk) | |
#f.flush() commented by recommendation from J.F.Sebastian | |
print("File Downloaded") | |
return True | |
def get_conversion_id(source): | |
global data | |
data["input"][0]["source"] = source | |
r = requests.post("https://api2.online-convert.com/jobs",data=json.dumps(data), headers=headers) | |
rText = json.loads(r.text) | |
return rText["id"] | |
def get_status(id): | |
c = requests.get("https://api2.online-convert.com/jobs/" + id, headers=headers) | |
cText = json.loads(c.text) | |
global response | |
response = cText | |
return cText["status"]["code"] | |
############################################################### | |
# NOTE: Main function | |
if len(sys.argv) == 1: | |
print "please specify a link" | |
exit(0) | |
id = get_conversion_id(sys.argv[1]) | |
status = get_status(id) | |
# print json.dumps(cText, indent=2, sort_keys=True) | |
while status != "completed" and status != "failed": | |
print status | |
status = get_status(id) | |
sleep(1) | |
print status | |
if status != "failed": | |
download_file(response["output"][0]["uri"], response["input"][0]["filename"] ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment