-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmail_api.py
More file actions
executable file
·203 lines (184 loc) · 9.67 KB
/
gmail_api.py
File metadata and controls
executable file
·203 lines (184 loc) · 9.67 KB
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
#!/usr/bin/env python
import os
import json
import base64
import ssl
import requests
from google.cloud import pubsub_v1
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from retrying import retry
import logging
logger = logging.getLogger('gmail_app')
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
PROJECT_ID = os.environ.get('SFDC')
EMAIL = 'me'
if not PROJECT_ID:
raise 'No Project ID Found'
class gapi(object):
def __init__(self):
super(gapi, self).__init__()
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(os.environ.get('SFDC_GMAIL_CREDENTIALS'), SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
self.service = service.users()
self.subscriber = pubsub_v1.SubscriberClient()
self.history = None
self.history_id = None
self.is_first_email = True
self.last_message_id = None
def get_mail(self, message):
raw_email = None
attachmentId = None
response = None
response_data = None
messages = None
try:
try:
if self.is_first_email:
if not self.history and isinstance(message, str):
logger.debug('History ID not set from watch response, using subscriber \
message: {}'.format(message))
self.history_id = json.loads(message).get('historyId', {})
logger.debug('History Id set as: {}'.format(self.history_id))
else:
self.history_id = self.history.get('historyId', {})
logger.debug('First history id found setting self.history_id: {}'.format(
self.history_id))
self.is_first_email = False
else:
logger.debug('First email ALREADY found, using last self.history_id: \
{}'.format(self.history_id))
except Exception, e:
logger.error('Exception found: {}'.format(e))
pass
if self.history_id:
messages = self.service.history().list(
userId=EMAIL, startHistoryId=self.history_id).execute()
logger.debug('From the last history id: {}, new history ids have come in: {}\
'.format(self.history_id, messages))
if isinstance(messages, list):
logger.debug('Messages var is a list and expected a dict')
if messages.get('history', []):
logger.debug('Message var is a dict as expected and the message history is: {}\
'.format(messages['history']))
if isinstance(messages['history'], list):
logger.debug('Messages history -1 is: {}'.format(messages['history'][-1]))
if messages['history'][-1].get('messages', []):
try:
message_id = messages['history'][-1]['messages'][0]['id']
except Exception, e:
logger.error('No message history message id was found')
pass
if message_id and message_id != self.last_message_id:
self.last_message_id = message_id
logger.debug('The message history messages Id is: {}'.format(
messages['history'][-1]['messages'][0]['id']))
raw_email = self.service.messages().get(
userId=EMAIL, id=message_id).execute()
if raw_email:
logger.debug('Raw email val: {}'.format(raw_email))
else:
logger.error('No raw email found when there should have been one.')
else:
logger.debug('This message was already processed, skipping this \
message, current history id: {} - current message details: {}\
'.format(self.history_id, messages))
else:
logger.error('No message was found when getting: \
"messages[\'history\'][0].get(\'messages\')"')
elif messages.get('historyId', []):
logger.debug('New historyid detected, replacing old self.history_id({}) with \
new: {}'.format(self.history_id, messages['historyId']))
self.history_id = messages['historyId']
if raw_email:
has_attachment = False
try:
if 'parts' in raw_email['payload']['parts'][0].keys():
message_contents = base64.urlsafe_b64decode(raw_email['payload']['parts'][0]['parts'][0]['body']['data'].encode('UTF8'))
logger.debug('Message Contents found with attachment')
has_attachment = True
elif 'body' in raw_email['payload']['parts'][0].keys():
message_contents = base64.urlsafe_b64decode(raw_email['payload']['parts'][0]['body']['data'].encode('UTF8'))
logger.debug('Message Contents found without attachment\n{}\n{}\n{}\n: '.format('*' * 20, message_contents, '*' * 20))
except Exception, e:
logger.error('Failed to collect message_contents: {}'.format(e))
if has_attachment:
try:
raw_email['payload']['parts'][1]['filename'] # set to filename if you would like to use
except Exception, e:
logger.error('Failed to collect filename: {}'.format(e))
try:
attachmentId = raw_email['payload']['parts'][1]['body']['attachmentId']
except Exception, e:
logger.error('Failed to collect attachmentId: {}'.format(e))
if attachmentId:
response = self.service.messages().attachments().get(userId=EMAIL, messageId=message_id, id=attachmentId).execute()
if response:
response_data = base64.urlsafe_b64decode(response['data'].encode('UTF8'))
if response_data:
attachment_data = response_data[3:] if response_data[:3] == '\xef\xbb\xbf' else response_data
with open('logfile.txt', 'w+') as f:
f.write(attachment_data)
logger.debug('Attachment Data: {}'.format(attachment_data))
else:
logger.debug('No self.history_id found...')
except Exception, e:
logger.error('Caught Exception 1: {}'.format(e))
if isinstance(message, str) and not self.is_first_email:
self.history_id = json.loads(message).get('historyId', {})
logger.debug('Message is a string, coverting to json then setting self.history_id to: {}'.format(self.history_id))
elif not isinstance(message, str) and not self.is_first_email:
try:
self.history_id = message.get('historyId', {})
logger.debug('Message is json, setting self.history_id to: {}'.format(self.history_id))
except Exception, e:
logger.debug('Caught Exception 2: {}'.format(e))
logger.debug('{}{}{}{}{}'.format('\n', '=' * 30, 'End', '=' * 30, '\n'))
def stop(self):
self.service.stop(userId=EMAIL).execute()
logger.debug('Stopping Watcher')
def callback(self, message):
logger.debug('Message Data: {}'.format(message.data))
try:
response = requests.post(url='http://0.0.0.0:5000/get_mail', json=json.loads(message.data))
except Exception, e:
logger.error('Exception: {}'.format(e))
logger.debug('Callback response: {}'.format(response))
message.ack()
def sub_to_topic(self):
logger.debug('Starting sub_to_topic')
subscription_name = 'projects/{project_id}/subscriptions/{sub}'.format(
project_id=PROJECT_ID,
sub='sub_new_email_v1',
)
logger.debug('{}{}{}{}{}'.format('\n', '=' * 30, 'Starting', '=' * 30, '\n'))
logger.debug('Subscribing to new callback')
self.subscriber.subscribe(subscription_name, self.callback)
@retry(wait_exponential_multiplier=1000, wait_exponential_max=60000,
retry_on_exception=ssl.SSLError, stop_max_attempt_number=5)
def watch(self):
pub_topic = 'new_email'
inbox_labels = ['UNREAD']
request = {
"labelIds": inbox_labels,
"topicName": "projects/{}/topics/{}".format(PROJECT_ID, pub_topic),
"labelFilterAction": "include"
}
try:
self.history = self.service.watch(userId=EMAIL, body=request).execute()
except ssl.SSLError:
logger.debug('\n------\nssl.SSLError, retrying\n------\n\n')
logger.debug('Setting first history point: {}'.format(self.history))
def start():
api = gapi()
api.sub_to_topic()
api.stop()
api.watch()
if __name__ == '__main__':
start()