bcpkgfox 0.16.54__tar.gz → 0.16.56__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bcpkgfox might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bcpkgfox
3
- Version: 0.16.54
3
+ Version: 0.16.56
4
4
  Summary: Biblioteca BCFOX
5
5
  Home-page: https://github.com/robotsbcfox/PacotePythonBCFOX
6
6
  Author: Guilherme Neri
@@ -456,6 +456,6 @@ def move_mouse_smoothly(element, click=False):
456
456
  RESET, GR, ORANGE, DK_ORANGE = "\033[0m", "\033[38;5;34m", "\033[38;5;214m", "\033[38;5;130m"
457
457
  result = subprocess.run(['pip', 'show', "bcpkgfox"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
458
458
  version_line = next((line for line in result.stdout.decode().splitlines() if line.startswith('Version:')), None)
459
- try: print(f"\n\n{ORANGE}Biblioteca BCFOX importada - {re.sub(r"[^0-9.b]", "", version_line)}{RESET}")
459
+ try: print(f"\n\n{ORANGE}Biblioteca BCFOX importada - {re.sub(r'[^0-9.b]', '', version_line)}{RESET}")
460
460
  except: pass
461
461
  create_dirs()
@@ -0,0 +1,430 @@
1
+ from typing import Optional
2
+ import time
3
+
4
+ def invoke_api_list(link: str, token: str, method: Optional[str] = "GET", headers: Optional[str] = None, print_response: Optional[bool] = False) -> dict:
5
+ import requests
6
+
7
+ """
8
+ Exemplo de uso abaixo:
9
+
10
+ import BCFOX as bc
11
+
12
+ def invoke_api_list(self):
13
+ link = 'https://linK_api.com.br/apis/{parametros}'
14
+ token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
15
+
16
+ bc.invoke_api_list(link, token, print_response=True)
17
+
18
+ OBS: o print_response vem por padrão desligado, caso você queira ativa o print da view coloque 'ON'
19
+
20
+ """
21
+ http_methods = {
22
+ "POST": requests.post,
23
+ "GET": requests.get,
24
+ "PUT": requests.put,
25
+ "DELETE": requests.delete,
26
+ "PATCH": requests.patch
27
+ }
28
+
29
+ # Verifica se o método fornecido é válido
30
+ method = method.upper()
31
+ if method not in http_methods:
32
+ raise ValueError(f"Método HTTP inválido. Use um dos seguintes: {', '.join(http_methods.keys())}.")
33
+
34
+ payload = {}
35
+ if headers is None: headers = {"x-access-token": token}
36
+ else: {headers: token}
37
+
38
+ max_attempts = 5
39
+ for attempt in range(1, max_attempts + 1):
40
+ from .get_driver import RD, RESET
41
+ try:
42
+
43
+ # Realiza a requisição com o método correto
44
+ if method == "GET" or method == "DELETE": response_insert = http_methods[method](link, params=payload, headers=headers)
45
+ else: response_insert = http_methods[method](link, json=payload, headers=headers)
46
+ if "Sequelize" in response_insert.json(): raise SystemError(f" {RD}>>> {response_insert.json()}{RESET}")
47
+
48
+ if print_response == True:
49
+ print(f"\n{response_insert.json()}")
50
+
51
+ return response_insert.json()
52
+
53
+ except Exception as e:
54
+ print(f"Tentativa {attempt} falhou: {e}")
55
+
56
+ if attempt < max_attempts:
57
+ print("Tentando novamente em 5 segundos...")
58
+ time.sleep(5)
59
+ continue
60
+
61
+ else: raise ValueError("Api list falhou")
62
+
63
+ def invoke_api_proc(link: str, payload_vars: dict, token: str, method: str, print_response: Optional[bool | str] = False) -> str:
64
+ import requests
65
+
66
+ """
67
+ Exemplo de uso abaixo:
68
+
69
+ import BCFOX as bc
70
+
71
+ def invoke_api_proc_final(self):
72
+ link = https://linK_api.com.br/apis/{parametros}
73
+ token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
74
+
75
+ payload = [
76
+ {"ID":self.id},
77
+ {"STATUS":self.status},
78
+ {"PAGAMENTO":self.pagamento}
79
+ ...
80
+ ]
81
+
82
+ bc.invoke_api_proc_final(link, payload, token, print_response=True)
83
+
84
+ OBS: o print_response vem por padrão desligado, caso você queria ver o returno do response coloque 'ON'
85
+ OBS2: Caso queria printar o json response intero coloque: 'print_response = "full"'
86
+
87
+ """
88
+
89
+ if isinstance(print_response, str):
90
+ if print_response.lower().strip() == "full":
91
+ print_response = "full"
92
+
93
+ else:
94
+ raise ValueError("print_response com variável inválida\n Use tipo 'bool' ou escreva 'full' (str) para response completo")
95
+
96
+ http_methods = {
97
+ "POST": requests.post,
98
+ "GET": requests.get,
99
+ "PUT": requests.put,
100
+ "DELETE": requests.delete,
101
+ "PATCH": requests.patch,
102
+ }
103
+
104
+ # Verifica se o método fornecido é válido
105
+ method = method.upper()
106
+ if method not in http_methods:
107
+ raise ValueError(f"Método HTTP inválido. Use um dos seguintes: {', '.join(http_methods.keys())}.")
108
+
109
+ # PROC PARA FINALIZAR PROCESSO
110
+ url = link
111
+
112
+ payload = payload_vars
113
+
114
+ if print_response == True or print_response == "full":
115
+ print(f'payload: {payload}')
116
+
117
+ headers = {"x-access-token": token}
118
+
119
+ max_attempts = 5
120
+ for attempt in range(1, max_attempts + 1):
121
+ try:
122
+ # Realiza a requisição com o método correto
123
+ if method == "GET" or method == "DELETE": response_insert = http_methods[method](url, params=payload, headers=headers)
124
+ else: response_insert = http_methods[method](url, json=payload, headers=headers)
125
+
126
+ response_insert.raise_for_status()
127
+
128
+ if print_response == True or print_response == "full":
129
+ print(response_insert.json())
130
+
131
+ if print_response == "full":
132
+ return response_insert.json()
133
+
134
+ status = response_insert.json()[0]['STATUS']
135
+ return status
136
+
137
+ except Exception as e:
138
+ print(f"Tentativa {attempt} falhou: {e}")
139
+
140
+ if attempt < max_attempts:
141
+ print("Tentando novamente em 5 segundos...")
142
+ time.sleep(5)
143
+ continue
144
+
145
+ else: raise ValueError("Api proc final falhou")
146
+
147
+ def invoke_api_proc_log(link, id_robo, token):
148
+ import requests
149
+
150
+ """Só colocar o ID do robo e o Token direto """
151
+
152
+ payload = {
153
+ "id": id_robo
154
+ }
155
+
156
+ print(payload)
157
+
158
+ headers = {
159
+ "x-access-token": token}
160
+
161
+ responseinsert = requests.request(
162
+ "POST", link, json=payload, headers=headers)
163
+ print(f"\n{responseinsert.json()}")
164
+
165
+ def login_2fac(driver, certificate, system, token, code_timeout=60):
166
+ from . import mostrar_mensagem
167
+ import time
168
+ import requests
169
+ import pyautogui
170
+ from selenium.webdriver.common.by import By
171
+ from selenium.webdriver.support.ui import WebDriverWait
172
+ from selenium.webdriver.support import expected_conditions as EC
173
+
174
+ class login_2fac:
175
+ def __init__(self):
176
+ self.certificate = certificate
177
+ self.system = system
178
+ self.token = token
179
+ self.code_timeout = code_timeout
180
+ self.driver = driver
181
+
182
+ class tools(login_2fac):
183
+ def find_element_with_wait(self, by, value, timeout=10):
184
+ global driver
185
+ return WebDriverWait(
186
+ self.driver, timeout).until(
187
+ EC.presence_of_element_located(
188
+ (by, value)))
189
+
190
+ def find_elements_with_wait(self, by, value, timeout=10):
191
+ return WebDriverWait(
192
+ self.driver, timeout).until(
193
+ EC.presence_of_all_elements_located(
194
+ (by, value)))
195
+
196
+ class invokes_whoom(login_2fac):
197
+ def __init__(self):
198
+ super().__init__()
199
+
200
+ self.list_codes = []
201
+
202
+ def invoke_get_codes(self):
203
+
204
+ url = "https://api-4.bcfox.com.br/bcjur/views/codigo-validacao"
205
+ headers = {"x-access-token": self.token}
206
+
207
+ max_attempts = 5
208
+ for attempt in range(1, max_attempts + 1):
209
+ try:
210
+ response = requests.get(url, headers=headers)
211
+ response.raise_for_status() # Lança uma exceção se a resposta não for bem-sucedida
212
+
213
+ self.list_codes = response.json()
214
+ # print(self.list_codes)
215
+ return self.list_codes
216
+
217
+ except Exception as e:
218
+ print(f'Tentativa {attempt} falhou: {e}')
219
+
220
+ if attempt < max_attempts:
221
+ print('Tentando novamente em 5 segundos...')
222
+ time.sleep(5)
223
+ continue
224
+ else:
225
+ raise('Todas as tentativas falharam!')
226
+
227
+ def invoke_update_status(self, id):
228
+
229
+ url = f"https://api-4.bcfox.com.br/bcjur/views/codigo-validacao/{id}"
230
+ headers = {"x-access-token": self.token}
231
+
232
+ max_attempts = 5
233
+ for attempt in range(1, max_attempts + 1):
234
+ try:
235
+ responseinsert = requests.put(url, headers=headers)
236
+ responseinsert.raise_for_status() # Lança uma exceção se a resposta não for bem-sucedida
237
+
238
+ print(responseinsert)
239
+ return responseinsert
240
+
241
+ except Exception as e:
242
+ print(f'Tentativa {attempt} falhou: {e}')
243
+
244
+ if attempt < max_attempts:
245
+ print('Tentando novamente em 5 segundos...')
246
+ time.sleep(5)
247
+ continue
248
+ else:
249
+ raise('Todas as tentativas falharam!')
250
+
251
+ class whoom_codes(login_2fac):
252
+ def __init__(self):
253
+ super().__init__()
254
+
255
+ def codes_2_fac(self):
256
+
257
+ self.extension_check()
258
+ time.sleep(3)
259
+
260
+ try:
261
+ tools.find_element_with_wait(By.XPATH, '//input[@placeholder="Digite ou selecione um sistema pra acessar"]', timeout=10).send_keys(self.system)
262
+ code_insertion = True
263
+
264
+ except:
265
+ self.driver.get('chrome-extension://lnidijeaekolpfeckelhkomndglcglhh/index.html')
266
+ # Request the code
267
+ for _ in range(50): # Wait the extension to load
268
+
269
+ try:
270
+ tools.find_element_with_wait(By.XPATH, '//*[@id="root"]/div/div[1]/div//div//input', timeout=1).send_keys('eliezer@bcfox.com.br')
271
+
272
+ break
273
+ except:
274
+ self.driver.get('chrome-extension://lnidijeaekolpfeckelhkomndglcglhh/index.html')
275
+
276
+ tools.find_element_with_wait(By.XPATH, '//button').click()
277
+
278
+ # Attempts the new codes until success or requests limit
279
+ for _ in range(code_timeout):
280
+ responses = api.invoke_get_codes()
281
+
282
+ # Try new codes
283
+ code_insertion = False
284
+ for response in responses:
285
+
286
+ CODE = response['CODIGO']
287
+ ID = response['ID']
288
+
289
+ tools.find_element_with_wait(By.XPATH, '//input[@type="password"]').send_keys(CODE)
290
+ tools.find_element_with_wait(By.XPATH, '//div/div[2]/button').click()
291
+
292
+ # Check the code result
293
+ for _ in range(7):
294
+
295
+ # Correct
296
+ try:
297
+ # input('\n\n > Selecione o sistema e aperte alguma tecla.')
298
+ tools.find_element_with_wait(By.XPATH, '//input[@placeholder="Digite ou selecione um sistema pra acessar"]', timeout=1).send_keys(self.system)
299
+ api.invoke_update_status(ID) #FIX: Update
300
+ code_insertion = True
301
+ break
302
+
303
+ except:
304
+ pass
305
+
306
+ # Wrong
307
+ try:
308
+ tools.find_element_with_wait(By.XPATH, "//span[contains(text(), 'Senha inválida')]", timeout=1)
309
+ tools.find_element_with_wait(By.XPATH, "//button[text()='Voltar']", timeout=1)
310
+ code_insertion = False
311
+ break
312
+
313
+ except:
314
+ pass
315
+
316
+ # If the 'new_response' loop succeeds immediately
317
+ if not responses:
318
+ time.sleep(1)
319
+
320
+ if code_insertion:
321
+ break
322
+
323
+ if not(code_insertion):
324
+ mostrar_mensagem('Código WHOOM não chegou dentro do timeout estabelecido')
325
+ raise TimeoutError('Código WHOOM não chegou dentro do timeout estabelecido')
326
+
327
+ # Selects the system to access
328
+ try:
329
+ lines = self.find_elements_with_wait(self.driver, By.XPATH, '//*[@id="root"]/div[2]/div/div[1]/div/div[2]/div/div/div', timeout=5)
330
+ except:
331
+ try:
332
+ lines = self.find_elements_with_wait(self.driver, By.XPATH, '//*[@id="root"]/div[2]/div/div[2]/div/div[2]/div/div/div', timeout=5)
333
+ except:
334
+ mostrar_mensagem('Não conseguiu achar o sistema no certificado')
335
+ raise ValueError('Não conseguiu achar o sistema no certificado')
336
+
337
+ finded = False
338
+ div_list = []
339
+
340
+ # This loop extract the lines with the system name
341
+ for line in lines:
342
+
343
+ titulo_element = line.find_elements(By.XPATH, './span[*[name()="svg"]]')
344
+
345
+ if not titulo_element and not finded:
346
+ continue
347
+
348
+ elif titulo_element and not finded:
349
+ titulo_text = line.find_element(By.XPATH, './span').text
350
+ if self.certificate.lower().strip() in titulo_text.lower().strip():
351
+ finded = True
352
+ continue
353
+
354
+ elif not titulo_element and finded:
355
+ div_list.append(line)
356
+
357
+ elif titulo_element and finded:
358
+ break
359
+
360
+ if not div_list:
361
+ mostrar_mensagem('Não conseguiu achar o sistema no certificado')
362
+ raise ValueError('Não conseguiu achar o sistema no certificado')
363
+
364
+ if len(div_list) == 1:
365
+ div_list[0].click()
366
+
367
+ # Just do this loop if there are more than one system
368
+ else:
369
+ for div in div_list:
370
+ div_text = div.find_element(By.XPATH, './span').text
371
+ if self.system.lower().strip() not in div_text.lower().strip():
372
+ div_list.remove(div)
373
+
374
+ if len(div_list) == 1:
375
+ div_list[0].click()
376
+ else:
377
+ mostrar_mensagem('Mais de um sistema encontrado, verifique o nome do sistema no WHOOM e coloque um nome único na função')
378
+ raise ValueError('Mais de um sistema encontrado, verifique o nome')
379
+
380
+ # Verifies if the system was opened
381
+ num_windows = len(self.driver.window_handles)
382
+ for _ in range(5):
383
+ time.sleep(1)
384
+ if len(self.driver.window_handles) == num_windows:
385
+ tools.find_element_with_wait(By.XPATH, "//button[text()='Acessar']").click()
386
+ else:
387
+ break
388
+
389
+ def extension_check(self):
390
+
391
+ self.driver.get('chrome-extension://lnidijeaekolpfeckelhkomndglcglhh/index.html')
392
+
393
+ try:
394
+ tools.find_element_with_wait(By.XPATH, '//input[@placeholder="Digite ou selecione um sistema pra acessar"]', timeout=10).send_keys(self.system)
395
+ return
396
+
397
+ except Exception as e:
398
+
399
+ # Abrir uma nova aba
400
+ self.driver.execute_script("window.open('');")
401
+
402
+ # Fechar a aba original
403
+ self.driver.close()
404
+
405
+ # Mudar para a nova aba
406
+ self.driver.switch_to.window(self.driver.window_handles[-1])
407
+
408
+ time.sleep(1)
409
+
410
+ self.driver.get("https://chromewebstore.google.com/detail/whom-gerenciador-de-certi/lnidijeaekolpfeckelhkomndglcglhh")
411
+
412
+ try:
413
+ tools.find_element_with_wait(By.XPATH, "//span[contains(text(), 'Instalar') or contains(text(), 'Obter') or contains(text(), 'Add to Chrome')]").click()
414
+ except Exception as e:
415
+ return
416
+ time.sleep(5)
417
+
418
+ # Envia TAB e ENTER do teclado físico
419
+ pyautogui.press('tab')
420
+ time.sleep(0.5)
421
+ pyautogui.press('enter')
422
+ time.sleep(5)
423
+
424
+ self.driver.get('chrome-extension://lnidijeaekolpfeckelhkomndglcglhh/index.html')
425
+
426
+ tools = tools()
427
+ api = invokes_whoom()
428
+ bot = whoom_codes()
429
+
430
+ bot.codes_2_fac()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bcpkgfox
3
- Version: 0.16.54
3
+ Version: 0.16.56
4
4
  Summary: Biblioteca BCFOX
5
5
  Home-page: https://github.com/robotsbcfox/PacotePythonBCFOX
6
6
  Author: Guilherme Neri
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="bcpkgfox",
5
- version="0.16.54",
5
+ version="0.16.56",
6
6
  author="Guilherme Neri",
7
7
  author_email="guilherme.neri@bcfox.com.br",
8
8
  description="Biblioteca BCFOX",
@@ -1,163 +0,0 @@
1
- from typing import Optional
2
- import time
3
-
4
- def invoke_api_list(link: str, token: str, method: Optional[str] = "GET", headers: Optional[str] = None, print_response: Optional[bool] = False) -> dict:
5
- import requests
6
-
7
- """
8
- Exemplo de uso abaixo:
9
-
10
- import BCFOX as bc
11
-
12
- def invoke_api_list(self):
13
- link = 'https://linK_api.com.br/apis/{parametros}'
14
- token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
15
-
16
- bc.invoke_api_list(link, token, print_response=True)
17
-
18
- OBS: o print_response vem por padrão desligado, caso você queira ativa o print da view coloque 'ON'
19
-
20
- """
21
- http_methods = {
22
- "POST": requests.post,
23
- "GET": requests.get,
24
- "PUT": requests.put,
25
- "DELETE": requests.delete,
26
- "PATCH": requests.patch
27
- }
28
-
29
- # Verifica se o método fornecido é válido
30
- method = method.upper()
31
- if method not in http_methods:
32
- raise ValueError(f"Método HTTP inválido. Use um dos seguintes: {', '.join(http_methods.keys())}.")
33
-
34
- payload = {}
35
- if headers is None: headers = {"x-access-token": token}
36
- else: {headers: token}
37
-
38
- max_attempts = 5
39
- for attempt in range(1, max_attempts + 1):
40
- from .get_driver import RD, RESET
41
- try:
42
-
43
- # Realiza a requisição com o método correto
44
- if method == "GET" or method == "DELETE": response_insert = http_methods[method](link, params=payload, headers=headers)
45
- else: response_insert = http_methods[method](link, json=payload, headers=headers)
46
- if "Sequelize" in response_insert.json(): raise SystemError(f" {RD}>>> {response_insert.json()}{RESET}")
47
-
48
- if print_response == True:
49
- print(f"\n{response_insert.json()}")
50
-
51
- return response_insert.json()
52
-
53
- except Exception as e:
54
- print(f"Tentativa {attempt} falhou: {e}")
55
-
56
- if attempt < max_attempts:
57
- print("Tentando novamente em 5 segundos...")
58
- time.sleep(5)
59
- continue
60
-
61
- else: raise ValueError("Api list falhou")
62
-
63
- def invoke_api_proc(link: str, payload_vars: dict, token: str, method: str, print_response: Optional[bool | str] = False) -> str:
64
- import requests
65
-
66
- """
67
- Exemplo de uso abaixo:
68
-
69
- import BCFOX as bc
70
-
71
- def invoke_api_proc_final(self):
72
- link = https://linK_api.com.br/apis/{parametros}
73
- token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
74
-
75
- payload = [
76
- {"ID":self.id},
77
- {"STATUS":self.status},
78
- {"PAGAMENTO":self.pagamento}
79
- ...
80
- ]
81
-
82
- bc.invoke_api_proc_final(link, payload, token, print_response=True)
83
-
84
- OBS: o print_response vem por padrão desligado, caso você queria ver o returno do response coloque 'ON'
85
- OBS2: Caso queria printar o json response intero coloque: 'print_response = "full"'
86
-
87
- """
88
-
89
- if isinstance(print_response, str):
90
- if print_response.lower().strip() == "full":
91
- print_response = "full"
92
-
93
- else:
94
- raise ValueError("print_response com variável inválida\n Use tipo 'bool' ou escreva 'full' (str) para response completo")
95
-
96
- http_methods = {
97
- "POST": requests.post,
98
- "GET": requests.get,
99
- "PUT": requests.put,
100
- "DELETE": requests.delete,
101
- "PATCH": requests.patch,
102
- }
103
-
104
- # Verifica se o método fornecido é válido
105
- method = method.upper()
106
- if method not in http_methods:
107
- raise ValueError(f"Método HTTP inválido. Use um dos seguintes: {', '.join(http_methods.keys())}.")
108
-
109
- # PROC PARA FINALIZAR PROCESSO
110
- url = link
111
-
112
- payload = payload_vars
113
-
114
- if print_response == True or print_response == "full":
115
- print(f'payload: {payload}')
116
-
117
- headers = {"x-access-token": token}
118
-
119
- max_attempts = 5
120
- for attempt in range(1, max_attempts + 1):
121
- try:
122
- # Realiza a requisição com o método correto
123
- if method == "GET" or method == "DELETE": response_insert = http_methods[method](url, params=payload, headers=headers)
124
- else: response_insert = http_methods[method](url, json=payload, headers=headers)
125
-
126
- response_insert.raise_for_status()
127
-
128
- if print_response == True or print_response == "full":
129
- print(response_insert.json())
130
-
131
- if print_response == "full":
132
- return response_insert.json()
133
-
134
- status = response_insert.json()[0]['STATUS']
135
- return status
136
-
137
- except Exception as e:
138
- print(f"Tentativa {attempt} falhou: {e}")
139
-
140
- if attempt < max_attempts:
141
- print("Tentando novamente em 5 segundos...")
142
- time.sleep(5)
143
- continue
144
-
145
- else: raise ValueError("Api proc final falhou")
146
-
147
- def invoke_api_proc_log(link, id_robo, token):
148
- import requests
149
-
150
- """Só colocar o ID do robo e o Token direto """
151
-
152
- payload = {
153
- "id": id_robo
154
- }
155
-
156
- print(payload)
157
-
158
- headers = {
159
- "x-access-token": token}
160
-
161
- responseinsert = requests.request(
162
- "POST", link, json=payload, headers=headers)
163
- print(f"\n{responseinsert.json()}")
File without changes
File without changes
File without changes
File without changes