-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite_client.py
217 lines (203 loc) · 8.11 KB
/
sqlite_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import json
import sqlite3
import re
SQL_DATABASE = 'test_sql.db'
class SQLiteClient:
"""
SQLite Client interacts with database built
to fetch and store emails in db as cache
"""
def __init__(self):
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
# UNIQUEKEY: *Primary Key* '{user}{uid}' combines user and uid
# SERVICE: service provider: 'gmail', 'yahoo'
# SEEN: if the email has been seen or not: 'True'/'False'
# FLAGGED: if emails is starred: 'True'/'False'
# UID: unique email id from imap server
# SUBJECT: subject of email
# FROM_: from address
# TO_: to address
# DATE: date string of when email was sent/received
# HTML: html string of email
table ='''CREATE TABLE AllEmails
(
UNIQUEKEY VARCHAR(255) PRIMARY KEY UNIQUE,
SERVICE VARCHAR(255),
SEEN VARCHAR(255),
FLAGGED VARCHAR(255),
UID VARCHAR(255),
SUBJECT VARCHAR(255),
FROM_ VARCHAR(255),
TO_ VARCHAR(255),
DATE VARCHAR(255),
HTML VARCHAR(255)
)'''
try:
cursor.execute(table)
except Exception as e:
# print(e)
pass
table = '''CREATE TABLE Folders
(
FOLDER VARCHAR(255) PRIMARY KEY UNIQUE
)'''
try:
cursor.execute(table)
except Exception as e:
# print(e)
pass
def fetch(self, email_service: str, limit: int, offset: int):
"""
Fetch emails from specific email service provider using limit and offset bounds.
:return: list of emails in json format
"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
result = cursor.execute(f'''SELECT SERVICE, SEEN, FLAGGED, UID, SUBJECT, FROM_, TO_, DATE
FROM AllEmails WHERE SERVICE = "{email_service}"
ORDER BY datetime(DATE) DESC LIMIT {limit} OFFSET {offset}''')
fetch = result.fetchall()
cursor.close()
conn.close()
# convert fetch data into json format
json_data = json.dumps(fetch)
# converting data back to python obj in json format
data = json.loads(json_data)
data[:0] = [['service', 'seen', 'flagged', 'uid', 'subject', 'from', 'to', 'date']]
# applying keys to each row of data
output = [dict(zip(data[0], row)) for row in data[1:]]
return output
def fetch_all(self, limit: int, offset: int):
"""
Fetch emails from all accounts using limit and offset bounds.
:return: list of emails in json format
"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
result = cursor.execute(f'''SELECT SERVICE, SEEN, FLAGGED, UID, SUBJECT, FROM_, TO_, DATE
FROM AllEmails ORDER BY datetime(DATE) DESC LIMIT {limit} OFFSET {offset}''')
fetch = result.fetchall()
conn.commit()
cursor.close()
conn.close()
# convert fetch data into json format
json_data = json.dumps(fetch)
# converting data back to python obj in json format
data = json.loads(json_data)
data[:0] = [['service', 'seen', 'flagged', 'uid', 'subject', 'from', 'to', 'date']]
# applying keys to each row of data
output = [dict(zip(data[0], row)) for row in data[1:]]
return output
def fetch_email(self, email_service: str, uid: str):
"""
Fetch email message in html format.
:return: html string
"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
result = cursor.execute(f'SELECT HTML FROM AllEmails WHERE UID = "{uid}" AND SERVICE = "{email_service}"')
fetch = result.fetchone()
conn.commit()
cursor.close()
conn.close()
return fetch[0].rstrip()
def add_to_folder(self, folder: list, key: str):
# print(f"folder: {folder[0]}, uid: {key}")
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
cursor.execute(sql_query)
try:
cursor.execute(f'''INSERT INTO "{folder[0]}"
( UNIQUEKEY )
VALUES ( ? )''',
(key, ))
conn.commit()
return
except Exception as e:
print("Exception:", e)
return 'Email Exists'
finally:
cursor.close()
conn.close()
def create_folder(self, folder: str):
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
print("Creating Folder:", folder)
table =f'''CREATE TABLE "{folder}"
(
UNIQUEKEY VARCHAR(255) PRIMARY KEY UNIQUE
)'''
try:
cursor.execute(table)
except Exception as e:
print("Exception:", e)
pass
try:
cursor.execute('''INSERT INTO Folders
( FOLDER )
VALUES ( ? )''',
(folder, ))
conn.commit()
return 'Success'
except Exception as e:
print("Exception:", e)
return 'Duplicate'
finally:
cursor.close()
conn.close()
def fetch_folder(self, folder: str):
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
cursor.execute(f'SELECT * FROM "{folder[0]}"')
folder_emails = cursor.fetchall()
output = []
for result in folder_emails:
key: str = result[0]
if 'gmail' in key:
uid = key.split('gmail')[0]
service = 'gmail'
if 'outlook' in key:
uid = key.split('outlook')[0]
service = 'outlook'
result = cursor.execute(f'''SELECT SERVICE, SEEN, FLAGGED, UID, SUBJECT, FROM_, TO_, DATE
FROM AllEmails WHERE UID = "{uid}" AND SERVICE = "{service}" ORDER BY datetime(DATE)''')
fetch = result.fetchall()
# convert fetch data into json format
json_data = json.dumps(fetch)
# converting data back to python obj in json format
data = json.loads(json_data)
data[:0] = [['service', 'seen', 'flagged', 'uid', 'subject', 'from', 'to', 'date']]
# applying keys to each row of data
output.append([dict(zip(data[0], row)) for row in data[1:]][0])
return output
def list_folders(self):
"""
List all from Folders table
:return: list of strings
"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
cursor.execute('SELECT * FROM Folders')
tables = cursor.fetchall()
return tables
def store_email(self, uniquekey: str, email_service: str, seen: str, flagged: str, uid: str, subject: str, from_: str, to: str, date: str, html: str):
"""
Store email in DB for quick fetch.
:return: 'Done' on duplicate to stop loop, None to continue fetching.
"""
conn = sqlite3.connect(SQL_DATABASE)
cursor = conn.cursor()
try:
cursor.execute('''INSERT INTO AllEmails
( UNIQUEKEY, SERVICE, SEEN, FLAGGED, UID, SUBJECT, FROM_, TO_, DATE , HTML )
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )''',
(uniquekey, email_service, seen, flagged, uid, subject, from_, to, date, html))
conn.commit()
return
except:
return 'Done'
finally:
cursor.close()
conn.close()