import re
import os
import time
import requests
from random import *
from tkinter import *
import tkinter.filedialog as fd
class Download():
    def __init__ (self, link):
        self.mainlink = link + '?p='
        self.allinks = []
        self.n = 0

    def randname(n):
        return ''.join(sample(''.join([chr(i)*randint(1,3) for i in range(97,123)])+ str(randint(11111,99999))*10, n))

    def rawlinks(self):
        allinks = []
        p = 0
        mainpage = requests.get(self.mainlink+str(p)).content.decode()
        number_of_pages = int(re.search(r'(?<=Images:<\/td><td\s{1}class=\"gdt2\">)(\d+)(?=\s{1}@)',mainpage).group())//40
        raw_links = re.findall(r'(?<=href=\")(http:\/\/g\.e-hentai.org\/s\/[a-z0-9\/-]+\d+\b)(?=\")',mainpage)
        while p <= number_of_pages+1:
            raw_links = re.findall(r'(?<=href=\")(http:\/\/g\.e-hentai.org\/s\/[a-z0-9\/-]+\d+\b)(?=\")',mainpage)
            for elem in raw_links:
                allinks+=elem.split(' ')
            raw_links = []
            mainpage = requests.get(self.mainlink+str(p)).content.decode()
            p+=1
        self.allinks = list(set(allinks))
        self.n = len(self.allinks)

    def load(self):
        j = 0
        try:
            while j <= self.n:
                page = requests.get(self.allinks[j]).content.decode()
                true_link = re.search(r'(?<=src=\")(http:\/\/\d{1,3}\.\d{1,3}\S+)(?=\"\s{1}st)', page).group()
                ext = re.search(r'(?<=\w{1}\.{1})([jpgnife]{3,4})(?=\b)',true_link).group()
                pic = requests.get(true_link).content
                time.sleep(1)
                f = open(Download.randname(16)+'.'+ ext,'wb')
                f.write(pic)
                f.close()
                j+=1
        except IndexError:
            pass
    
def copypast(e):
    lk=mainw.selection_get(selection='CLIPBOARD')
    mylink.insert(1, lk)
    
def opendir():
    f = fd.askdirectory()
    try:
        os.chdir(f)
    except: pass

def go():
    s = mylink.get()
    b2.configure(state='disabled')
    mylink.configure(state='disabled')
    d = Download(s)
    d.rawlinks()
    d.load()
    b2.configure(state='normal')
    mylink.configure(state='normal')
    mylink.delete(0,END)

mainw = Tk()
mainw.title('g.e-hentai.org downloader')
mainw.resizable(0,0)
mainw.geometry('300x240')

mylink = Entry(mainw,width=30)
text1 = Label(mainw, text='My link:',font=14)
text2 = Label(mainw,text='My folder:',font=14)
b = Button(text='...',height=1,width=22,command=opendir)
b2 = Button(height=6,width=18,bg='#80DAEB',text='Start',fg='purple',font=18,command=go)
b2.place(x=80,y=100)
b.place(x=90,y=45)
text1.place(x=8,y=10)
text2.place(x=8,y=48)
mylink.place(x=75,y=10)
mylink.bind(lambda event='<Control-v>' : copypast)

mainw.mainloop()