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
|
#!/usr/bin/python2.4
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Sample to demonstrate the Email Audit API's email monitoring functions.
The sample demonstrates the creating, updating, retrieving and deleting of
email monitors.
"""
__author__ = 'Gunjan Sharma <gunjansharma@google.com>'
from datetime import datetime
import getopt
import re
import sys
import gdata
from gdata.apps.audit.service import AuditService
class EmailMonitoringException(Exception):
"""Exception class for EmailMonitoring, shows appropriate error message."""
class EmailMonitoring(object):
"""Sample demonstrating how to perform CRUD operations on email monitor."""
def __init__(self, consumer_key, consumer_secret, domain):
"""Create a new EmailMonitoring object configured for a domain.
Args:
consumer_key: A string representing a consumerKey.
consumer_secret: A string representing a consumerSecret.
domain: A string representing the domain to work on in the sample.
"""
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.domain = domain
self._Authorize()
def _Authorize(self):
"""Asks the domain's admin to authorize access to the apps Apis."""
self.service = AuditService(domain=self.domain, source='emailAuditSample')
self.service.SetOAuthInputParameters(
gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
self.consumer_key, self.consumer_secret)
request_token = self.service.FetchOAuthRequestToken()
self.service.SetOAuthToken(request_token)
auth_url = self.service.GenerateOAuthAuthorizationURL()
print auth_url
raw_input('Manually go to the above URL and authenticate.'
'Press Return after authorization.')
self.service.UpgradeToOAuthAccessToken()
def _CheckUsername(self, username):
"""Checks if a given username is valid or not.
Args:
username: A string to check for validity.
Returns:
True if username is valid, False otherwise.
"""
if len(username) > 64:
print 'Username length should be less than 64'
return False
pattern = re.compile('[^\w\.\+-_\']+')
return not bool(pattern.search(username))
def _GetValidUsername(self, typeof):
"""Takes a valid username as input.
Args:
typeof: A string representing the type of user.
Returns:
A valid string corresponding to username.
"""
username = ''
while not username:
username = raw_input('Enter a valid %s username: ' % typeof)
if not self._CheckUsername(username):
print 'Invalid username'
username = ''
return username
def _GetValidDate(self, is_neccessary):
"""Takes a valid date as input in 'yyyy-mm-dd HH:MM' format.
Args:
is_neccessary: A boolean denoting if a non empty value is needed.
Returns:
A valid string corresponding to date.
"""
date = ''
extra_stmt = ''
if not is_neccessary:
extra_stmt = '. Press enter to skip.'
while not date:
date = raw_input(
'Enter a valid date as (yyyy-mm-dd HH:MM)%s:' % extra_stmt)
if not (date and is_neccessary):
return date
try:
datetime.strptime(date, '%Y-%m-%d %H:%M')
return date
except ValueError:
print 'Not a valid date!'
date = ''
def _GetBool(self, name):
"""Takes a boolean value as input.
Args:
name: A string for which input is to be taken.
Returns:
A boolean for an entity represented by name.
"""
choice = raw_input(
'Enter your choice (t/f) for %s (defaults to False):' % name).strip()
if choice == 't':
return True
return False
def _CreateEmailMonitor(self):
"""Creates/Updates an email monitor."""
src_user = self._GetValidUsername('source')
dest_user = self._GetValidUsername('destination')
end_date = self._GetValidDate(True)
start_date = self._GetValidDate(False)
incoming_headers = self._GetBool('incoming headers')
outgoing_headers = self._GetBool('outgoing headers')
drafts = self._GetBool('drafts')
drafts_headers = False
if drafts:
drafts_headers = self._GetBool('drafts headers')
chats = self._GetBool('chats')
chats_headers = False
if chats:
self._GetBool('chats headers')
self.service.createEmailMonitor(
src_user, dest_user,
end_date, start_date,
incoming_headers, outgoing_headers,
drafts, drafts_headers,
chats, chats_headers)
print 'Email monitor created/updated successfully!\n'
def _RetrieveEmailMonitor(self):
"""Retrieves all email monitors for a user."""
src_user = self._GetValidUsername('source')
monitors = self.service.getEmailMonitors(src_user)
for monitor in monitors:
for key in monitor.keys():
print '%s ----------- %s' % (key, monitor.get(key))
print ''
print 'Email monitors retrieved successfully!\n'
def _DeleteEmailMonitor(self):
"""Deletes an email monitor."""
src_user = self._GetValidUsername('source')
dest_user = self._GetValidUsername('destination')
self.service.deleteEmailMonitor(src_user, dest_user)
print 'Email monitor deleted successfully!\n'
def Run(self):
"""Handles the flow of the sample."""
functions_list = [
{
'function': self._CreateEmailMonitor,
'description': 'Create a email monitor for a domain user'
},
{
'function': self._CreateEmailMonitor,
'description': 'Update a email monitor for a domain user'
},
{
'function': self._RetrieveEmailMonitor,
'description': 'Retrieve all email monitors for a domain user'
},
{
'function': self._DeleteEmailMonitor,
'description': 'Delete a email monitor for a domain user'
}
]
while True:
print 'What would you like to do? Choose an option:'
print '0 - To exit'
for i in range (0, len(functions_list)):
print '%d - %s' % ((i + 1), functions_list[i].get('description'))
choice = raw_input('Enter your choice: ').strip()
if choice.isdigit():
choice = int(choice)
if choice == 0:
break
if choice < 0 or choice > len(functions_list):
print 'Not a valid option!'
continue
try:
functions_list[choice - 1].get('function')()
except gdata.apps.service.AppsForYourDomainException, e:
if e.error_code == 1301:
print '\nError: Invalid username!!\n'
else:
raise e
def PrintUsageString():
"""Prints the correct call for running the sample."""
print ('python email_audit_email_monitoring.py '
'--consumer_key [ConsumerKey] --consumer_secret [ConsumerSecret] '
'--domain [domain]')
def main():
"""Runs the sample using an instance of EmailMonitoring."""
try:
opts, args = getopt.getopt(sys.argv[1:], '', ['consumer_key=',
'consumer_secret=',
'domain='])
except getopt.error, msg:
PrintUsageString()
sys.exit(1)
consumer_key = ''
consumer_secret = ''
domain = ''
for option, arg in opts:
if option == '--consumer_key':
consumer_key = arg
elif option == '--consumer_secret':
consumer_secret = arg
elif option == '--domain':
domain = arg
if not (consumer_key and consumer_secret and domain):
print 'Requires exactly three flags.'
PrintUsageString()
sys.exit(1)
try:
email_monitoring = EmailMonitoring(
consumer_key, consumer_secret, domain)
email_monitoring.Run()
except gdata.apps.service.AppsForYourDomainException, e:
raise EmailMonitoringException('Invalid Domain')
except gdata.service.FetchingOAuthRequestTokenFailed, e:
raise EmailMonitoringException('Invalid consumer credentials')
except Exception, e:
if e.args[0].get('status') == 503:
raise EmailMonitoringException('Server busy')
elif e.args[0].get('status') == 500:
raise EmailMonitoringException('Internal server error')
else:
raise EmailMonitoringException('Unknown error')
if __name__ == '__main__':
main()
|