#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#universal downloader
#author:Wos

#copy link,then run the script,no need args

import pyperclip
import os
import requests
import random
import time
import tkinter as tk
from tkinter import messagebox
import string

pxy = ""
tl = ""
xff = ""

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ini_path = os.path.join(BASE_DIR, "proxy.ini")
tracker_path = os.path.join(BASE_DIR, "trackers_all_ip.txt")
def random_ip():
    global xff
    a=random.randint(1,255)
    b=random.randint(1,255)
    c=random.randint(1,255)
    d=random.randint(1,255)
    xff = (str(a)+'.'+str(b)+'.'+str(c)+'.'+str(d))
    return
    
def vname_str():
    ran_str = ''.join(random.sample(string.ascii_letters, 8))
    return ran_str

def check():
    global pxy
    if not os.path.exists(ini_path):
        f=open(ini_path,"w",encoding="utf-8")
        f.close()
    else:
        f = open(ini_path,"r",encoding="utf-8")
        line = f.readline().strip()
        if line:
            pxy = "--all-proxy=\"http://"+line+"\""
        f.close()


def get_tracker_list():
    try:
        global tl
        url = "https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_ip.txt"
        hdr = {
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
            "X-Forwarded-For" : xff
        }
        res = requests.get(url,headers=hdr)
        temp = res.text.split("\n")
        for i in temp:
            if i != "":
                tl = tl+','+str(i)
        tl = str(tl).lstrip(',')
        f = f=open(tracker_path,"w",encoding="utf-8")
        f.write(tl)
        f.close()
        return
    except:
        random_ip()
        time.sleep(1)
        return get_tracker_list()

def check_tracker_list():
    global tl
    if not os.path.exists(tracker_path):
        get_tracker_list()
    else:
        sid = input("whether update trackerlistY/N?(N)")
        if sid == 'y' or sid == 'Y':
            get_tracker_list()
        else:
            f = open(tracker_path,"r",encoding="utf-8")
            line = f.readline().strip()
            if line:
                tl = line
            f.close()

def check_torrent_link(link):
    if "torrent" in str(link) or str(link).endswith('.torrent') or "Torrent" in str(link):
        try:
            print("filetype:torrent")
            res = requests.get(link,stream=True)
            fname = '/tmp/temp.torrent'
            with open(fname, 'wb') as f:
                for i in res.iter_content(chunk_size=1024):
                    f.write(i)
                f.close()
            print("torrent file downloaded")
            return True
        except:
            print("filetype:Normal_1")
            return False
    else:
        print("filetype:Normal_2")
        return False            

#check aria2c exist
def check_aria2c():
    temp = ""
    try:
        temp = (os.popen("aria2c --version").read())
    except:
        pass
    if str(temp).startswith("aria2 "):
        return True
    else:
        root=tk.Tk()
        root.withdraw()
        root.attributes('-topmost',True)                
        messagebox.showinfo(title="warn",message="no aria2c installed!")
        root.destroy()         
        return False




def mdown():
    os.system('clear')
    link = pyperclip.paste()
    if link:
        if str(link).startswith('http') or str(link).startswith('ftp'):
            sid = input("Enable Proxy Y/N?(N)")
            if sid == 'y' or sid == 'Y' and pxy != "":
                cmdline = 'aria2c --check-certificate=false --file-allocation=none \"'+link+'\" -c -x8 -s8 -k 1M --out='+vname_str()+pxy
                os.system(cmdline)
            else:
                if(check_torrent_link(link)):
                    check_tracker_list()
                    cmdline = 'aria2c -U80K --seed-time=0 --bt-tracker-connect-timeout=90 --bt-tracker-timeout=120 --bt-tracker-interval=60 --file-allocation=none \"/tmp/temp.torrent\" --bt-tracker='+tl
                else:
                    cmdline = 'aria2c --check-certificate=false --file-allocation=none \"'+link+'\" -c -x8 -s8 -k 1M --out='+vname_str()

                os.system(cmdline)

        elif str(link).startswith("magnet:?xt="):
            check_tracker_list()
            cmdline = 'aria2c -U80K --seed-time=0 --bt-tracker-connect-timeout=90 --bt-tracker-timeout=120 --bt-tracker-interval=60 --file-allocation=none \"'+link+'\" --bt-tracker='+tl
            os.system(cmdline)           

if __name__ == '__main__':
    if(check_aria2c()):
        check()
        mdown()