﻿# -*- coding: utf-8 -*-
import requests
import re
import json
from subprocess import call, check_output
from os.path import isfile
from aria2c_analyser import getMaxConnPerServer
import sys
from certifi import where


maxconn = getMaxConnPerServer()
if maxconn is None:
	print('aria2c Analysation failed')

mci = int(maxconn)
if mci > 16:
	if mci > 100:
		print('Respect, you have set a very high number in your aria2cMOD, I support that')
	else:
		print('Respect, you have must have modified version of aria2c')
else:
	print('Seems you have the original version of aria2c...')

if not len(sys.argv) == 2:
	print('ERROR: Incorrect number of arguments')
	exit(1)
	
url = sys.argv[1]
 
r = requests.get(url)


x = re.search(r'window\.cloudSettings =\{(.+)\};<', r.text, flags = re.DOTALL)

if x:
	json_text = '{'+x.group(1)+'}'
	json_text = json_text.replace(r'\x3c',r'\\x3b')
	#~ print(json_text)
	jso = json.loads(json_text)
	
	weblink_get_url = jso['dispatcher']['weblink_get'][0]['url']
	
	dl_token = jso['params']['tokens']['download']
	
	id = jso['request']['id']
	
	link = f'{weblink_get_url}/{id}?key={dl_token}'
	
	
	x = call(['aria2c', f'-s{maxconn}',f'-x{maxconn}', link])
	
	if x != 0:
		if x == 1:
			cacerts = where()
			#~ trying again with the certifi pem location
			call(['aria2c', f'-s{maxconn}',f'-x{maxconn}',f'--ca-certificate={cacerts}', link])

			
	
	