deploy.py
6.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#-*- coding: utf-8 -*-
from flask import Flask, render_template, request, url_for, make_response, redirect
from iselenium import SeleniumInterface as SI
import random, json, os
app = Flask(__name__)
def create():
if not os.path.exists("users.json"):
with open("users.json", "+w") as f:
f.write("{}")
def usersave(usr, psw):
create()
content = ""
with open("users.json", "r") as u:
content = u.read()
with open("users.json", "w") as u:
try:
content = json.loads(content)
except:
content = {}
content[usr] = psw
u.write( json.dumps(content) )
def userget(usr):
create()
content = ""
with open("users.json", "r") as u:
content = u.read()
try:
return json.loads(content)[usr]
except:
return None
@app.route('/')
def main():
if "login" in request.cookies:
return render_template(
"form.html",
bypass = False
)
else:
return redirect(url_for("login"))
@app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == "GET":
return render_template(
"login.html"
)
else:
try:
s = SI(SI.Chrome)
r = make_response(
json.dumps(
login(
request.json['usuario'],
request.json['contrasena'],
s
)
)
)
r.set_cookie(
"login",
request.json['usuario'],
60 * 60 * 8,
httponly = True
)
usersave(
request.json['usuario'],
request.json['contrasena']
)
s.driver.close()
return r
except:
s.driver.close()
return "Error en el login"
@app.route('/manual')
def manual():
return render_template(
"form.html",
bypass = True
)
@app.route('/pdf', methods = ['POST'])
def pdf():
if "login" not in request.cookies:
return redirect(url_for("login"))
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:
login(
request.cookies["login"],
userget(
request.cookies["login"]
),
s
)
except:
s.driver.close()
return f"Error en el login"
try:
answer = gototec(s, answer)
except:
s.driver.close()
return f"Error yendo a las especificaciones técnicas del dominio '{plate}'."
#try:
answer = readdata(s, answer)
#except:
#s.driver.close()
#return f"Error leyendo datos de la patente '{plate}'."
try:
answer = rnddata(answer)
except:
s.driver.close()
return f"Error completando datos extra de la patente '{plate}'."
s.driver.close()
return json.dumps(answer)
def login(u, p, s):
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()
login = _attempt(lambda s: s.find(SI.By.NAME, "j_username"), "?")(s)
# login succeeded
if login == "?":
return True
# 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'] = _e2q(_attempt( reach("deriva"), "?" )(s))
# suspension
sus = r['suspension']
for i in range(2):
# si valores de rendimiento son numeros, leer el peso
if sus[f'rendimiento_izquierdo_{i + 1}'].isnumeric() or sus[f'rendimiento_derecho_{i + 1}'].isnumeric():
sus[f'peso_estatico_{i + 1}'] = _e2q(_attempt( reach(f"pesoBascula-{i}"), "?" )(s))
else:
sus[f'rendimiento_izquierdo_{i + 1}'] = "?"
sus[f'rendimiento_derecho_{i + 1}'] = "?"
sus[f'peso_estatico_{i + 1}'] = "?"
r['suspension'].update(sus)
# frenos
for i in range(4):
fre = {}
fre[f'peso_estatico_{i + 1}'] = _e2q(_attempt( reach(f"pesoBascula-{i}"), "?" )(s))
fre[f'fuerza_izquierda_{i + 1}'] = _e2q(_attempt( reach(f"fuerzaIzq-{i}"), "?" )(s))
fre[f'fuerza_derecha_{i + 1}'] = _e2q(_attempt( reach(f"fuerzaDer-{i}"), "?" )(s))
r['frenos'].update(fre)
# freno trasero
r['trasero']['peso_estatico'] = _e2q(_attempt( reach(f"pesoBasculaEst-0"), "?" )(s))
r['trasero']['fuerza_izquierda'] = _e2q(_attempt( reach(f"fuerzaIzqEst-0"), "?" )(s))
r['trasero']['fuerza_derecha'] = _e2q(_attempt( reach(f"fuerzaDerEst-0"), "?" )(s))
r['trasero']['eje'] = _e2q(_attempt( reach(f"nroEjeEst-0"), "?" )(s))
# gases y humos
r['gaseshumos']['opacidad_logaritmica'] = _e2q(_attempt( reach(f"opacidadLogaritmica"), "?" )(s))
r['gaseshumos']['co'] = _e2q(_attempt( reach(f"cantCO"), "?" )(s))
r['gaseshumos']['hc'] = _e2q(_attempt( reach(f"cantHC"), "?" )(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(f, default = "", error = ""):
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
if error != "":
raise Exception(error)
return default
return inner
def _e2q(string):
return "?" if string == "" else string
# Inicio del servicio
if __name__ == "__main__":
app.run("0.0.0.0")