blob: f088ad63a31fa2f193b03d53a99e143175237d9b [file] [log] [blame]
Dan Albertd3fe4f12015-04-17 13:01:29 -07001#
2# Copyright (C) 2015 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the 'License');
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an 'AS IS' BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16import base64
17import httplib2
18
19import config
20
21
22def get_body(msg):
23 if 'attachmentId' in msg['payload']['body']:
24 raise NotImplementedError('Handling of messages contained in '
25 'attachments not yet implemented.')
26 b64_body = msg['payload']['body']['data']
27 return base64.urlsafe_b64decode(b64_body.encode('ASCII'))
28
29
30def build_service():
31 from apiclient.discovery import build
32 from oauth2client.client import flow_from_clientsecrets
33 from oauth2client.file import Storage
34 from oauth2client.tools import run
35
36 OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.modify'
37 STORAGE = Storage('oauth.storage')
38
39 # Start the OAuth flow to retrieve credentials
40 flow = flow_from_clientsecrets(config.client_secret_file,
41 scope=OAUTH_SCOPE)
42 http = httplib2.Http()
43
44 # Try to retrieve credentials from storage or run the flow to generate them
45 credentials = STORAGE.get()
46 if credentials is None or credentials.invalid:
47 credentials = run(flow, STORAGE, http=http)
48
49 http = credentials.authorize(http)
50 return build('gmail', 'v1', http=http)
51
52
53def get_gerrit_label(labels):
54 for label in labels:
55 if label['name'] == 'gerrit':
56 return label['id']
57 return None
58
59
60def get_all_messages(service, label):
61 msgs = []
62 response = service.users().messages().list(
63 userId='me', labelIds=label).execute()
64 if 'messages' in response:
65 msgs.extend(response['messages'])
66 while 'nextPageToken' in response:
67 page_token = response['nextPageToken']
68 response = service.users().messages().list(
69 userId='me', pageToken=page_token).execute()
70 msgs.extend(response['messages'])
71 return msgs