main.py
10.5 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#-*- 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, datetime, ingenieros,apollo, fosadiaria
import configuracion
ing = ingenieros.ingenieros()
FozaDiaria = fosadiaria.FosaDiaria()
app = Flask(__name__)
def create():
if not os.path.exists("data/users.json"):
with open("data/users.json", "+w") as f:
f.write("{}")
def usersave(usr, psw):
create()
content = ""
with open("data/users.json", "r") as u:
content = u.read()
with open("data/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("data/users.json", "r") as u:
content = u.read()
try:
return json.loads(content)[usr]
except:
return None
@app.route('/')
def main():
if "login" not in request.cookies:
return redirect(url_for("login"))
return render_template(
"form.html",
bypass = False
)
@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.quit()
return r
except Exception as E:
#s.driver.quit()
TratarCerrarNabegador(s)
return f"Error en el login {str(E)}"
def TratarCerrarNabegador(s):
try:
s.driver.quit()
except:
pass
@app.route('/manual')
def manual():
if ("login" not in request.cookies) and configuracion.ManualLogin:
return redirect(url_for("login"))
return render_template(
"form.html",
bypass = True
)
@app.route('/anomalies', methods = ['POST'])
def anomalies():
if "login" not in request.cookies:
return redirect(url_for("login"))
d = request.json
plate = d['header']['patente']
s = SI(SI.Chrome)
anom = {
"header" : {
"patente" : plate
}
}
try:
login(
request.cookies["login"],
userget(
request.cookies["login"]
),
s
)
except:
s.driver.quit()
return f"Error en el login"
fingfd = FozaDiaria.BuscarDatosDominio(plate.upper(),selenium=s)
try:
gototec(s, d)
except:
s.driver.quit()
return f"Error yendo a las especificaciones técnicas del dominio '{plate}'."
try:
anom = fetchAnomalies(s, anom)
except:
s.driver.quit()
return f"Fallo en la recolección de anomalías del dominio '{plate}'."
try:
anom = gotoadmin(s, anom)
except:
return f"Error yendo a los datos administrativos del dominio '{plate}'."
s.driver.quit()
anom['header']['patente'] = plate
anom['header']['fecha'] = datetime.datetime.now().strftime("%d/%m/%Y")
anom['header']["hora"] = str(fingfd)
return render_template("anomalies.html", anomalies = anom)
@app.route('/report', methods = ['POST'])
def report():
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" : {},
"ruido":{},
}
answer['header']['patente'] = plate.upper()
answer['header']["fecha-hora"] = apollo.estaticos.FechaHora()
#print(1,answer)
answer['header']["ingeniero"] = ing.LeerDatosUsuario(request.cookies["login"])['nombreyapellido']
#answer['header']["hora"] = apollo.estaticos.Hora()
#print(2,answer)
try:
login(
request.cookies["login"],
userget(
request.cookies["login"]
),
s
)
except:
s.driver.quit()
return f"Error en el login"
fingfd = FozaDiaria.BuscarDatosDominio(plate.upper(),selenium=s)
#print(3,answer)
try:
answer = gototec(s, answer)
except Exception as E:
s.driver.quit()
return f"Error yendo a las especificaciones técnicas del dominio '{plate}'. {str(E)}"
try:
answer = readdata(s, answer)
except Exception as E:
s.driver.quit()
print(answer)
print(s)
return f"Error leyendo datos de la patente '{plate}' {str(E)}."
#try:
# answer = rnddata(answer)
#except:
# s.driver.quit()
# return f"Error completando datos extra de la patente '{plate}'."
#print(answer)
answer['header']["hora"] = str(fingfd)
s.driver.quit()
print("report",answer)
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 = s.find(SI.By.NAME, "j_username")
# login succeeded
if login == None:
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
# Assumes already in tec
def gotoadmin(s, r):
s.find(SI.By.XPATH, "//a/span[@class='externo']/parent::*", "1-")[0].click()
s.find(SI.By.XPATH, "//a[@href='#titularOperador']").click()
rsocial = s.find(SI.By.XPATH, "//div[@id='datosOperador']//fieldset[2]/div")
cp = s.find(SI.By.XPATH, "//div[@id='datosOperador']//fieldset[3]/div[4]")
r['header']['rsocial'] = rsocial.get_attribute("innerText").split(":")[1].strip()
r['header']['cp'] = cp.get_attribute("innerText").split(":")[1].strip()
return r
######################Cambio DBA ruido
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))
fre[f'diferencia_freno_{i + 1}'] = s.traerTextDiv(f"remotoDivDiferencia-{i}")
fre[f'eficacia_freno_{i + 1}'] = s.traerTextDiv(f"remotoDivEficiencia-{i}")
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))
r["trasero"][f'eficacia_freno_mano'] = s.traerTextDiv(f"remotoDivEficienciaEst-0")
r["trasero"][f'diferencia_freno_mano'] = s.traerTextDiv(f"remotoDivDiferenciaEst-0")
# 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))
#Nivel sonoro
try:
r['ruido']["nivelsonoro"] = _e2q(_attempt( reach(f"extEscape"), "?" )(s))
except Exception as E:
print("""###Error a traer datos de nivel sonoro###""")
print(E)
print("""###Error a traer datos de nivel sonoro###""")
#print(r)
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
def fetchAnomalies(s, r):
def checked(Maybe_checkbox):
if Maybe_checkbox == None:
return False
return Maybe_checkbox.is_selected()
def severity(row):
hig = s.findFromElement(row[1], SI.By.XPATH, "input[@type='checkbox']")
med = s.findFromElement(row[2], SI.By.XPATH, "input[@type='checkbox']")
if checked(hig):
return "Grave"
elif checked(med):
return "Moderada"
else:
return "Leve"
def anomalyType(row):
return row[4].get_attribute('innerText').split('>')[0].strip()
def description(row):
textarea = s.findFromElement(row[5], SI.By.TAG_NAME, "textarea")
return textarea.get_attribute("value")
result = {}
# Click Anomalies tab
s.find(SI.By.ID, "ui-id-2").click()
# Anomaly table, if one exists
rows = s.children( s.find(SI.By.XPATH, "//div[@id='tableAnomaliaRevisionGuardadaDiv']/div/div/table/tbody") )
if rows == None:
return r
# Complete return data
for row in rows:
c = s.children(row)
t = anomalyType(c)
if t not in result:
result[t] = []
result[ t ].append({
'severity' : severity(c),
'description' : description(c)
})
r['anomalies'] = result
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", port=configuracion.port)