1
|
|
|
""" |
2
|
|
|
facilitates File Operations |
3
|
|
|
""" |
4
|
|
|
# package to handle date and times |
5
|
|
|
from datetime import datetime |
6
|
|
|
# package to add support for multi-language (i18n) |
7
|
|
|
import gettext |
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 facilitate operating system operations |
13
|
|
|
import os |
14
|
|
|
# package to facilitate os path manipulations |
15
|
|
|
import pathlib |
16
|
|
|
# package regular expressions |
17
|
|
|
import re |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
class FileOperations: |
21
|
|
|
timestamp_format = '%Y-%m-%d %H:%M:%S.%f %Z' |
22
|
|
|
lcl = None |
23
|
|
|
|
24
|
|
|
def __init__(self, default_language='en_US'): |
25
|
|
|
current_script = os.path.basename(__file__).replace('.py', '') |
26
|
|
|
lang_folder = os.path.join(os.path.dirname(__file__), current_script + '_Locale') |
27
|
|
|
self.lcl = gettext.translation(current_script, lang_folder, languages=[default_language]) |
28
|
|
|
|
29
|
|
|
def build_file_list(self, local_logger, timmer, given_input_file): |
30
|
|
|
if re.search(r'(\*|\?)*', given_input_file): |
31
|
|
|
local_logger.debug(self.lcl.gettext('File matching pattern identified')) |
32
|
|
|
parent_directory = os.path.dirname(given_input_file) |
33
|
|
|
# loading from a specific folder all files matching a given pattern into a file list |
34
|
|
|
relevant_files_list = self.fn_build_relevant_file_list(local_logger, timmer, |
35
|
|
|
parent_directory, |
36
|
|
|
given_input_file) |
37
|
|
|
else: |
38
|
|
|
local_logger.debug(self.lcl.gettext('Specific file name provided')) |
39
|
|
|
relevant_files_list = [given_input_file] |
40
|
|
|
return relevant_files_list |
41
|
|
|
|
42
|
|
|
def fn_build_file_list(self, local_logger, working_path, matching_pattern): |
43
|
|
|
resulted_file_list = [] |
44
|
|
|
file_counter = 0 |
45
|
|
|
for current_file in working_path.iterdir(): |
46
|
|
|
if current_file.is_file() and current_file.match(matching_pattern): |
47
|
|
|
resulted_file_list.append(file_counter) |
48
|
|
|
resulted_file_list[file_counter] = str(current_file.absolute()) |
49
|
|
|
local_logger.info(self.lcl.gettext('{file_name} identified') \ |
50
|
|
|
.replace('{file_name}', str(current_file.absolute()))) |
51
|
|
|
file_counter = file_counter + 1 |
52
|
|
|
return resulted_file_list |
53
|
|
|
|
54
|
|
|
def fn_build_relevant_file_list(self, local_logger, timmer, in_folder, matching_pattern): |
55
|
|
|
timmer.start() |
56
|
|
|
local_logger.info(self.lcl.gettext('Listing all files within {in_folder} folder ' |
57
|
|
|
+ 'looking for {matching_pattern} as matching pattern') \ |
58
|
|
|
.replace('{in_folder}', in_folder) \ |
59
|
|
|
.replace('{matching_pattern}', matching_pattern)) |
60
|
|
|
list_files = [] |
61
|
|
|
if os.path.isdir(in_folder): |
62
|
|
|
working_path = pathlib.Path(in_folder) |
63
|
|
|
list_files = self.fn_build_file_list(local_logger, working_path, matching_pattern) |
64
|
|
|
file_counter = len(list_files) |
65
|
|
|
local_logger.info(self.lcl.ngettext( \ |
66
|
|
|
'{files_counted} file from {in_folder} folder identified', |
67
|
|
|
'{files_counted} files from {in_folder} folder identified', file_counter) \ |
68
|
|
|
.replace('{files_counted}', str(file_counter)) \ |
69
|
|
|
.replace('{in_folder}', in_folder)) |
70
|
|
|
else: |
71
|
|
|
local_logger.error(self.lcl.gettext('Folder {folder_name} does not exist') \ |
72
|
|
|
.replace('{folder_name}', in_folder)) |
73
|
|
|
timmer.stop() |
74
|
|
|
return list_files |
75
|
|
|
|
76
|
|
|
def fn_get_file_content(self, in_file_handler, in_file_type): |
77
|
|
|
if in_file_type == 'json': |
78
|
|
|
try: |
79
|
|
|
json_interpreted_details = json.load(in_file_handler) |
80
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
81
|
|
|
self.lcl.gettext('JSON structure interpreted')) |
82
|
|
|
return json_interpreted_details |
83
|
|
|
except Exception as e: |
84
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
85
|
|
|
self.lcl.gettext('Error encountered when trying to interpret JSON')) |
86
|
|
|
print(e) |
87
|
|
|
elif in_file_type == 'raw': |
88
|
|
|
raw_interpreted_file = in_file_handler.read() |
89
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
90
|
|
|
self.lcl.gettext('Entire file content read')) |
91
|
|
|
return raw_interpreted_file |
92
|
|
|
else: |
93
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
94
|
|
|
self.lcl.gettext('Unknown file type provided, ' |
95
|
|
|
+ 'expected either "json" or "raw" but got {in_file_type}') \ |
96
|
|
|
.replace('{in_file_type}', in_file_type)) |
97
|
|
|
|
98
|
|
|
@staticmethod |
99
|
|
|
def fn_get_file_dates(file_to_evaluate): |
100
|
|
|
return { |
101
|
|
|
'created': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)), |
102
|
|
|
'last modified': datetime.fromtimestamp(os.path.getmtime(file_to_evaluate)), |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
def fn_get_file_simple_statistics(self, file_to_evaluate): |
106
|
|
|
file_date_time = self.fn_get_file_dates(file_to_evaluate) |
107
|
|
|
return { |
108
|
|
|
'date when created': datetime.strftime(file_date_time['created'], |
109
|
|
|
self.timestamp_format).strip(), |
110
|
|
|
'date when last modified': datetime.strftime(file_date_time['last modified'], |
111
|
|
|
self.timestamp_format).strip(), |
112
|
|
|
'size [bytes]': os.path.getsize(file_to_evaluate), |
113
|
|
|
} |
114
|
|
|
|
115
|
|
|
def fn_get_file_statistics(self, file_to_evaluate): |
116
|
|
|
file_statistics = self.fn_get_file_simple_statistics(file_to_evaluate) |
117
|
|
|
try: |
118
|
|
|
file_handler = open(file=file_to_evaluate, mode='r', encoding='mbcs') |
119
|
|
|
except UnicodeDecodeError: |
120
|
|
|
file_handler = open(file=file_to_evaluate, mode='r', encoding='utf-8') |
121
|
|
|
file_content = file_handler.read().encode() |
122
|
|
|
file_handler.close() |
123
|
|
|
file_statistics['MD5 Checksum'] = hashlib.md5(file_content).hexdigest() |
124
|
|
|
file_statistics['SHA1 Checksum'] = hashlib.sha1(file_content).hexdigest() |
125
|
|
|
file_statistics['SHA224 Checksum'] = hashlib.sha224(file_content).hexdigest() |
126
|
|
|
file_statistics['SHA256 Checksum'] = hashlib.sha256(file_content).hexdigest() |
127
|
|
|
file_statistics['SHA384 Checksum'] = hashlib.sha384(file_content).hexdigest() |
128
|
|
|
file_statistics['SHA512 Checksum'] = hashlib.sha512(file_content).hexdigest() |
129
|
|
|
return file_statistics |
130
|
|
|
|
131
|
|
|
def fn_get_file_datetime_verdict(self, local_logger, file_to_evaluate, |
132
|
|
|
created_or_modified, reference_datetime): |
133
|
|
|
implemented_choices = ['created', 'last modified'] |
134
|
|
|
verdict = self.lcl.gettext('unknown') |
135
|
|
|
file_date_time = self.fn_get_file_dates(file_to_evaluate) |
136
|
|
|
if created_or_modified in implemented_choices: |
137
|
|
|
which_datetime = file_date_time.get(created_or_modified) |
138
|
|
|
verdict = self.lcl.gettext('older') |
139
|
|
|
if which_datetime > reference_datetime: |
140
|
|
|
verdict = self.lcl.gettext('newer') |
141
|
|
|
elif which_datetime == reference_datetime: |
142
|
|
|
verdict = self.lcl.gettext('same') |
143
|
|
|
str_file_datetime = datetime.strftime(which_datetime, self.timestamp_format).strip() |
144
|
|
|
str_reference = datetime.strftime(reference_datetime, self.timestamp_format).strip() |
145
|
|
|
local_logger.debug(self.lcl.gettext( \ |
146
|
|
|
'File "{file_name}" which has the {created_or_modified} datetime ' |
147
|
|
|
+ 'as "{file_datetime}" vs. "{reference_datetime}" ' |
148
|
|
|
+ 'has a verdict = {verdict}') \ |
149
|
|
|
.replace('{file_name}', str(file_to_evaluate)) \ |
150
|
|
|
.replace('{created_or_modified}', |
151
|
|
|
self.lcl.gettext(created_or_modified)) \ |
152
|
|
|
.replace('{reference_datetime}', str_reference) \ |
153
|
|
|
.replace('{file_datetime}', str_file_datetime) \ |
154
|
|
|
.replace('{verdict}', verdict)) |
155
|
|
|
else: |
156
|
|
|
local_logger.error(self.lcl.gettext( \ |
157
|
|
|
'Unknown file datetime choice, ' |
158
|
|
|
+ 'expected is one of the following choices "{implemented_choices}" ' |
159
|
|
|
+ 'but provided was "{created_or_modified}"...') \ |
160
|
|
|
.replace('{implemented_choices}', '", "'.join(implemented_choices)) \ |
161
|
|
|
.replace('{created_or_modified}', created_or_modified)) |
162
|
|
|
return verdict |
163
|
|
|
|
164
|
|
|
def fn_move_files(self, local_logger, timmer, file_names, destination_folder): |
165
|
|
|
timmer.start() |
166
|
|
|
resulted_files = [] |
167
|
|
|
for current_file in file_names: |
168
|
|
|
source_folder = os.path.dirname(current_file) |
169
|
|
|
new_file_name = current_file.replace(source_folder, destination_folder) |
170
|
|
|
if os.path.isfile(new_file_name): |
171
|
|
|
local_logger.warning(self.lcl.gettext('File {file_name} will be overwritten') \ |
172
|
|
|
.replace('{file_name}', current_file)) |
173
|
|
|
os.replace(current_file, new_file_name) |
174
|
|
|
local_logger.info(self.lcl.gettext( \ |
175
|
|
|
'File {file_name} has just been been overwritten as {new_file_name}') \ |
176
|
|
|
.replace('{file_name}', current_file) \ |
177
|
|
|
.replace('{new_file_name}', current_file)) |
178
|
|
|
else: |
179
|
|
|
local_logger.info(self.lcl.gettext( \ |
180
|
|
|
'File {file_name} will be renamed as {new_file_name}') \ |
181
|
|
|
.replace('{file_name}', current_file) \ |
182
|
|
|
.replace('{new_file_name}', current_file)) |
183
|
|
|
os.rename(current_file, new_file_name) |
184
|
|
|
local_logger.info(self.lcl.gettext( \ |
185
|
|
|
'File {file_name} has just been renamed as {new_file_name}') \ |
186
|
|
|
.replace('{file_name}', current_file) \ |
187
|
|
|
.replace('{new_file_name}', current_file)) |
188
|
|
|
resulted_files.append(str(new_file_name)) |
189
|
|
|
timmer.stop() |
190
|
|
|
return resulted_files |
191
|
|
|
|
192
|
|
|
def fn_open_file_and_get_content(self, input_file, content_type='json'): |
193
|
|
|
if os.path.isfile(input_file): |
194
|
|
|
with open(input_file, 'r') as file_handler: |
195
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
196
|
|
|
self.lcl.gettext('File {file_name} has just been opened') \ |
197
|
|
|
.replace('{file_name}', str(input_file))) |
198
|
|
|
return self.fn_get_file_content(file_handler, content_type) |
199
|
|
|
else: |
200
|
|
|
print(datetime.utcnow().strftime(self.timestamp_format) + |
201
|
|
|
self.lcl.gettext('File {file_name} does not exist') \ |
202
|
|
|
.replace('{file_name}', str(input_file))) |
203
|
|
|
|
204
|
|
|
def fn_store_file_statistics(self, local_logger, timmer, file_name, file_meaning): |
205
|
|
|
timmer.start() |
206
|
|
|
list_file_names = [file_name] |
207
|
|
|
if type(file_name) == list: |
208
|
|
|
list_file_names = file_name |
209
|
|
|
for current_file_name in list_file_names: |
210
|
|
|
file_statistics = str(self.fn_get_file_statistics(current_file_name)) \ |
211
|
|
|
.replace('date when created', self.lcl.gettext('date when created')) \ |
212
|
|
|
.replace('date when last modified', self.lcl.gettext('date when last modified')) \ |
213
|
|
|
.replace('size [bytes]', self.lcl.gettext('size [bytes]')) \ |
214
|
|
|
.replace('Checksum', self.lcl.gettext('Checksum')) |
215
|
|
|
local_logger.info(self.lcl.gettext( \ |
216
|
|
|
'File "{file_name}" has the following characteristics: {file_statistics}') \ |
217
|
|
|
.replace('{file_meaning}', file_meaning) \ |
218
|
|
|
.replace('{file_name}', current_file_name) \ |
219
|
|
|
.replace('{file_statistics}', file_statistics)) |
220
|
|
|
timmer.stop() |
221
|
|
|
|