/
app.py
390 lines (319 loc) · 13.8 KB
/
app.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
import logging
import sys
import httplib2
import re
import json
import redis
import urllib
import base64
import email
import uuid
from premailer import transform
from threading import Thread
from apiclient import errors
from flask import Markup
from flask import Flask, abort, redirect, url_for, Response, render_template, session, request
#from flask.ext.sqlalchemy import SQLAlchemy
#from sqlalchemy.dialects.postgresql import JSON
#from rq import Queue
#from rq.job import Job
#from worker import conn
redis_url = os.getenv('REDISCLOUD_URL', 'redis://localhost:6379')
conn = redis.StrictRedis.from_url(redis_url)
from googleapiclient import discovery
from googleapiclient.http import BatchHttpRequest
from oauth2client import client
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(conn)
app = Flask(__name__)
KVSessionExtension(store, app)
#app.config['SESSION_TYPE'] = 'memcached'
from messages import get_messages
app.config['SECRET_KEY'] = 'super secret key'
#app.debug = True
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)
#app.config.from_object(os.environ['APP_SETTINGS'])
#db = SQLAlchemy(app)
#q = Queue(connection=conn)
#from contacts import get_messages
#from models import *
@app.route('/')
def index():
session['contactsNextPageToken'] = 0
session['contacts'] = []
session['seen'] = []
session['mails'] = []
session['messageIds'] = []
session['maillist'] = []
session['messagelist'] = []
if 'credentials' not in session:
return redirect(url_for('oauth2callback'))
credentials = client.OAuth2Credentials.from_json(session['credentials'])
if credentials.access_token_expired:
return redirect(url_for('oauth2callback'))
else:
return render_template('index.html')
@app.route('/oauth2callback')
def oauth2callback():
flow = client.flow_from_clientsecrets('client_secrets.json',
scope='https://www.googleapis.com/auth/gmail.readonly',
redirect_uri=url_for('oauth2callback',_external=True))
if 'code' not in request.args:
auth_uri = flow.step1_get_authorize_url()
return redirect(auth_uri)
else:
auth_code = request.args.get('code')
credentials = flow.step2_exchange(auth_code)
session['credentials'] = credentials.to_json()
return redirect(url_for('index'))
@app.route('/v1/gmail/contacts/<int:pagenr>')
def contacts(pagenr):
# Authorize the httplib2.Http object with our credentials
credentials = client.OAuth2Credentials.from_json(session['credentials'])
http = credentials.authorize(httplib2.Http(cache=".cache"))
# Build the Gmail service from discovery
gmail_service = discovery.build('gmail', 'v1', http=http)
while (len(session['seen'])+1 < pagenr*10):
# Retrieve a page of threads
# Print ID for each thread
# if threads['threads']:
# for thread in threads['threads']:
# print 'Thread ID: %s' % (thread['id'])
def contactscallbackfunc(result, results, moreresults):
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if 'UNREAD' in results['labelIds']:
Unread = 'true'
else:
Unread = 'false'
for header in results['payload']['headers']:
if header['name'] == 'Date':
Date = header['value']
if header['name'] == 'From':
From = header['value']
address = From.split()[-1]
address = re.sub(r'[<>]', '', address)
Address = address.strip()
Name = From.rsplit(' ', 1)[0]
From = From.replace('\"','')
Name = Name.replace('\"','')
if From not in session['seen']:
Contact = {
'id': len(session['seen']),
'date': Date,
'name': Name,
'address': Address,
'snippet': results['snippet'],
'unread': Unread
}
session['contacts'].append(Contact)
session['seen'].append(From)
message_ids = gmail_service.users().messages().list(userId='me', maxResults=50, labelIds='INBOX', pageToken=session['contactsNextPageToken']).execute()
batchContacts = BatchHttpRequest(callback=contactscallbackfunc)
#return message_ids['messages'][0]['id']
session['contactsNextPageToken'] = message_ids['nextPageToken']
for msg_id in message_ids['messages']:
batchContacts.add(gmail_service.users().messages().get(userId='me', id=msg_id['id'], format='metadata', metadataHeaders=['from', 'date']))
batchContacts.execute()
#return "test"
#def mailscallbackfunc(result, results, moreresults):
# if 'UNREAD' in results['labelIds']:
# Unread = 'true'
# else:
# Unread = 'false'
#
#batchMails = BatchHttpRequest(callback=mailscallbackfunc)
#for contact in session['seen']:
# batchContacts.add(gmail_service.users().messages().get(userId='me',
# id=msg_id['id'], format='metadata',
# metadataHeaders=['from', 'date']))
#batchMails.execute()
if pagenr - 1 == 0:
start = 0
end = 10
else:
start = (pagenr - 1) * 10 -1
end = pagenr * 10 -1
response = {'nextPageToken': session['contactsNextPageToken'], 'contacts': session['contacts'][start:end]}
js = json.dumps(response)
resp = Response(js, status=200, mimetype='application/json')
return resp
@app.route('/v1/gmail/message/<msg_id>')
def get_message(msg_id):
# Authorize the httplib2.Http object with our credentials
credentials = client.OAuth2Credentials.from_json(session['credentials'])
http = credentials.authorize(httplib2.Http(cache=".cache"))
# Build the Gmail service from discovery
gmail_service = discovery.build('gmail', 'v1', http=http)
try:
message = gmail_service.users().messages().get(userId='me', id=msg_id,
format='full').execute()
message_payload = message['payload']
if 'parts' in message_payload:
message_parts = message_payload['parts']
if 'parts' in message_parts:
message_parts['parts'] = message_parts['parts']
for part in message_parts:
if part['mimeType'] == 'text/html':
message_body=part['body']
else:
message_body=message_payload['body']
msg_str = base64.urlsafe_b64decode(message_body['data'].encode('utf-8'))
transformed_msg = transform(msg_str)
clean_msg = re.sub("<html>", "", transformed_msg, flags=re.DOTALL)
clean_msg = re.sub("</html>", "", clean_msg, flags=re.DOTALL)
clean_msg = re.sub('<head>.*?</head>', "", clean_msg, flags=re.DOTALL)
clean_msg = re.sub('<head>.*?</head>', "", clean_msg, flags=re.DOTALL)
clean_msg = clean_msg.replace('body', 'div', 1)
clean_msg = re.sub('<body>', "", clean_msg, flags=re.DOTALL)
clean_msg = re.sub('</body>', "", clean_msg, flags=re.DOTALL)
clean_msg = re.sub('<style type="text/css">.*?</style>', "", clean_msg, flags=re.DOTALL)
clean_msg = re.sub('<style type="text/css">.*?</style>', "", clean_msg, flags=re.DOTALL)
#return msg_str
#print 'Message snippet: %s' % message['snippet']
#mime_msg = email.message_from_string(msg_str)
#if mime_msg.is_multipart():
# for payload in mime_msg.get_payload():
# if payload.is_multipart(): ...
# message = payload.get_payload()
#return render_template('emailbody.html', emailbody=clean_msg)
return clean_msg
#return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
@app.route("/v1/gmail/messages/<int:contactId>", methods=['GET'])
def get_messages(contactId):
contact = session['seen'][contactId]
credentials = client.OAuth2Credentials.from_json(session['credentials'])
http = credentials.authorize(httplib2.Http(cache=".cache"))
# Build the Gmail service from discovery
gmail_service = discovery.build('gmail', 'v1', http=http)
def mailscallbackfunc(result, results, moreresults):
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if 'UNREAD' in results['labelIds']:
Unread = 'true'
else:
Unread = 'false'
for header in results['payload']['headers']:
if header['name'] == 'Date':
Date = header['value']
if header['name'] == 'From':
From = header['value']
if From == "Anders Damsgaard <andersdm@gmail.com>": #SKAL ÆNDRES
Sent = True
else:
Sent = False
if header['name'] == 'Subject':
Subject = header['value']
Contact = {
'messageId': results['id'],
'date': Date,
'subject': Subject,
'snippet': results['snippet'],
'unread': Unread,
'sent': Sent
}
session['mails'].append(Contact)
#for msg_id in message_ids['messages']:
# batchContacts.add(gmail_service.users().messages().get(userId='me',
# id=msg_id['id'], format='metadata',
# metadataHeaders=['from', 'date']))
#batchContacts.execute()
query = "\"to:'" + contact + "' AND from:me \" OR from:'" + contact + "'"
message_ids = gmail_service.users().messages().list(userId='me',
maxResults=10, labelIds='INBOX', q=query).execute()
batchMails = BatchHttpRequest(callback=mailscallbackfunc)
for msg_id in message_ids['messages']:
batchMails.add(gmail_service.users().messages().get(userId='me',
id=msg_id['id'], format='metadata',
metadataHeaders=['from', 'date', 'subject']))
batchMails.execute()
response = {'messages': session['mails']}
js = json.dumps(response)
resp = Response(js, status=200, mimetype='application/json')
return resp
@app.route("/v1/gmail/listmessages", methods=['GET'])
def get_listmessages():
def get_mailslist(message_ids, result, index, credentials):
mails = []
def mailscallbackfunc(result, results, moreresults):
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if 'UNREAD' in results['labelIds']:
Unread = 'true'
else:
Unread = 'false'
for header in results['payload']['headers']:
if header['name'] == 'Date':
Date = header['value']
if header['name'] == 'From':
From = header['value']
if From == "Anders Damsgaard <andersdm@gmail.com>": #SKAL ÆNDRES
Sent = True
else:
Sent = False
if header['name'] == 'Subject':
Subject = header['value']
Contact = {
'id': result,
'messageId': results['id'],
'date': Date,
'subject': Subject,
'snippet': results['snippet'],
'unread': Unread,
'sent': Sent
}
mails.append(Contact)
#for msg_id in message_ids['messages']:
# batchContacts.add(gmail_service.users().messages().get(userId='me',
# id=msg_id['id'], format='metadata',
# metadataHeaders=['from', 'date']))
#batchContacts.execute()
credentials = client.OAuth2Credentials.from_json(credentials)
http = credentials.authorize(httplib2.Http(cache=".cache"))
# Build the Gmail service from discovery
gmail_service = discovery.build('gmail', 'v1', http=http)
batchMails = BatchHttpRequest(callback=mailscallbackfunc)
for msg_id in message_ids['messages']:
batchMails.add(gmail_service.users().messages().get(userId='me',
id=msg_id['id'], format='metadata',
metadataHeaders=['from', 'date', 'subject']))
batchMails.execute()
results[index] = mails
return True
credentials = client.OAuth2Credentials.from_json(session['credentials'])
http = credentials.authorize(httplib2.Http(cache=".cache"))
# Build the Gmail service from discovery
gmail_service = discovery.build('gmail', 'v1', http=http)
def mailIdscallbackfunc(result, results, moreresults):
session['messageIds'].append(results)
batchMailIds = BatchHttpRequest(callback=mailIdscallbackfunc)
for contact in session['seen'][0:10]:
query = "\"to:'" + contact + "' AND from:me \" OR from:'" + contact + "'"
batchMailIds.add(gmail_service.users().messages().list(userId='me', maxResults=10, labelIds='INBOX', q=query))
batchMailIds.execute()
threads = [None]*10
results = [None]*10
for i in range(0, 10):
threads[i] = Thread(target=get_mailslist, args=(session['messageIds'][i], results, i, session['credentials']))
threads[i].start()
for i in range(0, 10):
threads[i].join()
js = json.dumps(results)
resp = Response(js, status=200, mimetype='application/json')
return resp
#if __name__ == '__main__':
# app.config['SECRET_KEY'] = 'super secret key'
# app.debug = True
# app.run()