Passed
Push — master ( 0d20df...326e42 )
by Guangyu
08:03 queued 17s
created

EmailMessageCollection.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 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
class EmailMessageCollection:
10
    @staticmethod
11
    def __init__():
12
        """"Initializes EmailMessageCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        access_control(req)
22
        print(req.params)
23
        start_datetime_local = req.params.get('startdatetime')
24
        end_datetime_local = req.params.get('enddatetime')
25
26
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
27
        if config.utc_offset[0] == '-':
28
            timezone_offset = -timezone_offset
29
30
        if start_datetime_local is None:
31
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
32
                                   description="API.INVALID_START_DATETIME_FORMAT")
33
        else:
34
            start_datetime_local = str.strip(start_datetime_local)
35
            try:
36
                start_datetime_utc = datetime.strptime(start_datetime_local,
37
                                                                 '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
38
                    timedelta(minutes=timezone_offset)
39
            except ValueError:
40
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
41
                                       description="API.INVALID_START_DATETIME_FORMAT")
42
43
        if end_datetime_local is None:
44
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
45
                                   description="API.INVALID_END_DATETIME_FORMAT")
46
        else:
47
            end_datetime_local = str.strip(end_datetime_local)
48
            try:
49
                end_datetime_utc = datetime.strptime(end_datetime_local,
50
                                                               '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
51
                    timedelta(minutes=timezone_offset)
52
            except ValueError:
53
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
54
                                       description="API.INVALID_END_DATETIME_FORMAT")
55
56
        if start_datetime_utc >= end_datetime_utc:
57
            raise falcon.HTTPError(falcon.HTTP_400,
58
                                   title='API.BAD_REQUEST',
59
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
60
61
        cnx = mysql.connector.connect(**config.myems_fdd_db)
62
        cursor = cnx.cursor()
63
64
        query = (" SELECT id, recipient_name, recipient_email, "
65
                 "        subject, message, attachment_file_name, "
66
                 "        created_datetime_utc, scheduled_datetime_utc, status "
67
                 " FROM tbl_email_messages "
68
                 " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
69
                 " ORDER BY created_datetime_utc ")
70
        cursor.execute(query, (start_datetime_utc, end_datetime_utc))
71
        rows = cursor.fetchall()
72
73
        if cursor:
74
            cursor.close()
75
        if cnx:
76
            cnx.disconnect()
77
78
        result = list()
79
        if rows is not None and len(rows) > 0:
80
            for row in rows:
81
                meta_result = {"id": row[0],
82
                               "recipient_name": row[1],
83
                               "recipient_email": row[2],
84
                               "subject": row[3],
85
                               "message": row[4].replace("<br>", ""),
86
                               "attachment_file_name": row[5],
87
                               "created_datetime": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
88
                               "scheduled_datetime":
89
                                   row[7].timestamp() * 1000 if isinstance(row[7], datetime) else None,
90
                               "status": row[8]}
91
                result.append(meta_result)
92
93
        resp.text = json.dumps(result)
94
95
96 View Code Duplication
class EmailMessageItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
97
    @staticmethod
98
    def __init__():
99
        """"Initializes EmailMessageItem"""
100
        pass
101
102
    @staticmethod
103
    def on_options(req, resp, id_):
104
        resp.status = falcon.HTTP_200
105
106
    @staticmethod
107
    def on_get(req, resp, id_):
108
        access_control(req)
109
        if not id_.isdigit() or int(id_) <= 0:
110
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
111
                                   description='API.INVALID_EMAIL_MESSAGE_ID')
112
113
        cnx = mysql.connector.connect(**config.myems_fdd_db)
114
        cursor = cnx.cursor()
115
116
        query = (" SELECT id, recipient_name, recipient_email, "
117
                 "        subject, message, attachment_file_name, "
118
                 "        created_datetime_utc, scheduled_datetime_utc, status "
119
                 " FROM tbl_email_messages "
120
                 " WHERE id = %s ")
121
        cursor.execute(query, (id_,))
122
        row = cursor.fetchone()
123
124
        if cursor:
125
            cursor.close()
126
        if cnx:
127
            cnx.disconnect()
128
129
        if row is None:
130
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
131
                                   description='API.EMAIL_MESSAGE_NOT_FOUND')
132
133
        result = {"id": row[0],
134
                  "recipient_name": row[1],
135
                  "recipient_email": row[2],
136
                  "subject": row[3],
137
                  "message": row[4].replace("<br>", ""),
138
                  "attachment_file_name": row[5],
139
                  "created_datetime": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
140
                  "scheduled_datetime": row[7].timestamp() * 1000 if isinstance(row[7], datetime) else None,
141
                  "status": row[8]}
142
143
        resp.text = json.dumps(result)
144
145
    @staticmethod
146
    @user_logger
147
    def on_delete(req, resp, id_):
148
        access_control(req)
149
        if not id_.isdigit() or int(id_) <= 0:
150
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
151
                                   description='API.INVALID_EMAIL_MESSAGE_ID')
152
153
        cnx = mysql.connector.connect(**config.myems_fdd_db)
154
        cursor = cnx.cursor()
155
156
        cursor.execute(" SELECT id "
157
                       " FROM tbl_email_messages "
158
                       " WHERE id = %s ", (id_,))
159
        row = cursor.fetchone()
160
161
        if row is None:
162
            if cursor:
163
                cursor.close()
164
            if cnx:
165
                cnx.disconnect()
166
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
167
                                   description='API.EMAIL_MESSAGE_NOT_FOUND')
168
169
        cursor.execute(" DELETE FROM tbl_email_messages WHERE id = %s ", (id_,))
170
        cnx.commit()
171
172
        if cursor:
173
            cursor.close()
174
        if cnx:
175
            cnx.disconnect()
176
177
        resp.status = falcon.HTTP_204
178
179