Passed
Push — master ( c06163...23501b )
by Guangyu
26:50 queued 18:56
created

DataRepairFileCollection.on_options()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 3
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 3
dl 3
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
from datetime import datetime, timezone, timedelta
7
import os
8
from core.useractivity import user_logger, access_control
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
    @staticmethod
13
    def __init__():
14
        """"Initializes DataRepairFileCollection"""
15
        pass
16
17
    @staticmethod
18
    def on_options(req, resp):
19
        resp.status = falcon.HTTP_200
20
21
    @staticmethod
22
    def on_get(req, resp):
23
        access_control(req)
24
        cnx = mysql.connector.connect(**config.myems_historical_db)
25
        cursor = cnx.cursor()
26
27
        query = (" SELECT id, file_name, uuid, upload_datetime_utc, status "
28
                 " FROM tbl_data_repair_files "
29
                 " ORDER BY upload_datetime_utc desc ")
30
        cursor.execute(query)
31
        rows = cursor.fetchall()
32
        cursor.close()
33
        cnx.close()
34
35
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
36
        if config.utc_offset[0] == '-':
37
            timezone_offset = -timezone_offset
38
39
        result = list()
40
        if rows is not None and len(rows) > 0:
41
            for row in rows:
42
                upload_datetime_local = row[3].replace(tzinfo=timezone.utc) + timedelta(minutes=timezone_offset)
43
                meta_result = {"id": row[0],
44
                               "file_name": row[1],
45
                               "uuid": row[2],
46
                               "upload_datetime": upload_datetime_local.strftime('%Y-%m-%dT%H:%M:%S'),
47
                               "status": row[4]}
48
                result.append(meta_result)
49
50
        resp.text = json.dumps(result)
51
52
    @staticmethod
53
    @user_logger
54
    def on_post(req, resp):
55
        """Handles POST requests"""
56
        access_control(req)
57
        try:
58
            upload = req.get_param('file')
59
            # Read upload file as binary
60
            raw_blob = upload.file.read()
61
62
            # Retrieve filename
63
            filename = upload.filename
64
            file_uuid = str(uuid.uuid4())
65
 
66
            # Define file_path
67
            file_path = os.path.join(config.upload_path, file_uuid)
68
  
69
            # Write to a temporary file to prevent incomplete files from
70
            # being used.
71
            temp_file_path = file_path + '~'
72
 
73
            open(temp_file_path, 'wb').write(raw_blob)
74
75
            # Now that we know the file has been fully saved to disk
76
            # move it into place.
77
            os.rename(temp_file_path, file_path)
78
79
        except Exception as ex:
80
            raise falcon.HTTPError(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(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(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(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(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(falcon.HTTP_400, title='API.BAD_REQUEST',
130
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
131
        else:
132
            user_id = row[0]
133
134
        cnx = mysql.connector.connect(**config.myems_historical_db)
135
        cursor = cnx.cursor()
136
137
        add_values = (" INSERT INTO tbl_data_repair_files "
138
                      " (file_name, uuid, upload_datetime_utc, status, file_object ) "
139
                      " VALUES (%s, %s, %s, %s, %s) ")
140
        cursor.execute(add_values, (filename,
141
                                    file_uuid,
142
                                    datetime.utcnow(),
143
                                    'new',
144
                                    raw_blob))
145
        new_id = cursor.lastrowid
146
        cnx.commit()
147
        cursor.close()
148
        cnx.close()
149
150
        resp.status = falcon.HTTP_201
151
        resp.location = '/datarepairfiles/' + str(new_id)
152
153
154 View Code Duplication
class DataRepairFileItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
155
    @staticmethod
156
    def __init__():
157
        """"Initializes DataRepairFileItem"""
158
        pass
159
160
    @staticmethod
161
    def on_options(req, resp, id_):
162
        resp.status = falcon.HTTP_200
163
164
    @staticmethod
165
    def on_get(req, resp, id_):
166
        access_control(req)
167
        if not id_.isdigit() or int(id_) <= 0:
168
            raise falcon.HTTPError(falcon.HTTP_400,
169
                                   title='API.BAD_REQUEST',
170
                                   description='API.INVALID_DATA_REPAIR_FILE_ID')
171
172
        cnx = mysql.connector.connect(**config.myems_historical_db)
173
        cursor = cnx.cursor()
174
175
        query = (" SELECT id, file_name, uuid, upload_datetime_utc, status "
176
                 " FROM tbl_data_repair_files "
177
                 " WHERE id = %s ")
178
        cursor.execute(query, (id_,))
179
        row = cursor.fetchone()
180
        cursor.close()
181
        cnx.close()
182
        if row is None:
183
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
184
                                   description='API.DATA_REPAIR_FILE_NOT_FOUND')
185
186
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
187
        if config.utc_offset[0] == '-':
188
            timezone_offset = -timezone_offset
189
190
        upload_datetime_local = row[3].replace(tzinfo=timezone.utc) + timedelta(minutes=timezone_offset)
191
192
        result = {"id": row[0],
193
                  "file_name": row[1],
194
                  "uuid": row[2],
195
                  "upload_datetime": upload_datetime_local.strftime('%Y-%m-%dT%H:%M:%S'),
196
                  "status": row[4]}
197
        resp.text = json.dumps(result)
198
199
    @staticmethod
200
    @user_logger
201
    def on_delete(req, resp, id_):
202
        access_control(req)
203
        if not id_.isdigit() or int(id_) <= 0:
204
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
205
                                   description='API.INVALID_DATA_REPAIR_FILE_ID')
206
207
        cnx = mysql.connector.connect(**config.myems_historical_db)
208
        cursor = cnx.cursor()
209
210
        cursor.execute(" SELECT uuid "
211
                       " FROM tbl_data_repair_files "
212
                       " WHERE id = %s ", (id_,))
213
        row = cursor.fetchone()
214
        if row is None:
215
            cursor.close()
216
            cnx.close()
217
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
218
                                   description='API.DATA_REPAIR_FILE_NOT_FOUND')
219
220
        try:
221
            file_uuid = row[0]
222
            # Define file_path
223
            file_path = os.path.join(config.upload_path, file_uuid)
224
225
            # remove the file from disk
226
            os.remove(file_path)
227
        except Exception as 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
    @staticmethod
243
    def __init__():
244
        """"Initializes DataRepairFileRestore"""
245
        pass
246
247
    @staticmethod
248
    def on_options(req, resp, id_):
249
        resp.status = falcon.HTTP_200
250
251
    @staticmethod
252
    def on_get(req, resp, id_):
253
        access_control(req)
254
        if not id_.isdigit() or int(id_) <= 0:
255
            raise falcon.HTTPError(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(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
            open(temp_file_path, 'wb').write(raw_blob)
287
288
            # Now that we know the file has been fully saved to disk
289
            # move it into place.
290
            os.replace(temp_file_path, file_path)
291
        except Exception as ex:
292
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
293
                                   description='API.FAILED_TO_RESTORE_DATA_REPAIR_FILE')
294
        resp.text = json.dumps('success')
295