Passed
Push — master ( 8a3da8...150791 )
by Guangyu
08:18 queued 12s
created

core.webmessage.WebMessageItem.on_put()   F

Complexity

Conditions 25

Size

Total Lines 110
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 84
dl 0
loc 110
rs 0
c 0
b 0
f 0
cc 25
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like core.webmessage.WebMessageItem.on_put() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
from core.useractivity import user_logger
7
8
9
class WebMessageCollection:
10
    @staticmethod
11
    def __init__():
12
        """"Initializes WebMessageCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp, startdate, enddate):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp, startdate, enddate):
21
        try:
22
            start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
23
        except Exception:
24
            raise falcon.HTTPError(falcon.HTTP_400,
25
                                   title='API.BAD_REQUEST',
26
                                   description='API.INVALID_START_DATE_FORMAT')
27
        try:
28
            end_datetime_local = datetime.strptime(enddate, '%Y-%m-%d')
29
        except Exception:
30
            raise falcon.HTTPError(falcon.HTTP_400,
31
                                   title='API.BAD_REQUEST',
32
                                   description='API.INVALID_END_DATE_FORMAT')
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
        start_datetime_utc = start_datetime_local.replace(tzinfo=timezone.utc)
39
        start_datetime_utc -= timedelta(minutes=timezone_offset)
40
41
        end_datetime_utc = end_datetime_local.replace(tzinfo=timezone.utc)
42
        end_datetime_utc -= timedelta(minutes=timezone_offset)
43
        end_datetime_utc += timedelta(days=1)
44
45
        if start_datetime_utc >= end_datetime_utc:
46
            raise falcon.HTTPError(falcon.HTTP_400,
47
                                   title='API.BAD_REQUEST',
48
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
49
50
        # Verify User Session
51
        token = req.headers.get('TOKEN')
52
        user_uuid = req.headers.get('USER-UUID')
53
        if token is None:
54
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
55
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
56
        if user_uuid is None:
57
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
58
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
59
60
        cnx = mysql.connector.connect(**config.myems_user_db)
61
        cursor = cnx.cursor(dictionary=True)
62
63
        query = (" SELECT utc_expires "
64
                 " FROM tbl_sessions "
65
                 " WHERE user_uuid = %s AND token = %s")
66
        cursor.execute(query, (user_uuid, token,))
67
        row = cursor.fetchone()
68
69
        if row is None:
70
            if cursor:
71
                cursor.close()
72
            if cnx:
73
                cnx.disconnect()
74
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
75
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
76
        else:
77
            utc_expires = row['utc_expires']
78
            if datetime.utcnow() > utc_expires:
79
                if cursor:
80
                    cursor.close()
81
                if cnx:
82
                    cnx.disconnect()
83
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
84
                                       description='API.USER_SESSION_TIMEOUT')
85
86
        cursor.execute(" SELECT id "
87
                       " FROM tbl_users "
88
                       " WHERE uuid = %s ",
89
                       (user_uuid,))
90
        row = cursor.fetchone()
91
        if row is None:
92
            if cursor:
93
                cursor.close()
94
            if cnx:
95
                cnx.disconnect()
96
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
97
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
98
        else:
99
            user_id = row['id']
100
101
        if cursor:
102
            cursor.close()
103
        if cnx:
104
            cnx.disconnect()
105
106
        # get web messages
107
        cnx = mysql.connector.connect(**config.myems_fdd_db)
108
        cursor = cnx.cursor()
109
110
        query = (" SELECT id, subject, message, "
111
                 "        created_datetime_utc, status, reply "
112
                 " FROM tbl_web_messages "
113
                 " WHERE user_id = %s AND "
114
                 "       created_datetime_utc >= %s AND created_datetime_utc < %s "
115
                 " ORDER BY created_datetime_utc DESC ")
116
        cursor.execute(query, (user_id, start_datetime_utc, end_datetime_utc))
117
        rows = cursor.fetchall()
118
119
        if cursor:
120
            cursor.close()
121
        if cnx:
122
            cnx.disconnect()
123
124
        result = list()
125
        if rows is not None and len(rows) > 0:
126
            for row in rows:
127
                meta_result = {"id": row[0],
128
                               "subject": row[1],
129
                               "message": row[2].replace("<br>", ""),
130
                               "created_datetime": row[3].timestamp() * 1000 if isinstance(row[4], datetime) else None,
131
                               "status": row[4],
132
                               "reply": row[5]}
133
                result.append(meta_result)
134
135
        resp.text = json.dumps(result)
136
137
138
class WebMessageStatusNewCollection:
139
    @staticmethod
140
    def __init__():
141
        """"Initializes WebMessageStatusNewCollection"""
142
        pass
143
144
    @staticmethod
145
    def on_options(req, resp):
146
        resp.status = falcon.HTTP_200
147
148
    @staticmethod
149
    def on_get(req, resp):
150
        """Handles GET requests"""
151
        # Verify User Session
152
        token = req.headers.get('TOKEN')
153
        user_uuid = req.headers.get('USER-UUID')
154
        if token is None:
155
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
156
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
157
        if user_uuid is None:
158
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
159
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
160
161
        cnx = mysql.connector.connect(**config.myems_user_db)
162
        cursor = cnx.cursor(dictionary=True)
163
164
        query = (" SELECT utc_expires "
165
                 " FROM tbl_sessions "
166
                 " WHERE user_uuid = %s AND token = %s")
167
        cursor.execute(query, (user_uuid, token,))
168
        row = cursor.fetchone()
169
170
        if row is None:
171
            if cursor:
172
                cursor.close()
173
            if cnx:
174
                cnx.disconnect()
175
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
176
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
177
        else:
178
            utc_expires = row['utc_expires']
179
            if datetime.utcnow() > utc_expires:
180
                if cursor:
181
                    cursor.close()
182
                if cnx:
183
                    cnx.disconnect()
184
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
185
                                       description='API.USER_SESSION_TIMEOUT')
186
187
        cursor.execute(" SELECT id "
188
                       " FROM tbl_users "
189
                       " WHERE uuid = %s ",
190
                       (user_uuid,))
191
        row = cursor.fetchone()
192
        if row is None:
193
            if cursor:
194
                cursor.close()
195
            if cnx:
196
                cnx.disconnect()
197
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
198
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
199
        else:
200
            user_id = row['id']
201
202
        if cursor:
203
            cursor.close()
204
        if cnx:
205
            cnx.disconnect()
206
207
        # get 'new' web messages
208
        cnx = mysql.connector.connect(**config.myems_fdd_db)
209
        cursor = cnx.cursor()
210
211
        query = (" SELECT id, subject, message, "
212
                 "        created_datetime_utc, status, reply "
213
                 " FROM tbl_web_messages "
214
                 " WHERE user_id = %s AND "
215
                 "       status = %s "
216
                 " ORDER BY created_datetime_utc DESC ")
217
        cursor.execute(query, (user_id, 'new'))
218
        rows = cursor.fetchall()
219
220
        if cursor:
221
            cursor.close()
222
        if cnx:
223
            cnx.disconnect()
224
225
        result = list()
226
        if rows is not None and len(rows) > 0:
227
            for row in rows:
228
                meta_result = {"id": row[0],
229
                               "subject": row[1],
230
                               "message": row[2].replace("<br>", ""),
231
                               "created_datetime": row[3].timestamp() * 1000 if isinstance(row[4], datetime) else None,
232
                               "status": row[4],
233
                               "reply": row[5]}
234
                result.append(meta_result)
235
236
        resp.text = json.dumps(result)
237
238
239
class WebMessageItem:
240
    @staticmethod
241
    def __init__():
242
        """"Initializes WebMessageItem"""
243
        pass
244
245
    @staticmethod
246
    def on_options(req, resp, id_):
247
        resp.status = falcon.HTTP_200
248
249
    @staticmethod
250
    def on_get(req, resp, id_):
251
        """Handles GET requests"""
252
        if not id_.isdigit() or int(id_) <= 0:
253
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
254
                                   description='API.INVALID_WEB_MESSAGE_ID')
255
256
        # Verify User Session
257
        token = req.headers.get('TOKEN')
258
        user_uuid = req.headers.get('USER-UUID')
259
        if token is None:
260
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
261
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
262
        if user_uuid is None:
263
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
264
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
265
266
        cnx = mysql.connector.connect(**config.myems_user_db)
267
        cursor = cnx.cursor(dictionary=True)
268
269
        query = (" SELECT utc_expires "
270
                 " FROM tbl_sessions "
271
                 " WHERE user_uuid = %s AND token = %s")
272
        cursor.execute(query, (user_uuid, token,))
273
        row = cursor.fetchone()
274
275
        if row is None:
276
            if cursor:
277
                cursor.close()
278
            if cnx:
279
                cnx.disconnect()
280
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
281
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
282
        else:
283
            utc_expires = row['utc_expires']
284
            if datetime.utcnow() > utc_expires:
285
                if cursor:
286
                    cursor.close()
287
                if cnx:
288
                    cnx.disconnect()
289
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
290
                                       description='API.USER_SESSION_TIMEOUT')
291
292
        cursor.execute(" SELECT id "
293
                       " FROM tbl_users "
294
                       " WHERE uuid = %s ",
295
                       (user_uuid,))
296
        row = cursor.fetchone()
297
        if row is None:
298
            if cursor:
299
                cursor.close()
300
            if cnx:
301
                cnx.disconnect()
302
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
303
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
304
        else:
305
            user_id = row['id']
306
307
        if cursor:
308
            cursor.close()
309
        if cnx:
310
            cnx.disconnect()
311
312
        # get web message by id
313
        cnx = mysql.connector.connect(**config.myems_fdd_db)
314
        cursor = cnx.cursor()
315
316
        query = (" SELECT id, subject, message, "
317
                 "        created_datetime_utc, status, reply "
318
                 " FROM tbl_web_messages "
319
                 " WHERE id = %s AND user_id = %s "
320
                 " ORDER BY created_datetime_utc DESC ")
321
        cursor.execute(query, (id_, user_id))
322
        row = cursor.fetchone()
323
324
        if cursor:
325
            cursor.close()
326
        if cnx:
327
            cnx.disconnect()
328
329
        if row is None:
330
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
331
                                   description='API.WEB_MESSAGE_NOT_FOUND')
332
333
        meta_result = {"id": row[0],
334
                       "subject": row[1],
335
                       "message": row[2].replace("<br>", ""),
336
                       "created_datetime": row[3].timestamp() * 1000 if isinstance(row[4], datetime) else None,
337
                       "status": row[4],
338
                       "reply": row[5]}
339
340
        resp.text = json.dumps(meta_result)
341
342
    @staticmethod
343
    @user_logger
344
    def on_put(req, resp, id_):
345
        """Handles PUT requests"""
346
        try:
347
            raw_json = req.stream.read().decode('utf-8')
348
        except Exception as ex:
349
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
350
351
        if not id_.isdigit() or int(id_) <= 0:
352
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
353
                                   description='API.INVALID_WEB_MESSAGE_ID')
354
355
        new_values = json.loads(raw_json)
356
357
        if 'status' not in new_values['data'].keys() or \
358
                not isinstance(new_values['data']['status'], str) or \
359
                len(str.strip(new_values['data']['status'])) == 0 or \
360
                str.strip(new_values['data']['status']) not in ('new', 'acknowledged', 'timeout'):
361
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
362
                                   description='API.INVALID_STATUS')
363
        status = str.strip(new_values['data']['status'])
364
365
        if 'reply' not in new_values['data'].keys() or \
366
                not isinstance(new_values['data']['reply'], str) or \
367
                len(str.strip(new_values['data']['reply'])) == 0:
368
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
369
                                   description='API.INVALID_REPLY')
370
        reply = str.strip(new_values['data']['reply'])
371
372
        # Verify User Session
373
        token = req.headers.get('TOKEN')
374
        user_uuid = req.headers.get('USER-UUID')
375
        if token is None:
376
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
377
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
378
        if user_uuid is None:
379
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
380
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
381
382
        cnx = mysql.connector.connect(**config.myems_user_db)
383
        cursor = cnx.cursor(dictionary=True)
384
385
        query = (" SELECT utc_expires "
386
                 " FROM tbl_sessions "
387
                 " WHERE user_uuid = %s AND token = %s")
388
        cursor.execute(query, (user_uuid, token,))
389
        row = cursor.fetchone()
390
391
        if row is None:
392
            if cursor:
393
                cursor.close()
394
            if cnx:
395
                cnx.disconnect()
396
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
397
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
398
        else:
399
            utc_expires = row['utc_expires']
400
            if datetime.utcnow() > utc_expires:
401
                if cursor:
402
                    cursor.close()
403
                if cnx:
404
                    cnx.disconnect()
405
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
406
                                       description='API.USER_SESSION_TIMEOUT')
407
408
        cursor.execute(" SELECT id "
409
                       " FROM tbl_users "
410
                       " WHERE uuid = %s ",
411
                       (user_uuid,))
412
        row = cursor.fetchone()
413
        if row is None:
414
            if cursor:
415
                cursor.close()
416
            if cnx:
417
                cnx.disconnect()
418
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
419
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
420
        else:
421
            user_id = row['id']
422
423
        if cursor:
424
            cursor.close()
425
        if cnx:
426
            cnx.disconnect()
427
428
        cnx = mysql.connector.connect(**config.myems_fdd_db)
429
        cursor = cnx.cursor()
430
431
        cursor.execute(" SELECT user_id "
432
                       " FROM tbl_web_messages "
433
                       " WHERE id = %s AND user_id = %s ", (id_, user_id))
434
        if cursor.fetchone() is None:
435
            cursor.close()
436
            cnx.disconnect()
437
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
438
                                   description='API.WEB_MESSAGE_NOT_FOUND')
439
440
        update_row = (" UPDATE tbl_web_messages "
441
                      " SET status = %s, reply = %s "
442
                      " WHERE id = %s ")
443
        cursor.execute(update_row, (status,
444
                                    reply,
445
                                    id_,))
446
        cnx.commit()
447
448
        cursor.close()
449
        cnx.disconnect()
450
451
        resp.status = falcon.HTTP_200
452
453
    @staticmethod
454
    @user_logger
455
    def on_delete(req, resp, id_):
456
        if not id_.isdigit() or int(id_) <= 0:
457
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
458
                                   description='API.INVALID_WEB_MESSAGE_ID')
459
460
        # Verify User Session
461
        token = req.headers.get('TOKEN')
462
        user_uuid = req.headers.get('USER-UUID')
463
        if token is None:
464
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
465
                                   description='API.TOKEN_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
466
        if user_uuid is None:
467
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
468
                                   description='API.USER_UUID_NOT_FOUND_IN_HEADERS_PLEASE_LOGIN')
469
470
        cnx = mysql.connector.connect(**config.myems_user_db)
471
        cursor = cnx.cursor(dictionary=True)
472
473
        query = (" SELECT utc_expires "
474
                 " FROM tbl_sessions "
475
                 " WHERE user_uuid = %s AND token = %s")
476
        cursor.execute(query, (user_uuid, token,))
477
        row = cursor.fetchone()
478
479
        if row is None:
480
            if cursor:
481
                cursor.close()
482
            if cnx:
483
                cnx.disconnect()
484
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
485
                                   description='API.INVALID_SESSION_PLEASE_RE_LOGIN')
486
        else:
487
            utc_expires = row['utc_expires']
488
            if datetime.utcnow() > utc_expires:
489
                if cursor:
490
                    cursor.close()
491
                if cnx:
492
                    cnx.disconnect()
493
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
494
                                       description='API.USER_SESSION_TIMEOUT')
495
496
        cursor.execute(" SELECT id "
497
                       " FROM tbl_users "
498
                       " WHERE uuid = %s ",
499
                       (user_uuid,))
500
        row = cursor.fetchone()
501
        if row is None:
502
            if cursor:
503
                cursor.close()
504
            if cnx:
505
                cnx.disconnect()
506
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
507
                                   description='API.INVALID_USER_PLEASE_RE_LOGIN')
508
        else:
509
            user_id = row['id']
510
511
        if cursor:
512
            cursor.close()
513
        if cnx:
514
            cnx.disconnect()
515
516
        cnx = mysql.connector.connect(**config.myems_fdd_db)
517
        cursor = cnx.cursor()
518
519
        cursor.execute(" SELECT id "
520
                       " FROM tbl_web_messages "
521
                       " WHERE id = %s AND user_id = %s ", (id_, user_id))
522
        row = cursor.fetchone()
523
524
        if row is None:
525
            if cursor:
526
                cursor.close()
527
            if cnx:
528
                cnx.disconnect()
529
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
530
                                   description='API.WEB_MESSAGE_NOT_FOUND')
531
532
        cursor.execute(" DELETE FROM tbl_web_messages WHERE id = %s ", (id_,))
533
        cnx.commit()
534
        if cursor:
535
            cursor.close()
536
        if cnx:
537
            cnx.disconnect()
538
539
        resp.status = falcon.HTTP_204
540