2 This is the the class in charge of containing the non-http boilerplates.
8from random
import randint
9from datetime
import datetime, timedelta
10from typing
import Union, List, Dict, Any
12from fastapi
import Response
13from display_tty
import Disp, TOML_CONF, FILE_DESCRIPTOR, SAVE_TO_FILE, FILE_NAME
15from ..components
import RuntimeData, CONST
16from ..sql.sql_manager
import SQL
23 def __init__(self, runtime_data_initialised: RuntimeData, success: int = 0, error: int = 84, debug: bool =
False) ->
None:
37 logger=self.__class__.__name__
42 This is a pause function that works in the same wat as the batch pause command.
43 It pauses the program execution until the user presses the enter key.
46 str: _description_: The input from the user
48 return input(
"Press enter to continue...")
52 The function to set the lifespan of the user token
54 seconds (int): Seconds
57 datetime: The datetime of the lifespan of the token
59 current_time = datetime.now()
60 offset_time = current_time + timedelta(seconds=seconds)
65 Check if the token is correct.
67 token (str): _description_: The token to check
70 bool: _description_: True if the token is correct, False otherwise
72 title =
"is_token_correct"
73 self.
disp.log_debug(
"Checking if the token is correct.", title)
74 if isinstance(token, str)
is False:
77 CONST.TAB_CONNECTIONS,
79 where=f
"token={token}",
82 if isinstance(login_table, int):
84 if len(login_table) != 1:
86 self.
disp.log_debug(f
"login_table = {login_table}", title)
87 if datetime.now() > login_table[0][-1]:
90 CONST.UA_TOKEN_LIFESPAN
93 datetime_instance=new_date,
97 self.
disp.log_debug(f
"string date: {new_date_str}", title)
99 table=CONST.TAB_CONNECTIONS,
101 column=
"expiration_date",
102 where=f
"token={token}"
105 self.
disp.log_warning(
106 f
"Failed to update expiration_date for {token}.",
113 This is a function that will generate a token for the user.
115 str: _description_: The token generated
117 title =
"generate_token"
118 token = str(uuid.uuid4())
120 table=CONST.TAB_CONNECTIONS,
122 where=f
"token='{token}'",
125 self.
disp.log_debug(f
"user_token = {user_token}", title)
126 while len(user_token) > 0:
127 token = str(uuid.uuid4())
129 table=CONST.TAB_CONNECTIONS,
131 where=f
"token='{token}'",
134 self.
disp.log_debug(f
"user_token = {user_token}", title)
135 if isinstance(user_token, int)
is True and user_token == self.
error:
137 if len(user_token) == 0:
141 def server_show_item_content(self, function_name: str =
"show_item_content", item_name: str =
"", item: object =
None, show: bool =
True) ->
None:
143 This is a function that will display the content of an item.
144 The purpose of this function is more for debugging purposes.
146 function_name (str, optional): _description_. Defaults to "show_item_content".
147 item (object, optional): _description_. Defaults to None.
152 f
"({function_name}) dir({item_name}) = {dir(item)}",
153 "pet_server_show_item_content"
156 if i
in (
"auth",
"session",
"user"):
158 f
"({function_name}) skipping {item_name}.{i}"
162 f
"({function_name}) {item_name}.{i} = {getattr(item, i)}"
167 This is a function that will check if the date is correct or not.
169 date (str, optional): _description_: The date to check. Defaults to "DD/MM/YYYY".
172 bool: _description_: True if the date is correct, False otherwise
174 pattern = re.compile(
175 r"^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/\d{4}$"
177 match = pattern.match(date)
182 This function will reconnect to the database in case it has been disconnected.
187 "database_link is none, initialising sql.",
188 "check_database_health"
193 username=CONST.DB_USER,
194 password=CONST.DB_PASSWORD,
195 db_name=CONST.DB_DATABASE,
200 except RuntimeError
as e:
201 msg =
"Could not connect to the database."
202 raise RuntimeError(msg)
from e
208 "database_link is none, initialising sql.",
209 "check_database_health"
214 username=CONST.DB_USER,
215 password=CONST.DB_PASSWORD,
216 db_name=CONST.DB_DATABASE,
221 except RuntimeError
as e:
222 msg =
"(check_database_health) Could not connect to the database."
223 raise RuntimeError(msg)
from e
227 Check if the user's token has admin privileges.
229 token (str): _description_
234 title =
"is_token_admin"
236 table=CONST.TAB_CONNECTIONS,
238 where=f
"token='{token}'",
241 if isinstance(user_id, int)
is True and user_id == self.
error or not user_id:
243 f
"Failed to find token {token} in the database.", title
246 self.
disp.log_debug(f
"usr_id = {user_id}", title)
248 table=CONST.TAB_ACCOUNTS,
250 where=f
"id={user_id[0][0]}",
253 if isinstance(user_info, int)
is True and user_info == self.
error:
255 f
"Failed to find user {user_id[0][0]} in the database.", title
258 self.
disp.log_debug(f
"usr_info = {user_info}", title)
259 return user_info[0][0] == 1
263 Create a token that can be used for e-mail verification.
268 if isinstance(token_size, (int, float))
is False:
270 token_size = int(token_size)
271 token_size = max(token_size, 0)
272 code = f
"{randint(CONST.RANDOM_MIN, CONST.RANDOM_MAX)}"
273 for i
in range(token_size):
274 code += f
"-{randint(CONST.RANDOM_MIN, CONST.RANDOM_MAX)}"
279 The function in charge of getting the user id based of the provided content.
282 title (str): _description_: The title of the endpoint calling it
283 token (str): _description_: The token of the user account
286 Union[str, Response]: _description_: Returns as string id if success, otherwise, a pre-made response for the endpoint.
288 function_title =
"get_user_id_from_token"
289 usr_id_node: str =
"user_id"
291 f
"Getting user id based on {token}", function_title
294 table=CONST.TAB_CONNECTIONS,
296 where=f
"token='{token}'",
299 self.
disp.log_debug(f
"current_user = {current_user}", function_title)
300 if current_user == self.
error:
303 f
"user_length = {len(current_user)}", function_title
305 if len(current_user) == 0
or len(current_user) > 1:
308 f
"current_user[0] = {current_user[0]}", function_title
310 if usr_id_node
not in current_user[0]:
312 msg =
"str(current_user[0]["
313 msg += f
"{usr_id_node}]) = {str(current_user[0][usr_id_node])}"
314 self.
disp.log_debug(msg, function_title)
315 return str(current_user[0][usr_id_node])
317 def update_user_data(self, title: str, usr_id: str, line_content: List[str]) -> Union[int, Response]:
319 Update the account information based on the provided line.
322 title (str): _description_: This is the title of the endpoint
323 usr_id (str): _description_: This is the id of the user that needs to be updated
324 line_content (List[str]): _description_: The content of the line to be edited.
327 Union[int, Response]: _description_
329 self.
disp.log_debug(f
"Compile line_content: {line_content}.", title)
333 self.
disp.log_debug(f
"Removing id from columns: {columns}.", title)
336 table=CONST.TAB_ACCOUNTS,
339 where=f
"id='{usr_id}'"
341 if status == self.
error:
347 Remove the user from the provided tables.
350 where (str): _description_: The id of the user to remove
351 tables (List[str]): _description_: The tables to remove the user from
354 int: _description_: The status of the operation
356 title =
"remove_user_from_tables"
357 if isinstance(tables, (List, tuple, str))
is False:
359 f
"Expected tables to be of type list but got {type(tables)}",
363 if isinstance(tables, str)
is True:
364 self.
disp.log_warning(
365 "Tables is of type str, converting to list[str].", title
374 deletion_status[str(table)] = status
375 if status == self.
error:
376 self.
disp.log_warning(
377 f
"Failed to remove data from table: {table}",
380 return deletion_status
382 def update_single_data(self, table: str, column_finder: str, column_to_update: str, data_finder: str, request_body: dict) -> int:
384 The function in charge of updating the data in the database
388 [request_body[column_to_update]],
390 f
"{column_finder}='{data_finder}'"
397 Get the actions that are available for the service
400 service_id (str): _description_
403 List[Dict[str, Any]]: _description_
405 title =
"get_actions"
407 self.
disp.log_debug(
"Gathering actions", title)
409 table=CONST.TAB_ACTION_TEMPLATE,
411 where=f
"service_id='{service_id}' AND type='trigger'",
414 self.
disp.log_debug(f
"actions = {actions}", title)
415 if actions == self.
error:
416 self.
disp.log_error(
"Failed to get actions", title)
418 for index, item
in enumerate(actions):
420 if "json" not in item:
421 self.
disp.log_error(f
"json not in item {index}", title)
422 self.
disp.log_warning(
"Skipping action", title)
424 if item[
"type"].lower() !=
"trigger":
426 f
"item {index} is not a trigger", title
428 self.
disp.log_debug(
"Skipping action", title)
430 self.
disp.log_debug(f
"item = {item}", title)
431 self.
disp.log_debug(
"Getting json node.", title)
432 node_str = item[
"json"]
433 node = json.loads(node_str)
434 self.
disp.log_debug(
"data has been converted to json", title)
435 self.
disp.log_debug(f
"node = {node}", title)
436 self.
disp.log_debug(f
"node keys = {list(node)}", title)
437 self.
disp.log_debug(
"Adding reaction to result", title)
440 "name": node[
"name"],
441 "description": node[
"description"],
444 self.
disp.log_debug(
"Reaction gathered.", title)
445 except Exception
as e:
446 self.
disp.log_error(f
"Failed to parse reaction {index}", title)
447 self.
disp.log_error(f
"Error: {e}", title)
448 self.
disp.log_info(
"Skipping reaction", title)
449 self.
disp.log_debug(f
"result = {result}", title)
454 Get the reactions that are available for the service
457 service_id (str): _description_
460 List[Dict[str, Any]]: _description_
462 title =
"get_reactions"
463 self.
disp.log_debug(
"Gathering reactions", title)
466 table=CONST.TAB_ACTION_TEMPLATE,
468 where=f
"service_id='{service_id}' AND type='action'",
471 self.
disp.log_debug(f
"reactions = {reactions}", title)
472 if reactions == self.
error:
473 self.
disp.log_error(
"Failed to get reactions", title)
475 for index, item
in enumerate(reactions):
477 if "json" not in item:
478 self.
disp.log_error(f
"json not in item {index}", title)
479 self.
disp.log_warning(
"Skipping action", title)
481 if item[
"type"].lower() !=
"action":
483 f
"item {index} is not a action", title
485 self.
disp.log_debug(
"Skipping trigger", title)
487 self.
disp.log_debug(f
"item = {item}", title)
488 self.
disp.log_debug(
"Getting json node.", title)
489 node_str = item[
"json"]
490 node = json.loads(node_str)
491 self.
disp.log_debug(
"data has been converted to json", title)
492 self.
disp.log_debug(f
"node = {node}", title)
493 self.
disp.log_debug(f
"node keys = {list(node)}", title)
494 self.
disp.log_debug(
"Adding reaction to result", title)
497 "name": node[
"name"],
498 "description": node[
"description"],
501 self.
disp.log_debug(
"Reaction gathered.", title)
502 except Exception
as e:
503 self.
disp.log_error(f
"Failed to parse reaction {index}", title)
504 self.
disp.log_error(f
"Error: {e}", title)
505 self.
disp.log_info(
"Skipping reaction", title)
506 self.
disp.log_debug(f
"result = {result}", title)
511 Get the services that are available.
514 List[Dict[str, Any]]: _description_
516 title =
"get_services"
517 self.
disp.log_debug(
"Gathering services", title)
520 table=CONST.TAB_SERVICES,
525 self.
disp.log_debug(f
"services = {services}", title)
526 if services == self.
error:
527 self.
disp.log_error(
"Failed to get services", title)
529 for index, item
in enumerate(services):
532 "name": item[
"name"],
533 "actions": self.
get_actions(services[index][
"id"]),
537 self.
disp.log_debug(f
"result = {result}", title)
542 Hide the api key from the user.
545 api_key (str): _description_: The api key to hide
548 str: _description_: The hidden api key
550 title =
"hide_api_key"
551 self.
disp.log_debug(f
"api_key = {api_key}", title)
553 api_key =
"No api key"
555 api_key =
"Some api key"
556 self.
disp.log_debug(f
"api_key after: {api_key}", title)
Union[int, Response] update_user_data(self, str title, str usr_id, List[str] line_content)
bool is_token_admin(self, str token)
None server_show_item_content(self, str function_name="show_item_content", str item_name="", object item=None, bool show=True)
None check_database_health(self)
bool check_date(self, str date="DD/MM/YYYY")
List[Dict[str, Any]] get_actions(self, str service_id)
List[Dict[str, Any]] get_services(self)
None __init__(self, RuntimeData runtime_data_initialised, int success=0, int error=84, bool debug=False)
datetime set_lifespan(self, int seconds)
Union[str, Response] get_user_id_from_token(self, str title, str token)
int update_single_data(self, str table, str column_finder, str column_to_update, str data_finder, dict request_body)
Union[int, Dict[str, int]] remove_user_from_tables(self, str where, List[str] tables)
str hide_api_key(self, str api_key)
str generate_check_token(self, int token_size=4)
RuntimeData runtime_data_initialised
List[Dict[str, Any]] get_reactions(self, str service_id)
bool is_token_correct(self, str token)