Passed
Push — master ( 4090c3...110378 )
by Guangyu
02:37 queued 19s
created

WebMessageStatusNewCollection.on_options()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
import falcon
2
import json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
7
8
class WebMessageCollection:
9
    @staticmethod
10
    def __init__():
11
        pass
12
13
    @staticmethod
14
    def on_options(req, resp, startdate, enddate):
15
        resp.status = falcon.HTTP_200
16
17
    @staticmethod
18
    def on_get(req, resp, startdate, enddate):
19
        try:
20
            start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
21
        except Exception:
22
            raise falcon.HTTPError(falcon.HTTP_400,
23
                                   title='API.BAD_REQUEST',
24
                                   description='API.INVALID_START_DATE_FORMAT')
25
        try:
26
            end_datetime_local = datetime.strptime(enddate, '%Y-%m-%d')
27
        except Exception:
28
            raise falcon.HTTPError(falcon.HTTP_400,
29
                                   title='API.BAD_REQUEST',
30
                                   description='API.INVALID_END_DATE_FORMAT')
31
32
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
33
        if config.utc_offset[0] == '-':
34
            timezone_offset = -timezone_offset
35
36
        start_datetime_utc = start_datetime_local.replace(tzinfo=timezone.utc)
37
        start_datetime_utc -= timedelta(minutes=timezone_offset)
38
39
        end_datetime_utc = end_datetime_local.replace(tzinfo=timezone.utc)
40
        end_datetime_utc -= timedelta(minutes=timezone_offset)
41
        end_datetime_utc += timedelta(days=1)
42
43
        if start_datetime_utc >= end_datetime_utc:
44
            raise falcon.HTTPError(falcon.HTTP_400,
45
                                   title='API.BAD_REQUEST',
46
                                   description='API.START_DATETIME_SHOULD_BE_EARLY_THAN_END_DATETIME')
47
        # get user dict
48
        cnx = mysql.connector.connect(**config.myems_user_db)
49
        cursor = cnx.cursor(dictionary=True)
50
51
        query = (" SELECT id, display_name "
52
                 " FROM tbl_users ")
53
        cursor.execute(query)
54
        rows_users = cursor.fetchall()
55
56
        if cursor:
57
            cursor.close()
58
        if cnx:
59
            cnx.disconnect()
60
61
        user_dict = dict()
62
        if rows_users is not None and len(rows_users) > 0:
63
            for row in rows_users:
64
                user_dict[row['id']] = row['display_name']
65
66
        # get web messages
67
        cnx = mysql.connector.connect(**config.myems_fdd_db)
68
        cursor = cnx.cursor()
69
70
        query = (" SELECT id, user_id, subject, message, "
71
                 "        created_datetime_utc, status, reply "
72
                 " FROM tbl_web_messages "
73
                 " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
74
                 " ORDER BY created_datetime_utc DESC ")
75
        cursor.execute(query, (start_datetime_utc, end_datetime_utc))
76
        rows = cursor.fetchall()
77
78
        if cursor:
79
            cursor.close()
80
        if cnx:
81
            cnx.disconnect()
82
83
        result = list()
84 View Code Duplication
        if rows is not None and len(rows) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
85
            for row in rows:
86
                meta_result = {"id": row[0],
87
                               "user_id": row[1],
88
                               "user_display_name": user_dict.get(row[1], None),
89
                               "subject": row[2],
90
                               "message": row[3].replace("<br>", ""),
91
                               "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
92
                               "status": row[5],
93
                               "reply": row[6]}
94
                result.append(meta_result)
95
96
        resp.body = json.dumps(result)
97
98
99
class WebMessageStatusNewCollection:
100
    @staticmethod
101
    def __init__():
102
        pass
103
104
    @staticmethod
105
    def on_options(req, resp):
106
        resp.status = falcon.HTTP_200
107
108
    @staticmethod
109
    def on_get(req, resp):
110
111
        # get user dict
112
        cnx = mysql.connector.connect(**config.myems_user_db)
113
        cursor = cnx.cursor(dictionary=True)
114
115
        query = (" SELECT id, display_name "
116
                 " FROM tbl_users ")
117
        cursor.execute(query)
118
        rows_users = cursor.fetchall()
119
120
        if cursor:
121
            cursor.close()
122
        if cnx:
123
            cnx.disconnect()
124
125
        user_dict = dict()
126
        if rows_users is not None and len(rows_users) > 0:
127
            for row in rows_users:
128
                user_dict[row['id']] = row['display_name']
129
130
        # get new web messages
131
        cnx = mysql.connector.connect(**config.myems_fdd_db)
132
        cursor = cnx.cursor()
133
134
        query = (" SELECT id, user_id, subject, message, "
135
                 "        created_datetime_utc, status "
136
                 " FROM tbl_web_messages "
137
                 " WHERE status = %s "
138
                 " ORDER BY created_datetime_utc DESC ")
139
        cursor.execute(query, ("new", ))
140
        rows = cursor.fetchall()
141
142
        if cursor:
143
            cursor.close()
144
        if cnx:
145
            cnx.disconnect()
146
147
        result = list()
148 View Code Duplication
        if rows is not None and len(rows) > 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
149
            for row in rows:
150
                meta_result = {"id": row[0],
151
                               "user_id": row[1],
152
                               "user_display_name": user_dict.get(row[1], None),
153
                               "subject": row[2],
154
                               "message": row[3].replace("<br>", ""),
155
                               "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
156
                               "status": row[5]}
157
                result.append(meta_result)
158
159
        resp.body = json.dumps(result)
160
161
162
class WebMessageItem:
163
    @staticmethod
164
    def __init__():
165
        pass
166
167
    @staticmethod
168
    def on_options(req, resp, id_):
169
        resp.status = falcon.HTTP_200
170
171
    @staticmethod
172
    def on_get(req, resp, id_):
173
        """Handles GET requests"""
174
        if not id_.isdigit() or int(id_) <= 0:
175
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
176
                                   description='API.INVALID_WEB_MESSAGE_ID')
177
178
        # get user dict
179
        cnx = mysql.connector.connect(**config.myems_user_db)
180
        cursor = cnx.cursor(dictionary=True)
181
182
        query = (" SELECT id, display_name "
183
                 " FROM tbl_users ")
184
        cursor.execute(query)
185
        rows_users = cursor.fetchall()
186
187
        if cursor:
188
            cursor.close()
189
        if cnx:
190
            cnx.disconnect()
191
192
        user_dict = dict()
193
        if rows_users is not None and len(rows_users) > 0:
194
            for row in rows_users:
195
                user_dict[row['id']] = row['display_name']
196
197
        # get web message
198
        cnx = mysql.connector.connect(**config.myems_fdd_db)
199
        cursor = cnx.cursor()
200
201
        query = (" SELECT id, user_id, subject, message, "
202
                 "        created_datetime_utc, status, reply "
203
                 " FROM tbl_web_messages "
204
                 " WHERE id = %s ")
205
        cursor.execute(query, (id_,))
206
        row = cursor.fetchone()
207
208
        if cursor:
209
            cursor.close()
210
        if cnx:
211
            cnx.disconnect()
212
213
        if row is None:
214
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
215
                                   description='API.WEB_MESSAGE_NOT_FOUND')
216
217
        meta_result = {"id": row[0],
218
                       "user_id": row[1],
219
                       "user_display_name": user_dict.get(row[1], None),
220
                       "subject": row[2],
221
                       "message": row[3].replace("<br>", ""),
222
                       "created_datetime": row[4].timestamp() * 1000 if isinstance(row[4], datetime) else None,
223
                       "status": row[5],
224
                       "reply": row[6]}
225
226
        resp.body = json.dumps(meta_result)
227
228
    @staticmethod
229
    def on_put(req, resp, id_):
230
        """Handles PUT requests"""
231
        try:
232
            raw_json = req.stream.read().decode('utf-8')
233
        except Exception as ex:
234
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
235
236
        if not id_.isdigit() or int(id_) <= 0:
237
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
238
                                   description='API.INVALID_WEB_MESSAGE_ID')
239
240
        new_values = json.loads(raw_json, encoding='utf-8')
241
242
        if 'status' not in new_values['data'].keys() or \
243
                not isinstance(new_values['data']['status'], str) or \
244
                len(str.strip(new_values['data']['status'])) == 0 or \
245
                str.strip(new_values['data']['status']) not in ('new', 'acknowledged', 'timeout'):
246
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
247
                                   description='API.INVALID_STATUS')
248
        status = str.strip(new_values['data']['status'])
249
250
        if 'reply' not in new_values['data'].keys() or \
251
                not isinstance(new_values['data']['reply'], str) or \
252
                len(str.strip(new_values['data']['reply'])) == 0:
253
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
254
                                   description='API.INVALID_REPLY')
255
        reply = str.strip(new_values['data']['reply'])
256
257
        cnx = mysql.connector.connect(**config.myems_fdd_db)
258
        cursor = cnx.cursor()
259
260
        cursor.execute(" SELECT user_id "
261
                       " FROM tbl_web_messages "
262
                       " WHERE id = %s ", (id_,))
263
        if cursor.fetchone() is None:
264
            cursor.close()
265
            cnx.disconnect()
266
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
267
                                   description='API.WEB_MESSAGE_NOT_FOUND')
268
269
        update_row = (" UPDATE tbl_web_messages "
270
                      " SET status = %s, reply = %s "
271
                      " WHERE id = %s ")
272
        cursor.execute(update_row, (status,
273
                                    reply,
274
                                    id_,))
275
        cnx.commit()
276
277
        cursor.close()
278
        cnx.disconnect()
279
280
        resp.status = falcon.HTTP_200
281
282
    @staticmethod
283
    def on_delete(req, resp, id_):
284
        if not id_.isdigit() or int(id_) <= 0:
285
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
286
                                   description='API.INVALID_WEB_MESSAGE_ID')
287
288
        cnx = mysql.connector.connect(**config.myems_fdd_db)
289
        cursor = cnx.cursor()
290
291
        cursor.execute(" SELECT id "
292
                       " FROM tbl_web_messages "
293
                       " WHERE id = %s ", (id_,))
294
        row = cursor.fetchone()
295
296
        if row is None:
297
            if cursor:
298
                cursor.close()
299
            if cnx:
300
                cnx.disconnect()
301
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
302
                                   description='API.WEB_MESSAGE_NOT_FOUND')
303
304
        cursor.execute(" DELETE FROM tbl_web_messages WHERE id = %s ", (id_,))
305
        cnx.commit()
306
        if cursor:
307
            cursor.close()
308
        if cnx:
309
            cnx.disconnect()
310
311
        resp.status = falcon.HTTP_204
312