-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.py
More file actions
552 lines (493 loc) · 20 KB
/
main2.py
File metadata and controls
552 lines (493 loc) · 20 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import pyautogui
import time
import subprocess
import logging
import os
import psutil
from datetime import datetime
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from abc import ABC, abstractmethod
import pyperclip
import boto3
from botocore.exceptions import NoCredentialsError, ClientError
from dotenv import load_dotenv
load_dotenv()
# Configuração do logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('automation.log'),
logging.StreamHandler()
]
)
def kill_firefox_processes():
"""Mata todos os processos do Firefox"""
try:
for proc in psutil.process_iter(['pid', 'name']):
if 'firefox' in proc.info['name'].lower():
logging.info(f"Matando processo Firefox: PID {proc.info['pid']}")
proc.kill()
logging.info("Todos os processos Firefox foram encerrados")
return True
except Exception as e:
logging.error(f"Erro ao matar processos Firefox: {e}")
return False
@dataclass
class ActionConfig:
"""Configuração base para ações de automação"""
tipo: str
max_retries: int = 3
retry_delay: float = 2.0
class Action(ABC):
"""Classe base abstrata para ações de automação"""
def __init__(self, config: ActionConfig):
self.config = config
self.retry_count = 0
@abstractmethod
def execute(self) -> bool:
"""Executa a ação e retorna True se bem sucedida"""
pass
def retry(self) -> bool:
"""Tenta executar a ação novamente se falhar"""
if self.retry_count < self.config.max_retries:
self.retry_count += 1
time.sleep(self.config.retry_delay)
return self.execute()
return False
class ClickAction(Action):
def __init__(self, imagens: List[str], tempos_espera: List[float], config: ActionConfig, usar_ultimo: bool = False):
super().__init__(config)
self.imagens = imagens
self.tempos_espera = tempos_espera
self.IMAGENS_PASTA = 'imagens'
self.usar_ultimo = usar_ultimo
def execute(self) -> bool:
try:
for i, imagem in enumerate(self.imagens):
imagem_path = os.path.join(self.IMAGENS_PASTA, imagem)
if self.usar_ultimo:
todas_posicoes = list(pyautogui.locateAllOnScreen(imagem_path, confidence=0.9))
if todas_posicoes:
posicao = todas_posicoes[-1]
pyautogui.click(pyautogui.center(posicao))
logging.info(f"Botão '{imagem}' (último encontrado) clicado com sucesso.")
else:
logging.warning(f"Botão '{imagem}' não encontrado.")
return False
else:
button_location = pyautogui.locateOnScreen(imagem_path, confidence=0.9)
if button_location:
pyautogui.click(pyautogui.center(button_location))
logging.info(f"Botão '{imagem}' clicado com sucesso.")
else:
logging.warning(f"Botão '{imagem}' não encontrado.")
return False
if i < len(self.tempos_espera):
time.sleep(self.tempos_espera[i])
return True
except Exception as e:
logging.error(f"Erro ao clicar nos botões: {e}")
return False
class TypeAction(Action):
def __init__(self, texto: str, config: ActionConfig):
super().__init__(config)
self.texto = texto
def execute(self) -> bool:
try:
pyperclip.copy(self.texto)
pyautogui.hotkey('ctrl', 'v')
logging.info(f"Texto colado via clipboard: {self.texto}")
return True
except Exception as e:
logging.error(f"Erro ao colar texto: {e}")
return False
class KeyPressAction(Action):
def __init__(self, tecla: str, config: ActionConfig):
super().__init__(config)
self.tecla = tecla
def execute(self) -> bool:
try:
pyautogui.press(self.tecla)
logging.info(f"Tecla pressionada: {self.tecla}")
return True
except Exception as e:
logging.error(f"Erro ao pressionar tecla: {e}")
return False
class WaitAction(Action):
def __init__(self, tempo: float, config: ActionConfig):
super().__init__(config)
self.tempo = tempo
def execute(self) -> bool:
try:
time.sleep(self.tempo)
logging.info(f"Aguardando {self.tempo} segundos")
return True
except Exception as e:
logging.error(f"Erro ao aguardar: {e}")
return False
class ScreenshotAction(Action):
def __init__(self, nome: str, config: ActionConfig):
super().__init__(config)
self.nome = nome
def execute(self) -> bool:
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{self.nome}_.png"
path = os.path.join('screenshots', filename)
os.makedirs('screenshots', exist_ok=True)
screenshot = pyautogui.screenshot()
screenshot.save(path)
logging.info(f"Screenshot salvo como {path}")
return True
except Exception as e:
logging.error(f"Erro ao tirar screenshot: {e}")
return False
class CloseAction(Action):
def execute(self) -> bool:
try:
pyautogui.hotkey('ctrl', 'w')
time.sleep(2)
pyautogui.hotkey('ctrl', 'q')
logging.info("Navegador fechado com sucesso")
return True
except Exception as e:
logging.error(f"Erro ao fechar navegador: {e}")
return False
class UploadMinioAction(Action):
def __init__(self, config: ActionConfig):
super().__init__(config)
def execute(self) -> bool:
try:
from datetime import date
# monta data e nomes de arquivo
day = date.today()
data_completa = day.strftime("%Y-%m-%d")
secoes = "DO1 DO2 DO3 DO1E DO2E DO3E".split()
nomes_arquivos = [f"{data_completa}-{sec}.zip" for sec in secoes]
downloads_path = os.path.expanduser("~/Downloads")
# lê variáveis de ambiente (já carregadas pelo load_dotenv)
bucket = os.getenv("MINIO_BUCKET")
access = os.getenv("MINIO_ACCESS_KEY")
secret = os.getenv("MINIO_SECRET_KEY")
endpoint = os.getenv("MINIO_ENDPOINT")
if not all([bucket, access, secret, endpoint]):
logging.error("L Variáveis de ambiente do MinIO faltando.")
return False
# cria client S3/MinIO
s3 = boto3.client(
's3',
endpoint_url=endpoint,
aws_access_key_id=access,
aws_secret_access_key=secret
)
sucesso = True
for nome in nomes_arquivos:
caminho = os.path.join(downloads_path, nome)
if not os.path.exists(caminho):
logging.warning(f"Arquivo não encontrado: {caminho}")
sucesso = False
continue
logging.info(f"¡ Upload de {caminho} para {bucket}/{nome}...")
try:
s3.upload_file(Filename=caminho, Bucket=bucket, Key=nome)
logging.info(f" Upload de {nome} concluído.")
os.remove(caminho)
logging.info(f"=Ñ Arquivo local excluído: {caminho}")
except FileNotFoundError:
logging.error(f"L Arquivo não encontrado durante o upload: {caminho}")
sucesso = False
except NoCredentialsError:
logging.error("L Credenciais do MinIO não encontradas.")
sucesso = False
except ClientError as e:
logging.error(f"L Falha no upload (ClientError): {e}")
sucesso = False
except Exception as e:
logging.error(f"L Erro inesperado no upload: {e}")
sucesso = False
return sucesso
except Exception as e:
logging.error(f"L Erro geral no upload para o MinIO: {e}")
return False
class BaixarArquivosGraficoAction(Action):
def __init__(self, config: ActionConfig):
super().__init__(config)
def execute(self) -> bool:
try:
import time
from datetime import date
day = date.today()
ano = day.strftime("%Y")
mes = day.strftime("%m")
dia = day.strftime("%d")
data_completa = f"{ano}-{mes}-{dia}"
tipo_dou = "DO1 DO2 DO3 DO1E DO2E DO3E"
url_download = "https://inlabs.in.gov.br/index.php?p="
urls = [
f"{url_download}{data_completa}&dl={data_completa}-{dou_secao}.zip"
for dou_secao in tipo_dou.split()
]
for i, url in enumerate(urls):
# Seleciona a barra de endereços
pyautogui.hotkey('ctrl', 't') if i > 0 else pyautogui.hotkey('ctrl', 'l')
time.sleep(1)
pyperclip.copy(url)
pyautogui.hotkey('ctrl', 'v')
time.sleep(1)
pyautogui.press('enter')
time.sleep(5) # Ajuste conforme a velocidade do download
logging.info("Downloads via automação gráfica finalizados.")
return True
except Exception as e:
logging.error(f"Erro ao baixar arquivos via automação gráfica: {e}")
return False
class VerificarDownloadsAction(Action):
"""Verifica se pelo menos um arquivo foi baixado com sucesso"""
def __init__(self, config: ActionConfig):
super().__init__(config)
def execute(self) -> bool:
try:
from datetime import date
day = date.today()
data_completa = day.strftime("%Y-%m-%d")
secoes = "DO1 DO2 DO3 DO1E DO2E DO3E".split()
nomes_arquivos = [f"{data_completa}-{sec}.zip" for sec in secoes]
downloads_path = os.path.expanduser("~/Downloads")
arquivos_encontrados = []
for nome in nomes_arquivos:
caminho = os.path.join(downloads_path, nome)
if os.path.exists(caminho):
tamanho = os.path.getsize(caminho)
arquivos_encontrados.append((nome, tamanho))
logging.info(f"Arquivo encontrado: {nome} ({tamanho} bytes)")
if arquivos_encontrados:
logging.info(f"Download bem-sucedido! {len(arquivos_encontrados)} arquivo(s) baixado(s)")
return True
else:
logging.error("Nenhum arquivo foi baixado!")
return False
except Exception as e:
logging.error(f"Erro ao verificar downloads: {e}")
return False
class KillFirefoxAction(Action):
"""Mata todos os processos do Firefox"""
def __init__(self, config: ActionConfig):
super().__init__(config)
def execute(self) -> bool:
return kill_firefox_processes()
class AutomationManager:
"""Gerenciador principal de automação"""
def __init__(self, config: Dict[str, Any]):
self.config = config
self.screenshot_dir = 'screenshots'
os.makedirs(self.screenshot_dir, exist_ok=True)
def take_screenshot(self, name: str = 'screenshot') -> str:
"""Tira um screenshot e retorna o caminho do arquivo"""
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{name}_{timestamp}.png"
path = os.path.join(self.screenshot_dir, filename)
screenshot = pyautogui.screenshot()
screenshot.save(path)
logging.info(f"Screenshot salvo como {path}")
return path
except Exception as e:
logging.error(f"Erro ao tirar screenshot: {e}")
return ""
def execute_action(self, action: Action) -> bool:
"""Executa uma ação com sistema de retry"""
success = action.execute()
if not success:
success = action.retry()
return success
def run_sequence(self, sequence: List[Dict[str, Any]]) -> None:
"""Executa uma sequência de ações"""
try:
for action_config in sequence:
# Cria a configuração base com o tipo da ação
base_config = {'tipo': action_config['tipo']}
# Atualiza com configurações específicas se existirem
if 'config' in action_config:
base_config.update(action_config['config'])
config = ActionConfig(**base_config)
if action_config['tipo'] == 'clicar':
usar_ultimo = action_config.get('usar_ultimo', False)
action = ClickAction(
action_config['imagens'],
action_config.get('tempos_espera', []),
config,
usar_ultimo=usar_ultimo
)
elif action_config['tipo'] == 'digitar':
action = TypeAction(action_config['texto'], config)
elif action_config['tipo'] == 'pressionar_tecla':
action = KeyPressAction(action_config['tecla'], config)
elif action_config['tipo'] == 'esperar':
action = WaitAction(action_config['tempo'], config)
elif action_config['tipo'] == 'tirar_screenshot':
action = ScreenshotAction(action_config['nome'], config)
elif action_config['tipo'] == 'fechar':
action = CloseAction(config)
elif action_config['tipo'] == 'upload_minio':
action = UploadMinioAction(config)
elif action_config['tipo'] == 'baixar_arquivos_grafico':
action = BaixarArquivosGraficoAction(config)
elif action_config['tipo'] == 'verificar_downloads':
action = VerificarDownloadsAction(config)
elif action_config['tipo'] == 'matar_firefox':
action = KillFirefoxAction(config)
else:
logging.error(f"Tipo de ação desconhecido: {action_config['tipo']}")
continue
if not self.execute_action(action):
logging.error(f"Falha na execução da ação: {action_config}")
# Se a ação falhou, mata o Firefox antes de sair
logging.info("Matando Firefox devido a falha na execução...")
kill_firefox_processes()
break
except Exception as e:
logging.error(f"Erro inesperado durante a execução: {e}")
# Em caso de erro inesperado, também mata o Firefox
logging.info("Matando Firefox devido a erro inesperado...")
kill_firefox_processes()
def main():
# Configuração inicial
config = {
'browser': {
'command': ['firefox', '--no-sandbox'],
'url': 'http://ip-api.com/json'
}
}
# Variáveis de ambiente para login e senha
INLABS_LOGIN = os.getenv("INLABS_LOGIN", "")
INLABS_PASSWORD = os.getenv("INLABS_PASSWORD", "")
# Inicializa o gerenciador
manager = AutomationManager(config)
try:
# Abre o navegador
try:
subprocess.Popen(config['browser']['command'] + [config['browser']['url']])
logging.info("Navegador iniciado.")
except Exception as e:
logging.error(f"Erro ao iniciar o navegador: {e}")
return
time.sleep(5)
pyautogui.hotkey('ctrl', 'shift', 'a')
time.sleep(2)
# Sequência de ações para login no INLABS
sequence = [
{
'tipo': 'clicar',
'imagens': ['bt.png'],
'tempos_espera': [5],
'config': {'max_retries': 3, 'retry_delay': 2.0}
},
{
'tipo': 'clicar',
'imagens': ['bt1.png'],
'tempos_espera': [5],
'config': {'max_retries': 3, 'retry_delay': 2.0}
},
{
'tipo': 'clicar',
'imagens': ['bt2.png'],
'tempos_espera': [3],
'config': {'max_retries': 3, 'retry_delay': 2.0}
},
{
'tipo': 'digitar',
'texto': 'https://inlabs.in.gov.br/acessar.php',
'config': {'max_retries': 2, 'retry_delay': 1.0}
},
{
'tipo': 'pressionar_tecla',
'tecla': 'enter',
'config': {'max_retries': 2, 'retry_delay': 1.0}
},
{
'tipo': 'esperar',
'tempo': 25,
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'clicar',
'imagens': ['bt_login.png'],
'tempos_espera': [1],
'usar_ultimo': True,
'config': {'max_retries': 3, 'retry_delay': 1.0}
},
{
'tipo': 'digitar',
'texto': INLABS_LOGIN,
'config': {'max_retries': 2, 'retry_delay': 0.5}
},
{
'tipo': 'clicar',
'imagens': ['bt_senha.png'],
'tempos_espera': [1],
'usar_ultimo': True,
'config': {'max_retries': 3, 'retry_delay': 1.0}
},
{
'tipo': 'digitar',
'texto': INLABS_PASSWORD,
'config': {'max_retries': 2, 'retry_delay': 0.5}
},
{
'tipo': 'clicar',
'imagens': ['bt_logar.png'],
'tempos_espera': [2],
'config': {'max_retries': 3, 'retry_delay': 1.0}
},
{
'tipo': 'tirar_screenshot',
'nome': 'screenshot_final',
'config': {'max_retries': 2, 'retry_delay': 1.0}
},
{
'tipo': 'esperar',
'tempo': 10,
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'baixar_arquivos_grafico',
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'verificar_downloads',
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'esperar',
'tempo': 20,
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'fechar',
'config': {'max_retries': 2, 'retry_delay': 1.0}
},
{
'tipo': 'upload_minio',
'config': {'max_retries': 1, 'retry_delay': 0.0}
},
{
'tipo': 'matar_firefox',
'config': {'max_retries': 1, 'retry_delay': 0.0}
}
]
# Executa a sequência completa
manager.run_sequence(sequence)
except KeyboardInterrupt:
logging.info("Processo interrompido pelo usuário")
kill_firefox_processes()
except Exception as e:
logging.error(f"Erro crítico no programa principal: {e}")
kill_firefox_processes()
finally:
# Garante que o Firefox seja fechado mesmo se houver erro
logging.info("Finalizando programa...")
kill_firefox_processes()
if __name__ == "__main__":
main()