pandoraPlugintools-basic 1.0.0__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.
@@ -0,0 +1,683 @@
1
+ import base64
2
+ import hashlib
3
+ import sys
4
+ from datetime import datetime
5
+
6
+ ####
7
+ # Define some global variables
8
+ #########################################################################################
9
+
10
+ # Entity to character mapping. Contains a few tweaks to make it backward compatible with the previous safe_input implementation.
11
+ _ENT2CHR = {
12
+ "#x00": chr(0),
13
+ "#x01": chr(1),
14
+ "#x02": chr(2),
15
+ "#x03": chr(3),
16
+ "#x04": chr(4),
17
+ "#x05": chr(5),
18
+ "#x06": chr(6),
19
+ "#x07": chr(7),
20
+ "#x08": chr(8),
21
+ "#x09": chr(9),
22
+ "#x0a": chr(10),
23
+ "#x0b": chr(11),
24
+ "#x0c": chr(12),
25
+ "#x0d": chr(13),
26
+ "#x0e": chr(14),
27
+ "#x0f": chr(15),
28
+ "#x10": chr(16),
29
+ "#x11": chr(17),
30
+ "#x12": chr(18),
31
+ "#x13": chr(19),
32
+ "#x14": chr(20),
33
+ "#x15": chr(21),
34
+ "#x16": chr(22),
35
+ "#x17": chr(23),
36
+ "#x18": chr(24),
37
+ "#x19": chr(25),
38
+ "#x1a": chr(26),
39
+ "#x1b": chr(27),
40
+ "#x1c": chr(28),
41
+ "#x1d": chr(29),
42
+ "#x1e": chr(30),
43
+ "#x1f": chr(31),
44
+ "#x20": chr(32),
45
+ "quot": chr(34),
46
+ "amp": chr(38),
47
+ "#039": chr(39),
48
+ "#40": chr(40),
49
+ "#41": chr(41),
50
+ "lt": chr(60),
51
+ "gt": chr(62),
52
+ "#92": chr(92),
53
+ "#x80": chr(128),
54
+ "#x81": chr(129),
55
+ "#x82": chr(130),
56
+ "#x83": chr(131),
57
+ "#x84": chr(132),
58
+ "#x85": chr(133),
59
+ "#x86": chr(134),
60
+ "#x87": chr(135),
61
+ "#x88": chr(136),
62
+ "#x89": chr(137),
63
+ "#x8a": chr(138),
64
+ "#x8b": chr(139),
65
+ "#x8c": chr(140),
66
+ "#x8d": chr(141),
67
+ "#x8e": chr(142),
68
+ "#x8f": chr(143),
69
+ "#x90": chr(144),
70
+ "#x91": chr(145),
71
+ "#x92": chr(146),
72
+ "#x93": chr(147),
73
+ "#x94": chr(148),
74
+ "#x95": chr(149),
75
+ "#x96": chr(150),
76
+ "#x97": chr(151),
77
+ "#x98": chr(152),
78
+ "#x99": chr(153),
79
+ "#x9a": chr(154),
80
+ "#x9b": chr(155),
81
+ "#x9c": chr(156),
82
+ "#x9d": chr(157),
83
+ "#x9e": chr(158),
84
+ "#x9f": chr(159),
85
+ "#xa0": chr(160),
86
+ "#xa1": chr(161),
87
+ "#xa2": chr(162),
88
+ "#xa3": chr(163),
89
+ "#xa4": chr(164),
90
+ "#xa5": chr(165),
91
+ "#xa6": chr(166),
92
+ "#xa7": chr(167),
93
+ "#xa8": chr(168),
94
+ "#xa9": chr(169),
95
+ "#xaa": chr(170),
96
+ "#xab": chr(171),
97
+ "#xac": chr(172),
98
+ "#xad": chr(173),
99
+ "#xae": chr(174),
100
+ "#xaf": chr(175),
101
+ "#xb0": chr(176),
102
+ "#xb1": chr(177),
103
+ "#xb2": chr(178),
104
+ "#xb3": chr(179),
105
+ "#xb4": chr(180),
106
+ "#xb5": chr(181),
107
+ "#xb6": chr(182),
108
+ "#xb7": chr(183),
109
+ "#xb8": chr(184),
110
+ "#xb9": chr(185),
111
+ "#xba": chr(186),
112
+ "#xbb": chr(187),
113
+ "#xbc": chr(188),
114
+ "#xbd": chr(189),
115
+ "#xbe": chr(190),
116
+ "Aacute": chr(193),
117
+ "Auml": chr(196),
118
+ "Eacute": chr(201),
119
+ "Euml": chr(203),
120
+ "Iacute": chr(205),
121
+ "Iuml": chr(207),
122
+ "Ntilde": chr(209),
123
+ "Oacute": chr(211),
124
+ "Ouml": chr(214),
125
+ "Uacute": chr(218),
126
+ "Uuml": chr(220),
127
+ "aacute": chr(225),
128
+ "auml": chr(228),
129
+ "eacute": chr(233),
130
+ "euml": chr(235),
131
+ "iacute": chr(237),
132
+ "iuml": chr(239),
133
+ "ntilde": chr(241),
134
+ "oacute": chr(243),
135
+ "ouml": chr(246),
136
+ "uacute": chr(250),
137
+ "uuml": chr(252),
138
+ "OElig": chr(338),
139
+ "oelig": chr(339),
140
+ "Scaron": chr(352),
141
+ "scaron": chr(353),
142
+ "Yuml": chr(376),
143
+ "fnof": chr(402),
144
+ "circ": chr(710),
145
+ "tilde": chr(732),
146
+ "Alpha": chr(913),
147
+ "Beta": chr(914),
148
+ "Gamma": chr(915),
149
+ "Delta": chr(916),
150
+ "Epsilon": chr(917),
151
+ "Zeta": chr(918),
152
+ "Eta": chr(919),
153
+ "Theta": chr(920),
154
+ "Iota": chr(921),
155
+ "Kappa": chr(922),
156
+ "Lambda": chr(923),
157
+ "Mu": chr(924),
158
+ "Nu": chr(925),
159
+ "Xi": chr(926),
160
+ "Omicron": chr(927),
161
+ "Pi": chr(928),
162
+ "Rho": chr(929),
163
+ "Sigma": chr(931),
164
+ "Tau": chr(932),
165
+ "Upsilon": chr(933),
166
+ "Phi": chr(934),
167
+ "Chi": chr(935),
168
+ "Psi": chr(936),
169
+ "Omega": chr(937),
170
+ "alpha": chr(945),
171
+ "beta": chr(946),
172
+ "gamma": chr(947),
173
+ "delta": chr(948),
174
+ "epsilon": chr(949),
175
+ "zeta": chr(950),
176
+ "eta": chr(951),
177
+ "theta": chr(952),
178
+ "iota": chr(953),
179
+ "kappa": chr(954),
180
+ "lambda": chr(955),
181
+ "mu": chr(956),
182
+ "nu": chr(957),
183
+ "xi": chr(958),
184
+ "omicron": chr(959),
185
+ "pi": chr(960),
186
+ "rho": chr(961),
187
+ "sigmaf": chr(962),
188
+ "sigma": chr(963),
189
+ "tau": chr(964),
190
+ "upsilon": chr(965),
191
+ "phi": chr(966),
192
+ "chi": chr(967),
193
+ "psi": chr(968),
194
+ "omega": chr(969),
195
+ "thetasym": chr(977),
196
+ "upsih": chr(978),
197
+ "piv": chr(982),
198
+ "ensp": chr(8194),
199
+ "emsp": chr(8195),
200
+ "thinsp": chr(8201),
201
+ "zwnj": chr(8204),
202
+ "zwj": chr(8205),
203
+ "lrm": chr(8206),
204
+ "rlm": chr(8207),
205
+ "ndash": chr(8211),
206
+ "mdash": chr(8212),
207
+ "lsquo": chr(8216),
208
+ "rsquo": chr(8217),
209
+ "sbquo": chr(8218),
210
+ "ldquo": chr(8220),
211
+ "rdquo": chr(8221),
212
+ "bdquo": chr(8222),
213
+ "dagger": chr(8224),
214
+ "Dagger": chr(8225),
215
+ "bull": chr(8226),
216
+ "hellip": chr(8230),
217
+ "permil": chr(8240),
218
+ "prime": chr(8242),
219
+ "Prime": chr(8243),
220
+ "lsaquo": chr(8249),
221
+ "rsaquo": chr(8250),
222
+ "oline": chr(8254),
223
+ "frasl": chr(8260),
224
+ "euro": chr(8364),
225
+ "image": chr(8465),
226
+ "weierp": chr(8472),
227
+ "real": chr(8476),
228
+ "trade": chr(8482),
229
+ "alefsym": chr(8501),
230
+ "larr": chr(8592),
231
+ "uarr": chr(8593),
232
+ "rarr": chr(8594),
233
+ "darr": chr(8595),
234
+ "harr": chr(8596),
235
+ "crarr": chr(8629),
236
+ "lArr": chr(8656),
237
+ "uArr": chr(8657),
238
+ "rArr": chr(8658),
239
+ "dArr": chr(8659),
240
+ "hArr": chr(8660),
241
+ "forall": chr(8704),
242
+ "part": chr(8706),
243
+ "exist": chr(8707),
244
+ "empty": chr(8709),
245
+ "nabla": chr(8711),
246
+ "isin": chr(8712),
247
+ "notin": chr(8713),
248
+ "ni": chr(8715),
249
+ "prod": chr(8719),
250
+ "sum": chr(8721),
251
+ "minus": chr(8722),
252
+ "lowast": chr(8727),
253
+ "radic": chr(8730),
254
+ "prop": chr(8733),
255
+ "infin": chr(8734),
256
+ "ang": chr(8736),
257
+ "and": chr(8743),
258
+ "or": chr(8744),
259
+ "cap": chr(8745),
260
+ "cup": chr(8746),
261
+ "int": chr(8747),
262
+ "there4": chr(8756),
263
+ "sim": chr(8764),
264
+ "cong": chr(8773),
265
+ "asymp": chr(8776),
266
+ "ne": chr(8800),
267
+ "equiv": chr(8801),
268
+ "le": chr(8804),
269
+ "ge": chr(8805),
270
+ "sub": chr(8834),
271
+ "sup": chr(8835),
272
+ "nsub": chr(8836),
273
+ "sube": chr(8838),
274
+ "supe": chr(8839),
275
+ "oplus": chr(8853),
276
+ "otimes": chr(8855),
277
+ "perp": chr(8869),
278
+ "sdot": chr(8901),
279
+ "lceil": chr(8968),
280
+ "rceil": chr(8969),
281
+ "lfloor": chr(8970),
282
+ "rfloor": chr(8971),
283
+ "lang": chr(9001),
284
+ "rang": chr(9002),
285
+ "loz": chr(9674),
286
+ "spades": chr(9824),
287
+ "clubs": chr(9827),
288
+ "hearts": chr(9829),
289
+ "diams": chr(9830),
290
+ }
291
+
292
+ # Construct the character to entity mapping.
293
+ _CHR2ENT = {v: "&" + k + ";" for k, v in _ENT2CHR.items()}
294
+
295
+ ####
296
+ # Internal: Alias for output.print_debug function
297
+ #########################################################################################
298
+
299
+
300
+ def _print_debug(var="", print_errors: bool = False):
301
+ """
302
+ Print the variable as a JSON-like representation for debugging purposes.
303
+
304
+ Args:
305
+ var (any): The variable to be printed.
306
+ print_errors (bool): A flag indicating whether to print errors during debugging.
307
+ """
308
+ from .output import print_debug
309
+
310
+ print_debug(var, print_errors)
311
+
312
+
313
+ ####
314
+ # Convert the input_string encoded in html entity to clear char string.
315
+ #########################################################################################
316
+ def safe_input(input_string: str = "") -> str:
317
+ """
318
+ Convert an input string encoded in HTML entities to a clear character string.
319
+
320
+ Args:
321
+ input_string (str): The input string encoded in HTML entities.
322
+
323
+ Returns:
324
+ str: The decoded clear character string.
325
+ """
326
+ if not input_string:
327
+ return ""
328
+
329
+ return "".join(_CHR2ENT.get(char, char) for char in input_string)
330
+
331
+
332
+ ####
333
+ # Convert the html entities to input_string encoded to rebuild char string.
334
+ #########################################################################################
335
+ def safe_output(input_string: str = "") -> str:
336
+ """
337
+ Convert HTML entities back to their corresponding characters in the input string.
338
+
339
+ Args:
340
+ input_string (str): The input string containing HTML entities.
341
+
342
+ Returns:
343
+ str: The decoded clear character string.
344
+ """
345
+ if not input_string:
346
+ return ""
347
+
348
+ for char, entity in _CHR2ENT.items():
349
+ input_string = input_string.replace(entity, char)
350
+
351
+ return input_string
352
+
353
+
354
+ ####
355
+ # Assign to a key in a dict a given value.
356
+ #########################################################################################
357
+
358
+
359
+ def set_dict_key_value(
360
+ input_dict: dict = {}, input_key: str = "", input_value=None
361
+ ) -> None:
362
+ """
363
+ Assign a given value to a specified key in a dictionary.
364
+
365
+ Args:
366
+ input_dict (dict): The dictionary to which the value will be assigned.
367
+ input_key (str): The key in the dictionary to which the value will be assigned.
368
+ input_value (any): The value to be assigned to the specified key.
369
+
370
+ Returns:
371
+ None
372
+ """
373
+ key = input_key.strip()
374
+
375
+ if len(key) > 0:
376
+ input_dict[key] = input_value
377
+
378
+
379
+ ####
380
+ # Return the value of a key in a given dict.
381
+ #########################################################################################
382
+
383
+
384
+ def get_dict_key_value(input_dict: dict = {}, input_key: str = "") -> None:
385
+ """
386
+ Return the value associated with a given key in a provided dictionary.
387
+
388
+ Args:
389
+ input_dict (dict): The dictionary to search for the key-value pair.
390
+ input_key (str): The key to look up in the dictionary.
391
+
392
+ Returns:
393
+ The value associated with the specified key, or None if the key is not found.
394
+ """
395
+ key = input_key.strip()
396
+
397
+ if key in input_dict:
398
+ return input_dict[key]
399
+ else:
400
+ return None
401
+
402
+
403
+ ####
404
+ # Return MD5 hash string.
405
+ #########################################################################################
406
+
407
+
408
+ def generate_md5(input_string: str = "") -> str:
409
+ """
410
+ Generates an MD5 hash for the given input string.
411
+
412
+ Args:
413
+ input_string (str): The string for which the MD5 hash will be generated.
414
+
415
+ Returns:
416
+ str: The MD5 hash of the input string as a hexadecimal string.
417
+ """
418
+ try:
419
+ md5_hash = hashlib.md5(input_string.encode()).hexdigest()
420
+ except:
421
+ md5_hash = ""
422
+
423
+ return md5_hash
424
+
425
+
426
+ ####
427
+ # Returns or print current time in date format or utimestamp.
428
+ #########################################################################################
429
+
430
+
431
+ def now(utimestamp: bool = False, print_flag: bool = False) -> str:
432
+ """
433
+ Get the current time in the specified format or as a Unix timestamp.
434
+
435
+ Args:
436
+ utimestamp (bool): Set to True to get the Unix timestamp (epoch time).
437
+ print_flag (bool): Set to True to print the time to standard output.
438
+
439
+ Returns:
440
+ str: The current time in the desired format or as a Unix timestamp.
441
+ """
442
+ from .output import print_stdout
443
+
444
+ today = datetime.today()
445
+
446
+ if utimestamp:
447
+ time = datetime.timestamp(today)
448
+ else:
449
+ time = today.strftime("%Y/%m/%d %H:%M:%S")
450
+
451
+ if print_flag:
452
+ print_stdout(time)
453
+
454
+ return time
455
+
456
+
457
+ ####
458
+ # Translate macros in string from a dict.
459
+ #########################################################################################
460
+ def translate_macros(macro_dic: dict = {}, data: str = "") -> str:
461
+ """
462
+ Replace macros in the input string with their corresponding values.
463
+
464
+ Args:
465
+ macro_dic (dict): A dictionary containing macro names and their corresponding values.
466
+ data (str): The input string in which macros should be replaced.
467
+
468
+ Returns:
469
+ str: The input string with macros replaced by their values.
470
+ """
471
+ for macro_name, macro_value in macro_dic.items():
472
+ data = data.replace(macro_name, macro_value)
473
+
474
+ return data
475
+
476
+
477
+ ####
478
+ # Parse configuration file line by line based on separator and return dict.
479
+ #########################################################################################
480
+
481
+
482
+ def parse_configuration(
483
+ file: str = "/etc/pandora/pandora_server.conf",
484
+ separator: str = " ",
485
+ default_values: dict = {},
486
+ ) -> dict:
487
+ """
488
+ Parse a configuration file and return its data as a dictionary.
489
+
490
+ Args:
491
+ file (str): The path to the configuration file. Defaults to "/etc/pandora/pandora_server.conf".
492
+ separator (str, optional): The separator between option and value. Defaults to " ".
493
+ default_values (dict, optional): A dictionary of default values. Defaults to an empty dictionary.
494
+
495
+ Returns:
496
+ dict: A dictionary containing all keys and values from the configuration file.
497
+ """
498
+ from .output import print_stderr
499
+
500
+ config = {}
501
+
502
+ try:
503
+ with open(file, "r") as conf:
504
+ lines = conf.read().splitlines()
505
+ for line in lines:
506
+ if line.strip().startswith("#") or len(line.strip()) < 1:
507
+ continue
508
+ else:
509
+ option, value = line.strip().split(separator, maxsplit=1)
510
+ config[option.strip()] = value.strip()
511
+
512
+ except Exception as e:
513
+ print_stderr(f"{type(e).__name__}: {e}")
514
+
515
+ for option, value in default_values.items():
516
+ if option.strip() not in config:
517
+ config[option.strip()] = value.strip()
518
+
519
+ return config
520
+
521
+
522
+ ####
523
+ # Parse csv file line by line and return list.
524
+ #########################################################################################
525
+
526
+
527
+ def parse_csv_file(
528
+ file: str = "",
529
+ separator: str = ";",
530
+ count_parameters: int = 0,
531
+ print_errors: bool = False,
532
+ ) -> list:
533
+ """
534
+ Parse a CSV configuration file and return its data in a list.
535
+
536
+ Args:
537
+ file (str): The path to the CSV configuration file.
538
+ separator (str, optional): The separator between values in the CSV. Defaults to ";".
539
+ count_parameters (int, optional): The minimum number of parameters each line should have. Defaults to 0.
540
+ print_errors (bool, optional): Set to True to print errors for lines with insufficient parameters. Defaults to False.
541
+
542
+ Returns:
543
+ list: A list containing lists of values for each line in the CSV.
544
+ """
545
+ from .output import print_stderr
546
+
547
+ csv_arr = []
548
+
549
+ try:
550
+ with open(file, "r") as csv:
551
+ lines = csv.read().splitlines()
552
+ for line in lines:
553
+ if line.strip().startswith("#") or len(line.strip()) < 1:
554
+ continue
555
+ else:
556
+ value = line.strip().split(separator)
557
+ if len(value) >= count_parameters:
558
+ csv_arr.append(value)
559
+ elif print_errors == True:
560
+ print_stderr(
561
+ f"Csv line: {line} does not match minimun parameter defined: {count_parameters}"
562
+ )
563
+
564
+ except Exception as e:
565
+ print_stderr(f"{type(e).__name__}: {e}")
566
+
567
+ return csv_arr
568
+
569
+
570
+ ####
571
+ # Parse given variable to integer.
572
+ #########################################################################################
573
+
574
+
575
+ def parse_int(var=None) -> int:
576
+ """
577
+ Parse given variable to integer.
578
+
579
+ Args:
580
+ var (any): The variable to be parsed as an integer.
581
+
582
+ Returns:
583
+ int: The parsed integer value. If parsing fails, returns 0.
584
+ """
585
+ try:
586
+ return int(var)
587
+ except:
588
+ return 0
589
+
590
+
591
+ ####
592
+ # Parse given variable to float.
593
+ #########################################################################################
594
+
595
+
596
+ def parse_float(var=None) -> float:
597
+ """
598
+ Parse given variable to float.
599
+
600
+ Args:
601
+ var (any): The variable to be parsed as an float.
602
+
603
+ Returns:
604
+ float: The parsed float value. If parsing fails, returns 0.
605
+ """
606
+ try:
607
+ return float(var)
608
+ except:
609
+ return 0
610
+
611
+
612
+ ####
613
+ # Parse given variable to string.
614
+ #########################################################################################
615
+
616
+
617
+ def parse_str(var=None) -> str:
618
+ """
619
+ Parse given variable to string.
620
+
621
+ Args:
622
+ var (any): The variable to be parsed as an string.
623
+
624
+ Returns:
625
+ str: The parsed string value. If parsing fails, returns "".
626
+ """
627
+ try:
628
+ return str(var)
629
+ except:
630
+ return ""
631
+
632
+
633
+ ####
634
+ # Parse given variable to bool.
635
+ #########################################################################################
636
+
637
+
638
+ def parse_bool(var=None) -> bool:
639
+ """
640
+ Parse given variable to bool.
641
+
642
+ Args:
643
+ var (any): The variable to be parsed as an bool.
644
+
645
+ Returns:
646
+ bool: The parsed bool value. If parsing fails, returns False.
647
+ """
648
+ try:
649
+ return bool(var)
650
+ except:
651
+ return False
652
+
653
+
654
+ ####
655
+ # Return base64 string.
656
+ #########################################################################################
657
+
658
+
659
+ def encode_string(input_string: str) -> str:
660
+ """
661
+ method to convert string to base64 encoded string
662
+ Args:
663
+ input_string (str): string to encode
664
+ Returns:
665
+ str: base64 encoded string
666
+ """
667
+ return base64.b64encode(input_string.encode("utf-8")).decode("utf-8")
668
+
669
+
670
+ ####
671
+ # Return decode base64 string.
672
+ #########################################################################################
673
+
674
+
675
+ def decode_string(base_string) -> str:
676
+ """
677
+ method to convert base64 encoded string to string
678
+ Args:
679
+ base_string (str): string to decode
680
+ Returns:
681
+ str: decoded string
682
+ """
683
+ return base64.b64decode(base_string).decode("utf-8")