Passed
Push — master ( 14eaf2...8a3da8 )
by Guangyu
07:24 queued 12s
created

core.textmessage   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 160
Duplicated Lines 93.13 %

Importance

Changes 0
Metric Value
wmc 32
eloc 122
dl 149
loc 160
rs 9.84
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A TextMessageCollection.on_options() 3 3 1
A TextMessageCollection.__init__() 4 4 1
A TextMessageItem.on_options() 3 3 1
B TextMessageItem.on_delete() 31 31 8
D TextMessageCollection.on_get() 61 61 12
B TextMessageItem.on_get() 36 36 8
A TextMessageItem.__init__() 4 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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, access_control
7
8
9 View Code Duplication
class TextMessageCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10
    @staticmethod
11
    def __init__():
12
        """"Initializes TextMessageCollection"""
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
        access_control(req)
22
        try:
23
            start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
24
        except Exception:
25
            raise falcon.HTTPError(falcon.HTTP_400,
26
                                   title='API.BAD_REQUEST',
27
                                   description='API.INVALID_START_DATE_FORMAT')
28
        try:
29
            end_datetime_local = datetime.strptime(enddate, '%Y-%m-%d')
30
        except Exception:
31
            raise falcon.HTTPError(falcon.HTTP_400,
32
                                   title='API.BAD_REQUEST',
33
                                   description='API.INVALID_END_DATE_FORMAT')
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
        start_datetime_utc = start_datetime_local.replace(tzinfo=timezone.utc)
40
        start_datetime_utc -= timedelta(minutes=timezone_offset)
41
42
        end_datetime_utc = end_datetime_local.replace(tzinfo=timezone.utc)
43
        end_datetime_utc -= timedelta(minutes=timezone_offset)
44
        end_datetime_utc += timedelta(days=1)
45
46
        if start_datetime_utc >= end_datetime_utc:
47
            raise falcon.HTTPError(falcon.HTTP_400,
48
                                   title='API.BAD_REQUEST',
49
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
50
        cnx = mysql.connector.connect(**config.myems_fdd_db)
51
        cursor = cnx.cursor()
52
53
        query = (" SELECT id, recipient_name, recipient_mobile, "
54
                 "        message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
55
                 " FROM tbl_text_messages_outbox "
56
                 " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
57
                 " ORDER BY created_datetime_utc DESC ")
58
        cursor.execute(query, (start_datetime_utc, end_datetime_utc))
59
        rows = cursor.fetchall()
60
61
        if cursor:
62
            cursor.close()
63
        if cnx:
64
            cnx.disconnect()
65
66
        result = list()
67
        if rows is not None and len(rows) > 0:
68
            for row in rows:
69
                meta_result = {"id": row[0],
70
                               "recipient_name": row[1],
71
                               "recipient_mobile": row[2],
72
                               "message": row[3],
73
                               "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
74
                               "scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
75
                               "acknowledge_code": row[6],
76
                               "status": row[7]}
77
                result.append(meta_result)
78
79
        resp.text = json.dumps(result)
80
81
82 View Code Duplication
class TextMessageItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
83
    @staticmethod
84
    def __init__():
85
        """"Initializes TextMessageItem"""
86
        pass
87
88
    @staticmethod
89
    def on_options(req, resp, id_):
90
        resp.status = falcon.HTTP_200
91
92
    @staticmethod
93
    def on_get(req, resp, id_):
94
        access_control(req)
95
        if not id_.isdigit() or int(id_) <= 0:
96
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
97
                                   description='API.INVALID_TEXT_MESSAGE_ID')
98
99
        cnx = mysql.connector.connect(**config.myems_fdd_db)
100
        cursor = cnx.cursor()
101
102
        query = (" SELECT id, recipient_name, recipient_mobile, "
103
                 "        message, created_datetime_utc, scheduled_datetime_utc, acknowledge_code, status "
104
                 " FROM tbl_text_messages_outbox "
105
                 " WHERE id = %s ")
106
        cursor.execute(query, (id_,))
107
        row = cursor.fetchone()
108
109
        if cursor:
110
            cursor.close()
111
        if cnx:
112
            cnx.disconnect()
113
114
        if row is None:
115
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
116
                                   description='API.TEXT_MESSAGE_NOT_FOUND')
117
118
        result = {"id": row[0],
119
                  "recipient_name": row[1],
120
                  "recipient_mobile": row[2],
121
                  "message": row[3],
122
                  "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
123
                  "scheduled_datetime": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
124
                  "acknowledge_code": row[6],
125
                  "status": row[7]}
126
127
        resp.text = json.dumps(result)
128
129
    @staticmethod
130
    @user_logger
131
    def on_delete(req, resp, id_):
132
        access_control(req)
133
        if not id_.isdigit() or int(id_) <= 0:
134
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
135
                                   description='API.INVALID_TEXT_MESSAGE_ID')
136
137
        cnx = mysql.connector.connect(**config.myems_fdd_db)
138
        cursor = cnx.cursor()
139
140
        cursor.execute(" SELECT id FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
141
        row = cursor.fetchone()
142
143
        if row is None:
144
            if cursor:
145
                cursor.close()
146
            if cnx:
147
                cnx.disconnect()
148
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
149
                                   description='API.TEXT_MESSAGE_NOT_FOUND')
150
151
        cursor.execute(" DELETE FROM tbl_text_messages_outbox WHERE id = %s ", (id_,))
152
        cnx.commit()
153
154
        if cursor:
155
            cursor.close()
156
        if cnx:
157
            cnx.disconnect()
158
159
        resp.status = falcon.HTTP_204
160