deploy.py 5.08 KB
#-*- coding: utf-8 -*-
from flask import Flask, render_template, request, url_for
from iselenium import SeleniumInterface as SI
import random, json

app = Flask(__name__)

@app.route('/')
def main():
	return render_template(
		"form.html",
		bypass = False
	)

@app.route('/manual')
def manual():
	return render_template(
		"form.html",
		bypass = True
	)

@app.route('/pdf', methods = ['POST'])
def pdf():
	d = request.json
	plate = d['header']['patente']
	s = SI(SI.Chrome)

	answer = {
		"header" : {},
		"alineador" : {},
		"suspension" : d['suspension'],
		"frenos" : {},
		"trasero" : {},
		"gaseshumos" : {},
	}

	answer['header']['patente'] = plate.upper()

	try:
		answer = login(
			d['credenciales']['usuario'],
			d['credenciales']['contrasena'],
			s,
			answer
		)
	except:
		return "Error en el login."
	try:
		answer = gototec(s, answer)
	except:
		return f"Error yendo a las especificaciones técnicas del dominio '{plate}'."
	try:
		answer = readdata(s, answer)
	except:
		return f"Error leyendo datos de la patente '{plate}'."
	try:
		answer = rnddata(answer)
	except:
		return f"Error completando datos extra de la patente '{plate}'."

	print(answer)
	return json.dumps(answer)

def login(u, p, s, r):
	s.get("https://rto.cent.gov.ar/rto")

	login = s.find(SI.By.NAME, "j_username")
	s.write(login, u)

	psw = s.find(SI.By.NAME, "j_password")
	s.write(psw, p)

	button = s.find(SI.By.ID, "submit")
	button.click()

	reach = lambda s: s.find(SI.By.NAME, "j_username")

	login = attempt_do(reach, default = "?")(s)

	# login succeeded
	if login == "?":
		return r

	# still in login page
	else:
		raise Exception("Fallo del login")

def gototec(s, r):
	s.get("https://rto.cent.gov.ar/rto/RTO/listaDePlanillas")

	# children of parent of td with innerText = plate
	found = False
	while(found == False):
		try:
			columns = s.children(s.parent( s.find(SI.By.XPATH, f"//tr//td[text()='{r['header']['patente']}']") ))
			r['header']['fecha'], r['header']['hora'] = s.readElement(columns[4]).split(" ")
			found = True
		except:
			# next page
			s.find(SI.By.XPATH, "//a[text()='Siguiente']").click()
		

	# get all a tags and click the last one
	options = s.findFromElement(columns[-1], SI.By.TAG_NAME, "a", "1-")
	options[-1].click()

	# if last clickable is 'Datos Técnicos', click, else you are already there
	tec = s.find(SI.By.XPATH, "//a/span[@class='externo']/parent::*", "1-")[-1]

	if tec.get_attribute("innerText") == "ir a Datos Técnicos":
		tec.click()
	
	return r

def readdata(s, r):
	reach = lambda id: lambda s: s.readInput( s.find(s.By.ID, id) )

	# alineacion
	r['alineador']['eje_delantero'] = empty_for_question(attempt_do(reach("deriva"), default = "?")(s))

	# suspension
	for i in range(2):
		sus = {}
		sus[f'peso_estatico_{i + 1}'] = empty_for_question(attempt_do(reach(f"pesoBascula-{i}"), default = "?")(s))

		r['suspension'].update(sus)

	# frenos
	frenos = s.find(SI.By.XPATH, "//table[@class='tabla_ensayo']/tbody//tr[@class='odd' or @class='even']","1-4")
	for i in range(4):
		fre = {}
		fre[f'peso_estatico_{i + 1}'] = empty_for_question(attempt_do(reach(f"pesoBascula-{i}"), default = "?")(s))
		fre[f'fuerza_izquierda_{i + 1}'] = empty_for_question(attempt_do(reach(f"fuerzaIzq-{i}"), default = "?")(s))
		fre[f'fuerza_derecha_{i + 1}'] = empty_for_question(attempt_do(reach(f"fuerzaDer-{i}"), default = "?")(s))

		r['frenos'].update(fre)

	# freno trasero

	r['trasero']['peso_estatico'] = empty_for_question(attempt_do(reach(f"pesoBasculaEst-0"), default = "?")(s))
	r['trasero']['fuerza_izquierda'] = empty_for_question(attempt_do(reach(f"fuerzaIzqEst-0"), default = "?")(s))
	r['trasero']['fuerza_derecha'] = empty_for_question(attempt_do(reach(f"fuerzaDerEst-0"), default = "?")(s))
	r['trasero']['eje'] = empty_for_question(attempt_do(reach(f"nroEjeEst-0"), default = "?")(s))

	# gases y humos

	r['gaseshumos']['opacidad_logaritmica'] = empty_for_question(attempt_do(reach(f"opacidadLogaritmica"), default = "?")(s))
	r['gaseshumos']['co'] = empty_for_question(attempt_do(reach(f"co"), default = "?")(s))
	r['gaseshumos']['hc'] = empty_for_question(attempt_do(reach(f"hc"), default = "?")(s))

	return r

def rnddata(r):

	res = lambda: round(random.random() * 0.9 + 0.05, 2)
	ov = lambda: round(random.random() * 39 + 0.5, 2)

	for i in range(4):
		f = r['frenos']; j = i+1; gen = False
		# If any values were found, it means the axis exists, random values will be generated.
		if f[f'fuerza_izquierda_{j}'] != "?" or f[f'fuerza_derecha_{j}'] != "?" or f[f'peso_estatico_{j}'] != "?":
			gen = True
		
		f[f'resistencia_izquierda_{j}'] = res() if gen else "?"
		f[f'resistencia_derecha_{j}'] = res() if gen else "?"
		f[f'ovalidad_izquierda_{j}'] = ov() if gen else "?"
		f[f'ovalidad_derecha_{j}'] = ov() if gen else "?"
	
	return r

# Executes the lambda with the arguments, with try except
def attempt_do(f, default = "", error = ""):
	def inner(*args, **kwargs):
		try:
			return f(*args, **kwargs)
		except:
			if error != "":
				raise Exception(error)
			return default
	return inner

def empty_for_question(string):
	return "?" if string == "" else string

# Inicio del servicio
if __name__ == "__main__":
        app.run("0.0.0.0")