|
1
|
|
|
""" |
|
2
|
|
|
BasicNeeds - useful functions library |
|
3
|
|
|
|
|
4
|
|
|
This library has functions useful to keep main logic short and simple |
|
5
|
|
|
""" |
|
6
|
|
|
# package to handle date and times |
|
7
|
|
|
from datetime import date, datetime, timedelta |
|
8
|
|
|
# package to use for checksum calculations (in this file) |
|
9
|
|
|
import hashlib |
|
10
|
|
|
# package to handle json files |
|
11
|
|
|
import json |
|
12
|
|
|
# package to handle files/folders and related metadata/operations |
|
13
|
|
|
import os.path |
|
14
|
|
|
# package regular expressions |
|
15
|
|
|
import re |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
class BasicNeeds: |
|
19
|
|
|
cfg_dtls = {} |
|
20
|
|
|
|
|
21
|
|
|
def fn_check_inputs(self, input_parameters, input_script): |
|
22
|
|
|
if input_parameters.output_log_file is not None: |
|
23
|
|
|
# checking log folder first as there's all further messages will be stored |
|
24
|
|
|
self.fn_validate_single_value(os.path.dirname(input_parameters.output_log_file), |
|
25
|
|
|
'folder', 'log file') |
|
26
|
|
|
|
|
27
|
|
|
def fn_final_message(self, local_logger, log_file_name, performance_in_seconds): |
|
28
|
|
|
total_time_string = str(timedelta(seconds=performance_in_seconds)) |
|
29
|
|
|
if log_file_name == 'None': |
|
30
|
|
|
self.fn_timestamped_print('Application finished, whole script took ' |
|
31
|
|
|
+ total_time_string) |
|
32
|
|
|
else: |
|
33
|
|
|
local_logger.info(f'Total execution time was ' + total_time_string) |
|
34
|
|
|
self.fn_timestamped_print('Application finished, ' |
|
35
|
|
|
+ 'for complete logged details please check ' |
|
36
|
|
|
+ log_file_name) |
|
37
|
|
|
|
|
38
|
|
|
def fn_get_file_content(self, in_file_handler, in_content_type): |
|
39
|
|
|
if in_content_type == 'json': |
|
40
|
|
|
try: |
|
41
|
|
|
json_interpreted_details = json.load(in_file_handler) |
|
42
|
|
|
self.fn_timestamped_print('I have interpreted JSON structure from given file') |
|
43
|
|
|
return json_interpreted_details |
|
44
|
|
|
except Exception as e: |
|
45
|
|
|
self.fn_timestamped_print('Error encountered when trying to interpret JSON') |
|
46
|
|
|
print(e) |
|
47
|
|
|
elif in_content_type == 'raw': |
|
48
|
|
|
raw_interpreted_file = in_file_handler.read() |
|
49
|
|
|
self.fn_timestamped_print('I have read file entire content') |
|
50
|
|
|
return raw_interpreted_file |
|
51
|
|
|
else: |
|
52
|
|
|
self.fn_timestamped_print('Unknown content type provided, ' |
|
53
|
|
|
+ 'expected either "json" or "raw" but got ' |
|
54
|
|
|
+ in_content_type) |
|
55
|
|
|
|
|
56
|
|
|
@staticmethod |
|
57
|
|
|
def fn_get_file_statistics(file_to_evaluate): |
|
58
|
|
|
try: |
|
59
|
|
|
file_sha512 = hashlib.sha512(open(file=file_to_evaluate, mode='r', encoding='utf-8')\ |
|
60
|
|
|
.read().encode()).hexdigest() |
|
61
|
|
|
except UnicodeDecodeError: |
|
62
|
|
|
file_sha512 = hashlib.sha512(open(file=file_to_evaluate, mode='r', encoding='mbcs')\ |
|
63
|
|
|
.read().encode()).hexdigest() |
|
64
|
|
|
file_dates = { |
|
65
|
|
|
'created': os.path.getctime(file_to_evaluate), |
|
66
|
|
|
'modified': os.path.getctime(file_to_evaluate), |
|
67
|
|
|
} |
|
68
|
|
|
file_info = { |
|
69
|
|
|
'date when created': date.strftime(datetime.fromtimestamp(file_dates['created']), |
|
70
|
|
|
'%Y-%m-%d %H:%M:%S.%f'), |
|
71
|
|
|
'date when last modified': date.strftime(datetime.fromtimestamp(file_dates['modified']), |
|
72
|
|
|
'%Y-%m-%d %H:%M:%S.%f'), |
|
73
|
|
|
'size [bytes]': os.path.getsize(file_to_evaluate), |
|
74
|
|
|
'SHA512-Checksum': file_sha512, |
|
75
|
|
|
} |
|
76
|
|
|
return file_info |
|
77
|
|
|
|
|
78
|
|
|
def fn_load_configuration(self): |
|
79
|
|
|
relevant_file = os.path.join(os.path.dirname(__file__), 'config.json') |
|
80
|
|
|
self.cfg_dtls = self.fn_open_file_and_get_content(relevant_file) |
|
81
|
|
|
|
|
82
|
|
|
@staticmethod |
|
83
|
|
|
def fn_multi_line_string_to_single_line(input_string): |
|
84
|
|
|
string_to_return = input_string.replace('\n', ' ').replace('\r', ' ') |
|
85
|
|
|
return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip() |
|
86
|
|
|
|
|
87
|
|
|
@staticmethod |
|
88
|
|
|
def fn_numbers_with_leading_zero(input_number_as_string, digits): |
|
89
|
|
|
final_number = input_number_as_string |
|
90
|
|
|
if len(input_number_as_string) < digits: |
|
91
|
|
|
final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string |
|
92
|
|
|
return final_number |
|
93
|
|
|
|
|
94
|
|
|
def fn_open_file_and_get_content(self, input_file, content_type='json'): |
|
95
|
|
|
if os.path.isfile(input_file): |
|
96
|
|
|
with open(input_file, 'r') as file_handler: |
|
97
|
|
|
self.fn_timestamped_print('I have opened file: ' + input_file) |
|
98
|
|
|
return self.fn_get_file_content(file_handler, content_type) |
|
99
|
|
|
else: |
|
100
|
|
|
self.fn_timestamped_print('Given file ' + input_file |
|
101
|
|
|
+ ' does not exist, please check your inputs!') |
|
102
|
|
|
|
|
103
|
|
|
def fn_optional_print(self, boolean_variable, string_to_print): |
|
104
|
|
|
if boolean_variable: |
|
105
|
|
|
self.fn_timestamped_print(string_to_print) |
|
106
|
|
|
|
|
107
|
|
|
def fn_store_file_statistics(self, local_logger, timmer, file_name, file_meaning): |
|
108
|
|
|
timmer.start() |
|
109
|
|
|
file_name_variable_type = str(type(file_name)) |
|
110
|
|
|
list_file_names = [file_name] |
|
111
|
|
|
if file_name_variable_type == "<class 'list'>": |
|
112
|
|
|
list_file_names = file_name |
|
113
|
|
|
for current_file_name in list_file_names: |
|
114
|
|
|
local_logger.info(file_meaning + ' file "' + current_file_name |
|
115
|
|
|
+ '" has the following characteristics: ' |
|
116
|
|
|
+ str(self.fn_get_file_statistics(current_file_name))) |
|
117
|
|
|
timmer.stop() |
|
118
|
|
|
|
|
119
|
|
|
@staticmethod |
|
120
|
|
|
def fn_timestamped_print(string_to_print): |
|
121
|
|
|
print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") |
|
122
|
|
|
+ ' - ' + string_to_print) |
|
123
|
|
|
|
|
124
|
|
|
@staticmethod |
|
125
|
|
|
def fn_validate_one_value(value_to_validate, validation_type, name_meaning): |
|
126
|
|
|
is_fatal_error = False |
|
127
|
|
|
message = '' |
|
128
|
|
|
if validation_type == 'file': |
|
129
|
|
|
is_fatal_error = (not os.path.isfile(value_to_validate)) |
|
130
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \ |
|
131
|
|
|
+ '" does not exist, please check your inputs!' |
|
132
|
|
|
elif validation_type == 'folder': |
|
133
|
|
|
is_fatal_error = (not os.path.isdir(value_to_validate)) |
|
134
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \ |
|
135
|
|
|
+ '" does not exist, please check your inputs!' |
|
136
|
|
|
elif validation_type == 'url': |
|
137
|
|
|
url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})' |
|
138
|
|
|
is_fatal_error = (not re.match(url_reg_expression, value_to_validate)) |
|
139
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \ |
|
140
|
|
|
+ '" does not seem a valid one, please check your inputs!' |
|
141
|
|
|
return { |
|
142
|
|
|
'is_fatal_error': is_fatal_error, |
|
143
|
|
|
'message': message, |
|
144
|
|
|
} |
|
145
|
|
|
|
|
146
|
|
|
def fn_validate_single_value(self, value_to_validate, validation_type, name_meaning): |
|
147
|
|
|
validation_details = self.fn_validate_one_value(value_to_validate, validation_type, |
|
148
|
|
|
name_meaning) |
|
149
|
|
|
if validation_details['is_fatal_error']: |
|
150
|
|
|
self.fn_timestamped_print(validation_details['message']) |
|
151
|
|
|
exit(1) |
|
152
|
|
|
|