-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoader.py
215 lines (166 loc) · 6.21 KB
/
Loader.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
import pickle
import os.path
import pandas as pd
import MessageHeandler
from email.mime.text import MIMEText
import base64
class Loader:
def __init__(self,service,directory,label_ids):
"""
Parameters
----------
service : Authorized Gmail API service instance.
directory : User directory.
label_ids : User LabelIds.
"""
self.service = service
self.directory = directory
self.user_label_ids = label_ids
if(os.path.exists(self.directory+'/spam/list')):
with open(self.directory+'/spam/list','rb') as file:
self.spam_ids = pickle.load(file)
else:
self.spam_ids = set()
def list_messages(self):
"""
List all Messages of the user's mailbox.
Returns
-------
List of Messages. Note that the returned list contains Message IDs,
you must use get with the appropriate ID to get the details of a Message.
"""
response = self.service.users().messages().list(userId='me').execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = self.service.users().messages().list(userId='me',pageToken=page_token).execute()
if 'messages' in response:
messages.extend(response['messages'])
return messages
def get_message(self,msg_id):
"""
Get a Message with given ID.
Parameters
----------
msg_id: The ID of the Message.
Returns
-------
message: Message.
"""
message = self.service.users().messages().get(userId='me', id=msg_id,format = 'full').execute()
return message
def save_message(self,msg_id):
"""
Save a Message if it is not spam or if it has not been saved yet.
Parameters
----------
msg_id: The ID of the Message.
"""
if(not self.spam(msg_id)):
if(not os.path.exists(self.directory+'/mails/mail_{}'.format(msg_id))):
msg = self.get_message(msg_id)
if(MessageHeandler.is_user_msg(msg)):
msg_data = MessageHeandler.pack_message(msg,self.user_label_ids)
with open(self.directory+'/mails/mail_{}'.format(msg_id),'wb') as file:
pickle.dump(msg_data,file)
else:
self.spam_ids.add(msg_id)
def save_all(self):
"""
Load all Messages from user's mailbox and save them on disk.
Does not resave Messages that has already been saved.
"""
message_list = self.list_messages()
for msg_info in message_list:
self.save_message(msg_info['id'])
self.save_spam()
def load_all(self):
"""
Load all Messages from disk to DataFrame.
Returns
-------
data : DataFrame with user Messages.
"""
data = pd.DataFrame()
for mail in os.listdir(self.directory+'/mails'):
with open(self.directory+'/mails/'+mail,'rb') as file:
cur_mail = pd.DataFrame.from_dict(pickle.load(file))
data = data.append(cur_mail,ignore_index = True)
return data
def spam(self,msg_id):
"""
Check whether Message ID contains in Spam IDs.
Parameters
----------
msg_id: The ID of the Message.
Returns
-------
True if msg_id contains in spam, in the other case returns False.
"""
if(msg_id in self.spam_ids):
return True
return False
def save_spam(self):
"""
Save Spam IDs on disk for reusage purpose.
"""
with open(self.directory+'/spam/list','wb') as file:
pickle.dump(self.spam_ids,file)
def send_message(self, message):
"""
Send an email Message.
Parameters
----------
message: Message to be sent.
Returns
-------
Sent Message.
"""
message = self.service.users().messages().send(userId='me', body=message).execute()
return message
def create_message(message_text,subject,address = '[email protected]'):
"""
Create a Message for an email.
Parameters
----------
message_text: Text of the email Message.
subject: Subject of the email Message.
address: Email address.
Returns
-------
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['To'] = address
message['Subject'] = subject
raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))
return {'raw': raw_message.decode("utf-8")}
def create_label(self, label_object):
"""
Creates a new label within user's mailbox.
Parameters
----------
label_object: label to be added.
Returns
-------
None.
"""
return self.service.users().labels().create(userId='me',body=label_object).execute()
def make_label(label_name, mlv='show', llv='labelShow'):
"""
Create new Label object.
Parameters
----------
label_name: The name of the Label.
mlv: Message list visibility, show/hide.
llv: Label list visibility, labelShow/labelHide.
Returns
-------
Created Label object.
"""
label = {'messageListVisibility': mlv,
'name': label_name,
'labelListVisibility': llv}
return label