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 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
|
14
|
|
|
# package regular expressions
|
15
|
|
|
import re
|
16
|
|
|
|
17
|
|
|
|
18
|
|
|
class BasicNeeds:
|
19
|
|
|
cfg_dtls = {}
|
20
|
|
|
|
21
|
|
|
def fn_check_inputs(self, input_parameters):
|
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_handler = open(file=file_to_evaluate, mode='r', encoding='mbcs')
|
60
|
|
|
except UnicodeDecodeError:
|
61
|
|
|
file_handler = open(file=file_to_evaluate, mode='r', encoding='utf-8')
|
62
|
|
|
file_content = file_handler.read().encode()
|
63
|
|
|
file_handler.close()
|
64
|
|
|
file_checksums = {
|
65
|
|
|
'md5': hashlib.md5(file_content).hexdigest(),
|
66
|
|
|
'sha1': hashlib.sha1(file_content).hexdigest(),
|
67
|
|
|
'sha256': hashlib.sha256(file_content).hexdigest(),
|
68
|
|
|
'sha512': hashlib.sha512(file_content).hexdigest(),
|
69
|
|
|
}
|
70
|
|
|
f_dts = {
|
71
|
|
|
'created': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
|
72
|
|
|
'modified': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
|
73
|
|
|
}
|
74
|
|
|
return {
|
75
|
|
|
'date when created': datetime.strftime(f_dts['created'], '%Y-%m-%d %H:%M:%S.%f'),
|
76
|
|
|
'date when last modified': datetime.strftime(f_dts['modified'], '%Y-%m-%d %H:%M:%S.%f'),
|
77
|
|
|
'size [bytes]': os.path.getsize(file_to_evaluate),
|
78
|
|
|
'MD5-Checksum': file_checksums['md5'],
|
79
|
|
|
'SHA256-Checksum': file_checksums['sha256'],
|
80
|
|
|
'SHA512-Checksum': file_checksums['sha512'],
|
81
|
|
|
}
|
82
|
|
|
|
83
|
|
|
def fn_load_configuration(self, in_configuration_file):
|
84
|
|
|
self.cfg_dtls = self.fn_open_file_and_get_content(in_configuration_file)
|
85
|
|
|
|
86
|
|
|
@staticmethod
|
87
|
|
|
def fn_multi_line_string_to_single_line(input_string):
|
88
|
|
|
string_to_return = input_string.replace('\n', ' ').replace('\r', ' ')
|
89
|
|
|
return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip()
|
90
|
|
|
|
91
|
|
|
@staticmethod
|
92
|
|
|
def fn_numbers_with_leading_zero(input_number_as_string, digits):
|
93
|
|
|
final_number = input_number_as_string
|
94
|
|
|
if len(input_number_as_string) < digits:
|
95
|
|
|
final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string
|
96
|
|
|
return final_number
|
97
|
|
|
|
98
|
|
|
def fn_open_file_and_get_content(self, input_file, content_type='json'):
|
99
|
|
|
if os.path.isfile(input_file):
|
100
|
|
|
with open(input_file, 'r') as file_handler:
|
101
|
|
|
self.fn_timestamped_print('I have opened file: ' + input_file)
|
102
|
|
|
return self.fn_get_file_content(file_handler, content_type)
|
103
|
|
|
else:
|
104
|
|
|
self.fn_timestamped_print('Given file ' + input_file
|
105
|
|
|
+ ' does not exist, please check your inputs!')
|
106
|
|
|
|
107
|
|
|
def fn_optional_print(self, boolean_variable, string_to_print):
|
108
|
|
|
if boolean_variable:
|
109
|
|
|
self.fn_timestamped_print(string_to_print)
|
110
|
|
|
|
111
|
|
|
def fn_store_file_statistics(self, local_logger, timmer, file_name, file_meaning):
|
112
|
|
|
timmer.start()
|
113
|
|
|
file_name_variable_type = str(type(file_name))
|
114
|
|
|
list_file_names = [file_name]
|
115
|
|
|
if file_name_variable_type == "<class 'list'>":
|
116
|
|
|
list_file_names = file_name
|
117
|
|
|
for current_file_name in list_file_names:
|
118
|
|
|
local_logger.info(file_meaning + ' file "' + current_file_name
|
119
|
|
|
+ '" has the following characteristics: '
|
120
|
|
|
+ str(self.fn_get_file_statistics(current_file_name)))
|
121
|
|
|
timmer.stop()
|
122
|
|
|
|
123
|
|
|
@staticmethod
|
124
|
|
|
def fn_timestamped_print(string_to_print):
|
125
|
|
|
print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") + ' - ' + string_to_print)
|
126
|
|
|
|
127
|
|
|
@staticmethod
|
128
|
|
|
def fn_validate_one_value(value_to_validate, validation_type, name_meaning):
|
129
|
|
|
is_fatal_error = False
|
130
|
|
|
message = ''
|
131
|
|
|
if validation_type == 'file':
|
132
|
|
|
is_fatal_error = (not os.path.isfile(value_to_validate))
|
133
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \
|
134
|
|
|
+ '" does not exist, please check your inputs!'
|
135
|
|
|
elif validation_type == 'folder':
|
136
|
|
|
is_fatal_error = (not os.path.isdir(value_to_validate))
|
137
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \
|
138
|
|
|
+ '" does not exist, please check your inputs!'
|
139
|
|
|
elif validation_type == 'url':
|
140
|
|
|
url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})'
|
141
|
|
|
is_fatal_error = (not re.match(url_reg_expression, value_to_validate))
|
142
|
|
|
message = 'Given ' + name_meaning + ' "' + value_to_validate \
|
143
|
|
|
+ '" does not seem a valid one, please check your inputs!'
|
144
|
|
|
return {
|
145
|
|
|
'is_fatal_error': is_fatal_error,
|
146
|
|
|
'message': message,
|
147
|
|
|
}
|
148
|
|
|
|
149
|
|
|
def fn_validate_single_value(self, value_to_validate, validation_type, name_meaning):
|
150
|
|
|
validation_details = self.fn_validate_one_value(value_to_validate, validation_type,
|
151
|
|
|
name_meaning)
|
152
|
|
|
if validation_details['is_fatal_error']:
|
153
|
|
|
self.fn_timestamped_print(validation_details['message'])
|
154
|
|
|
exit(1)
|
155
|
|
|
|