csc-cia-stne 0.0.37__py3-none-any.whl → 0.0.39__py3-none-any.whl

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.
csc_cia_stne/__init__.py CHANGED
@@ -10,6 +10,8 @@ from .bc_correios import BC_Correios
10
10
  from .gcp_bigquery import BigQuery
11
11
  from .email import Email
12
12
  from .provio import Provio
13
+ from .google_drive import GoogleDrive
14
+ from .slack import Slack
13
15
 
14
16
  # Define os itens disponíveis para importação
15
17
  __all__ = [
@@ -22,7 +24,9 @@ __all__ = [
22
24
  "Util",
23
25
  "logger",
24
26
  "Provio",
25
- "Email"
27
+ "Email",
28
+ "GoogleDrive",
29
+ "Slack"
26
30
  ]
27
31
 
28
32
  _diretorio_inicial = os.getcwd()
@@ -1,16 +1,13 @@
1
- import os, time, logging, json
2
- from .karavela import Karavela
1
+ import os, logging
3
2
  from googleapiclient.discovery import build
4
3
  from googleapiclient.http import MediaFileUpload
5
4
  from googleapiclient.errors import HttpError
6
5
  from io import BytesIO
7
- from googleapiclient.discovery import build
8
6
  from google.oauth2 import service_account
9
- from .utilitarios.validations.GoogleDriveValidator import InitParamsValidator, CreateFolderValidator, ListFolderValidator
7
+ from .utilitarios.validations.GoogleDriveValidator import InitParamsValidator, CreateFolderValidator, ListFolderValidator, UploadValidator
10
8
  from pydantic import ValidationError
11
9
 
12
10
 
13
-
14
11
  class GoogleDrive():
15
12
 
16
13
  """
@@ -20,8 +17,16 @@ class GoogleDrive():
20
17
  Args:
21
18
  key (str): Chave de autenticação para acessar a API do Google Drive.
22
19
  """
20
+ _instance = None # Atributo de classe para armazenar a única instância.
21
+
22
+ def __new__(cls, *args, **kwargs):
23
+ # Verifica se já existe uma instância da classe.
24
+ if cls._instance is None:
25
+ # Cria e armazena a instância na primeira chamada.
26
+ cls._instance = super().__new__(cls)
27
+ return cls._instance
23
28
 
24
- def __init__(self, key, with_subject : str, scopes : list = ["https://www.googleapis.com/auth/drive"], version : str = "v3"):
29
+ def __init__(self, token : dict, with_subject : str, scopes : list = ["https://www.googleapis.com/auth/drive"], version : str = "v3"):
25
30
  """
26
31
  Inicializa uma instância da classe GoogleDrive.
27
32
  Parâmetros:
@@ -36,43 +41,20 @@ class GoogleDrive():
36
41
  google_drive = GoogleDrive(key="chave_secreta", with_subject="assunto", scopes=["https://www.googleapis.com/auth/drive"], version="v3")
37
42
  ```
38
43
  """
39
- # código de inicialização da instância
40
44
 
41
45
  try:
42
- InitParamsValidator(key=key, with_subject=with_subject, scopes=scopes)
46
+ InitParamsValidator(token=token, with_subject=with_subject, scopes=scopes, version=version)
43
47
  except ValidationError as e:
44
48
  raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
45
-
46
- self.__token = json.loads(Karavela.get_secret(key))
49
+ self.__token = token
47
50
  self.version = version
48
51
  self.scopes = scopes
49
- self.__auth = self.__autentica(with_subject)
52
+ self.with_subject = with_subject
50
53
  self.page_size = 1000
51
- self.service = self.create_service()
54
+ self.service = self.__create_service()
52
55
 
53
- def timer_decorator(func):
54
- """
55
- Decorator que calcula o tempo de execução de uma função.
56
- Args:
57
- func: A função a ser decorada.
58
- Returns:
59
- A função decorada.
60
- Exemplo de uso:
61
- @timer_decorator
62
- def minha_funcao():
63
- # código da função
64
- minha_funcao()
65
- """
66
-
67
- def wrapper(*args, **kwargs):
68
- inicio = time.time()
69
- resultado = func(*args, **kwargs)
70
- fim = time.time()
71
- logging.debug(f"Tempo de execução de {func.__name__}: {fim - inicio:.2f} segundos")
72
- return resultado
73
- return wrapper
74
-
75
- def create_service(self):
56
+
57
+ def __create_service(self):
76
58
  """
77
59
  Cria um serviço do Google Drive.
78
60
  Returns:
@@ -89,14 +71,15 @@ class GoogleDrive():
89
71
  """
90
72
 
91
73
  try:
92
-
93
- cred = build(f"drive", f"{self.version}", credentials=self.__auth)
94
- logging.debug(f"Serviço do Google drive criado")
95
- return cred
74
+ auth = self.__autentica(self.with_subject)
75
+ service = build(f"drive", f"{self.version}", credentials=auth)
76
+ logging.info(f"Serviço do Google drive criado")
77
+ return service
96
78
  except Exception as e:
97
- logging.debug(f"Erro ao criar o serviço do Google drive: Error: {e}")
79
+ logging.info(f"Erro ao criar o serviço do Google drive: Error: {e}")
98
80
  return False
99
-
81
+
82
+
100
83
  def __autentica(self, with_subject : str):
101
84
  """
102
85
  Autentica o usuário com as credenciais fornecidas e retorna as credenciais delegadas para o assunto especificado.
@@ -121,7 +104,7 @@ class GoogleDrive():
121
104
  logging.debug(f"Erro ao tentar autenticar. Verifique o erro: {e}")
122
105
  return False
123
106
 
124
- @timer_decorator
107
+
125
108
  def upload(self, folder_id: str, name: str, file_path: str, mimetype: str):
126
109
  """
127
110
  Faz o upload de um arquivo para o Google Drive em uma pasta especificada.
@@ -131,11 +114,27 @@ class GoogleDrive():
131
114
  name (str): Nome do arquivo que será carregado.
132
115
  file_path (str): Caminho completo do arquivo no sistema local.
133
116
  mimetype (str): Tipo MIME do arquivo a ser carregado.
117
+ exemplos: text/plain
118
+ text/html
119
+ image/jpeg
120
+ image/png
121
+ audio/mpeg
122
+ audio/ogg
123
+ audio/*
124
+ video/mp4
125
+ application/octet-stream
134
126
 
135
127
  Returns:
136
128
  dict: Informações sobre o arquivo carregado, incluindo o ID do arquivo.
137
129
  None: Caso o caminho do arquivo não seja encontrado.
138
130
  """
131
+ try:
132
+ UploadValidator(folder_id=folder_id, name=name, file_path=file_path, mimetype=mimetype)
133
+ except ValidationError as e:
134
+ raise ValueError("Erro na validação dos dados para realizar o upload do arquivo", e.errors())
135
+
136
+
137
+
139
138
  file_metadata = {"name": name, "parents": [folder_id]}
140
139
  if not os.path.exists(file_path):
141
140
  logging.debug(f"Pasta {file_path} não encontrada")
@@ -156,6 +155,7 @@ class GoogleDrive():
156
155
  logging.debug(f"Erro ao realizar o upload do arquivo {name} no google drive. Erro: {e}")
157
156
  return {"success" : False, "result" : None, "error" : str(e)}
158
157
 
158
+
159
159
  def create_folder(self, name: str, parent_folder_id: str):
160
160
  """
161
161
  Cria uma pasta no Google Drive dentro de uma pasta existente.
@@ -185,8 +185,9 @@ class GoogleDrive():
185
185
  except Exception as e:
186
186
  logging.debug(f"Não foi possível criar a pasta {name}")
187
187
  return {"success" : False, "result": None, "error" : str(e)}
188
-
189
- def list(self, query: str = "", spaces: str = "drive", fields: str = "nextPageToken, files(id, name)"):
188
+
189
+
190
+ def list_items_folder(self, query: str = "", spaces: str = "drive", fields: str = "nextPageToken, files(id, name)"):
190
191
  """
191
192
  Lista os arquivos e pastas no Google Drive com base nos critérios fornecidos.
192
193
 
@@ -194,6 +195,7 @@ class GoogleDrive():
194
195
  query (str, optional): Critério de busca para os arquivos ou pastas no Google Drive.
195
196
  Consulte https://developers.google.com/drive/api/v3/ref-search-terms.
196
197
  Defaults to "".
198
+ exemplo: query = 'ID_DA_PASTA_NO_GOOGLE_DRIVE' in parents and trashed=false"
197
199
  spaces (str, optional): Especifica os locais de armazenamento a serem consultados. Pode ser 'drive',
198
200
  'appDataFolder', ou 'photos'. Defaults to 'drive'.
199
201
  fields (str, optional): Campos a serem retornados na resposta. Consulte a documentação para os campos disponíveis.
@@ -221,8 +223,10 @@ class GoogleDrive():
221
223
  except HttpError as hr:
222
224
  logging.debug(f"Ocorreu um de http. Erro: {hr}")
223
225
  return {"success" : False, "result" : None, "error" : str(hr)}
226
+ except Exception as e:
227
+ logging.error(f"Ocorreu um erro ao fazer a requisição. Error: {e}")
224
228
 
225
- @timer_decorator
229
+
226
230
  def get_file(self, file : str, ):
227
231
  """
228
232
  Obtém o conteúdo de um arquivo armazenado no Google Drive.
@@ -249,8 +253,7 @@ class GoogleDrive():
249
253
  - A função assume a existência de um atributo `self.service` configurado para interagir com a API do Google Drive.
250
254
  """
251
255
  try:
252
- # file_metadata = self.service.files().get(fileId=file_id, fields="name, mimeType").execute()
253
- logging.debug(f"Lendo o arquivo {file.get("name")}")
256
+ logging.debug(f"Lendo o arquivo {file.get('name')}")
254
257
  request = self.service.files().get_media(fileId=file.get("id"))
255
258
  file_data = BytesIO(request.execute())
256
259
  logging.debug("Leitura do arquivo finalizada")
csc_cia_stne/provio.py CHANGED
@@ -90,7 +90,7 @@ class Provio:
90
90
  skip += 500
91
91
  requisicao += 1
92
92
  if verbose:
93
- logging.info(f"Exportando relatório: Requisição #{str(requisicao).zfill(3)} - {len(todos_os_dados)} registros exportados")
93
+ logging.info(f"Exportando relatório: Requisição #{str(requisicao).zfill(3)} - {len(todos_os_dados)} registros no total")
94
94
 
95
95
  else:
96
96