Skip to content

Instantly share code, notes, and snippets.

@ketankr9
Created April 7, 2018 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ketankr9/c09fc939ffbca2b21bdf4111ae841bba to your computer and use it in GitHub Desktop.
Save ketankr9/c09fc939ffbca2b21bdf4111ae841bba to your computer and use it in GitHub Desktop.
#!/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