Passed
Push — master ( cb176a...4b8481 )
by
unknown
13:30
created

core.datarepairfile.DataRepairFileItem.on_get()   B

Complexity

Conditions 5

Size

Total Lines 33
Code Lines 27

Duplication

Lines 33
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 27
dl 33
loc 33
rs 8.7653
c 0
b 0
f 0
cc 5
nop 3
1
import os
2
import uuid
3
from datetime import datetime, timezone, timedelta
4
import falcon
5
import mysql.connector
6
import simplejson as json
7
from core.useractivity import user_logger, admin_control
8
import config
9
10
11 View Code Duplication
class DataRepairFileCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
12
    def __init__(self):
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        _ = req
18
        resp.status = falcon.HTTP_200
19
20
    @staticmethod
21
    def on_get(req, resp):
22
        admin_control(req)
23
        cnx = mysql.connector.connect(**config.myems_historical_db)
24
        cursor = cnx.cursor()
25
26
        query = (" SELECT id, file_name, uuid, upload_datetime_utc, status "
27
                 " FROM tbl_data_repair_files "
28
                 " ORDER BY upload_datetime_utc desc ")
29
        cursor.execute(query)
30
        rows = cursor.fetchall()
31
        cursor.close()
32
        cnx.close()
33
34
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
35
        if config.utc_offset[0] == '-':
36
            timezone_offset = -timezone_offset
37
38
        result = list()
39
        if rows is not None and len(rows) > 0:
40
            for row in rows:
41
                meta_result = {"id": row[0],
42
                               "file_name": row[1],
43
                               "uuid": row[2],
44
                               "upload_datetime": (row[3].replace(tzinfo=timezone.utc)
45
                                                   + timedelta(minutes=timezone_offset)).isoformat()[0:19],
46
                               "status": row[4]}
47
                result.append(meta_result)
48
49
        resp.text = json.dumps(result)
50
51
    @staticmethod
52
    @user_logger
53
    def on_post(req, resp):
54
        """Handles POST requests"""
55
        admin_control(req)
56
        try:
57
            upload = req.get_param('file')
58
            # Read upload file as binary
59
            raw_blob = upload.file.read()
60
61
            # Retrieve filename
62
            filename = upload.filename
63
            file_uuid = str(uuid.uuid4())
64
65
            # Define file_path
66
            file_path = os.path.join(config.upload_path, file_uuid)
67
68
            # Write to a temporary file to prevent incomplete files from being used.
69
            with open(file_path + '~', 'wb') as f:
70
                f.write(raw_blob)
71
72
            # Now that we know the file has been fully saved to disk move it into place.
73
            os.rename(file_path + '~', file_path)
74
        except OSError as ex:
75
            print("Failed to stream request")
76
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
77
                                   description='API.FAILED_TO_UPLOAD_DATA_REPAIR_FILE')
78
        except Exception as ex:
79
            print(str(ex))
80
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
81
                                   description='API.FAILED_TO_UPLOAD_DATA_REPAIR_FILE')
82
83
        # Verify User Session
84
        token = req.headers.get('TOKEN')
85
        user_uuid = req.headers.get('USER-UUID')
86
        if token is None:
87
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
88
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
89
        if user_uuid is None:
90
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
91
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
92
93
        cnx = mysql.connector.connect(**config.myems_user_db)
94
        cursor = cnx.cursor()
95
96
        query = (" SELECT utc_expires "
97
                 " FROM tbl_sessions "
98
                 " WHERE user_uuid = %s AND token = %s")
99
        cursor.execute(query, (user_uuid, token,))
100
        row = cursor.fetchone()
101
102
        if row is None:
103
            if cursor:
104
                cursor.close()
105
            if cnx:
106
                cnx.close()
107
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
108
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
109
        else:
110
            utc_expires = row[0]
111
            if datetime.utcnow() > utc_expires:
112
                if cursor:
113
                    cursor.close()
114
                if cnx:
115
                    cnx.close()
116
                raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
117
                                       description='API.USER_SESSION_TIMEOUT')
118
119
        cursor.execute(" SELECT id "
120
                       " FROM tbl_users "
121
                       " WHERE uuid = %s ",
122
                       (user_uuid,))
123
        row = cursor.fetchone()
124
        if row is None:
125
            if cursor:
126
                cursor.close()
127
            if cnx:
128
                cnx.close()
129
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
130
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
131
132
        cnx = mysql.connector.connect(**config.myems_historical_db)
133
        cursor = cnx.cursor()
134
135
        add_values = (" INSERT INTO tbl_data_repair_files "
136
                      " (file_name, uuid, upload_datetime_utc, status, file_object ) "
137
                      " VALUES (%s, %s, %s, %s, %s) ")
138
        cursor.execute(add_values, (filename,
139
                                    file_uuid,
140
                                    datetime.utcnow(),
141
                                    'new',
142
                                    raw_blob))
143
        new_id = cursor.lastrowid
144
        cnx.commit()
145
        cursor.close()
146
        cnx.close()
147
148
        resp.status = falcon.HTTP_201
149
        resp.location = '/datarepairfiles/' + str(new_id)
150
151
152 View Code Duplication
class DataRepairFileItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
153
    def __init__(self):
154
        pass
155
156
    @staticmethod
157
    def on_options(req, resp, id_):
158
        _ = req
159
        resp.status = falcon.HTTP_200
160
        _ = id_
161
162
    @staticmethod
163
    def on_get(req, resp, id_):
164
        admin_control(req)
165
        if not id_.isdigit() or int(id_) <= 0:
166
            raise falcon.HTTPError(status=falcon.HTTP_400,
167
                                   title='API.BAD_REQUEST',
168
                                   description='API.INVALID_DATA_REPAIR_FILE_ID')
169
170
        cnx = mysql.connector.connect(**config.myems_historical_db)
171
        cursor = cnx.cursor()
172
173
        query = (" SELECT id, file_name, uuid, upload_datetime_utc, status "
174
                 " FROM tbl_data_repair_files "
175
                 " WHERE id = %s ")
176
        cursor.execute(query, (id_,))
177
        row = cursor.fetchone()
178
        cursor.close()
179
        cnx.close()
180
        if row is None:
181
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
182
                                   description='API.DATA_REPAIR_FILE_NOT_FOUND')
183
184
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
185
        if config.utc_offset[0] == '-':
186
            timezone_offset = -timezone_offset
187
188
        result = {"id": row[0],
189
                  "file_name": row[1],
190
                  "uuid": row[2],
191
                  "upload_datetime": (row[3].replace(tzinfo=timezone.utc)
192
                                      + timedelta(minutes=timezone_offset)).isoformat()[0:19],
193
                  "status": row[4]}
194
        resp.text = json.dumps(result)
195
196
    @staticmethod
197
    @user_logger
198
    def on_delete(req, resp, id_):
199
        admin_control(req)
200
        if not id_.isdigit() or int(id_) <= 0:
201
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
202
                                   description='API.INVALID_DATA_REPAIR_FILE_ID')
203
204
        cnx = mysql.connector.connect(**config.myems_historical_db)
205
        cursor = cnx.cursor()
206
207
        cursor.execute(" SELECT uuid "
208
                       " FROM tbl_data_repair_files "
209
                       " WHERE id = %s ", (id_,))
210
        row = cursor.fetchone()
211
        if row is None:
212
            cursor.close()
213
            cnx.close()
214
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
215
                                   description='API.DATA_REPAIR_FILE_NOT_FOUND')
216
217
        try:
218
            file_uuid = row[0]
219
            # Define file_path
220
            file_path = os.path.join(config.upload_path, file_uuid)
221
222
            # remove the file from disk
223
            os.remove(file_path)
224
        except OSError as ex:
225
            print("Failed to stream request")
226
        except Exception as ex:
227
            print(str(ex))
228
            # ignore exception and don't return API.DATA_REPAIR_FILE_NOT_FOUND error
229
            pass
230
231
        # Note: the energy data imported from the deleted file will not be deleted
232
        cursor.execute(" DELETE FROM tbl_data_repair_files WHERE id = %s ", (id_,))
233
        cnx.commit()
234
235
        cursor.close()
236
        cnx.close()
237
238
        resp.status = falcon.HTTP_204
239
240
241 View Code Duplication
class DataRepairFileRestore:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
242
    def __init__(self):
243
        pass
244
245
    @staticmethod
246
    def on_options(req, resp, id_):
247
        _ = req
248
        resp.status = falcon.HTTP_200
249
        _ = id_
250
251
    @staticmethod
252
    def on_get(req, resp, id_):
253
        admin_control(req)
254
        if not id_.isdigit() or int(id_) <= 0:
255
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
256
                                   description='API.INVALID_DATA_REPAIR_FILE_ID')
257
258
        cnx = mysql.connector.connect(**config.myems_historical_db)
259
        cursor = cnx.cursor()
260
261
        query = (" SELECT uuid, file_object "
262
                 " FROM tbl_data_repair_files "
263
                 " WHERE id = %s ")
264
        cursor.execute(query, (id_,))
265
        row = cursor.fetchone()
266
        cursor.close()
267
        cnx.close()
268
269
        if row is None:
270
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
271
                                   description='API.DATA_REPAIR_FILE_NOT_FOUND')
272
273
        result = {"uuid": row[0],
274
                  "file_object": row[1]}
275
        try:
276
            raw_blob = result["file_object"]
277
            file_uuid = result["uuid"]
278
279
            # Define file_path
280
            file_path = os.path.join(config.upload_path, file_uuid)
281
282
            # Write to a temporary file to prevent incomplete files from
283
            # being used.
284
            temp_file_path = file_path + '~'
285
286
            with open(temp_file_path, 'wb') as f:
287
                f.write(raw_blob)
288
289
            # Now that we know the file has been fully saved to disk
290
            # move it into place.
291
            os.replace(temp_file_path, file_path)
292
        except OSError as ex:
293
            print("Failed to stream request")
294
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
295
                                   description='API.FAILED_TO_RESTORE_DATA_REPAIR_FILE')
296
        except Exception as ex:
297
            print(str(ex))
298
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
299
                                   description='API.FAILED_TO_RESTORE_DATA_REPAIR_FILE')
300
        resp.text = json.dumps('success')
301