Skip to content

Commit

Permalink
Merge pull request googleapis#1 from janscas/master
Browse files Browse the repository at this point in the history
update
  • Loading branch information
PhoenixAlx authored Apr 27, 2018
2 parents cbb701f + 5dce8f8 commit 895d795
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 11 deletions.
31 changes: 29 additions & 2 deletions O365/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class Protocol:
_protocol_url = 'not_defined' # Main url to request. Override in subclass
_oauth_scope_prefix = '' # prefix for scopes (in MS GRAPH is 'https://graph.microsoft.com/' + SCOPE)
_oauth_scopes = {} # dictionary of {scopes_name: [scope1, scope2]}
_protocol_endpoint_transform = {} # a dictionary of endpoints transformations

def __init__(self, *, protocol_url=None, api_version=None, default_resource=ME_RESOURCE,
casing_function=None, protocol_scope_prefix=None, timezone=None):
Expand Down Expand Up @@ -163,6 +164,13 @@ def _prefix_scope(self, scope):
else:
return scope

def transform_endpoint(self, endpoint):
""" Converts and endpoint by replacing keywords """
for key_word, replacement in self._protocol_endpoint_transform.items():
if key_word in endpoint:
endpoint = endpoint.replace(key_word, replacement)
return endpoint

@staticmethod
def get_iana_tz(windows_tz):
""" Returns a valid pytz TimeZone (Iana/Olson Timezones) from a given windows TimeZone
Expand Down Expand Up @@ -193,7 +201,9 @@ def get_windows_tz(self, iana_tz=None):


class MSGraphProtocol(Protocol):
""" A Microsoft Graph Protocol Implementation """
""" A Microsoft Graph Protocol Implementation
https://docs.microsoft.com/en-us/outlook/rest/compare-graph-outlook
"""

_protocol_url = 'https://graph.microsoft.com/'
_oauth_scope_prefix = 'https://graph.microsoft.com/'
Expand All @@ -211,7 +221,9 @@ def __init__(self, api_version='v1.0', default_resource=ME_RESOURCE, **kwargs):


class MSOffice365Protocol(Protocol):
""" A Microsoft Office 365 Protocol Implementation """
""" A Microsoft Office 365 Protocol Implementation
https://docs.microsoft.com/en-us/outlook/rest/compare-graph-outlook
"""

_protocol_url = 'https://outlook.office.com/api/'
_oauth_scope_prefix = 'https://outlook.office.com/'
Expand All @@ -236,6 +248,9 @@ class BasicAuthProtocol(MSOffice365Protocol):
"""

_protocol_url = 'https://outlook.office365.com/api/'
_protocol_endpoint_transform = {
'mailFolders': 'Folders'
}

def __init__(self, api_version='v1.0', default_resource=ME_RESOURCE, **kwargs):
super().__init__(api_version=api_version, default_resource=default_resource, **kwargs)
Expand Down Expand Up @@ -477,6 +492,18 @@ def request(self, url, method, **kwargs):

log.info('Received response ({}) from URL {}'.format(response.status_code, response.url))

if response.status_code == 429: # too many requests
# Status Code 429 is not automatically retried by default.
retry_after = response.headers.get('retry-after')
reason = response.headers.get('rate-limit-reason')
log.info('The Server respond with 429: Too Many Requests. Reason {}. Retry After {} seconds.'.format(reason, retry_after))
# retry after seconds:
if retry_after < 6:
time.sleep(retry_after)
log.info('Retrying request now after waiting for {} seconds'.format(retry_after))
response = self.session.request(method, url, **kwargs) # retrying request
log.info('Received response ({}) from URL {}'.format(response.status_code, response.url))

if not response.ok and self.raise_http_errors:
raise self.raise_api_exception(response)
return response
Expand Down
16 changes: 8 additions & 8 deletions O365/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,9 @@ def __init__(self, *, parent=None, con=None, **kwargs):

self._track_changes = set() # TODO: change update method on message...
self.object_id = cloud_data.get(cc('id'), None)
self.created = cloud_data.get(cc('createdDateTime'), None)
self.received = cloud_data.get(cc('receivedDateTime'), None)
self.sent = cloud_data.get(cc('sentDateTime'), None)
self.created = cloud_data.get(cc('createdDateTime'), cloud_data.get(cc('dateTimeCreated'), None)) # fallback to office365 v1.0
self.received = cloud_data.get(cc('receivedDateTime'), cloud_data.get(cc('dateTimeReceived'), None)) # fallback to office365 v1.0
self.sent = cloud_data.get(cc('sentDateTime'), cloud_data.get(cc('dateTimeSent'), None)) # fallback to office365 v1.0

local_tz = self.protocol.timezone
self.created = parse(self.created).astimezone(local_tz) if self.created else None
Expand All @@ -219,7 +219,7 @@ def __init__(self, *, parent=None, con=None, **kwargs):
self.__bcc = self._recipients_from_cloud(cloud_data.get(cc('bccRecipients'), []))
self.__reply_to = self._recipients_from_cloud(cloud_data.get(cc('replyTo'), []))
self.__categories = cloud_data.get(cc('categories'), [])
self.__importance = ImportanceLevel(cloud_data.get(cc('importance'), 'normal') or 'normal')
self.__importance = ImportanceLevel((cloud_data.get(cc('importance'), 'normal') or 'normal').lower()) # lower because of office365 v1.0
self.is_read = cloud_data.get(cc('isRead'), None)
self.is_draft = cloud_data.get(cc('isDraft'), kwargs.get('is_draft', True)) # a message is a draft by default
self.conversation_id = cloud_data.get(cc('conversationId'), None)
Expand Down Expand Up @@ -557,10 +557,10 @@ def save_draft(self, target_folder=WellKnowFolderNames.DRAFTS):
if not isinstance(target_folder, str):
target_folder = getattr(target_folder, 'folder_id', None)

if target_folder and target_folder is not WellKnowFolderNames.DRAFTS:
url = self.build_url(self._endpoints.get('create_draft_folder').format(id=target_folder))
else:
url = self.build_url(self._endpoints.get('create_draft'))
target_folder = target_folder or WellKnowFolderNames.DRAFTS
target_folder = target_folder.value if isinstance(target_folder, WellKnowFolderNames) else target_folder

url = self.build_url(self._endpoints.get('create_draft_folder').format(id=target_folder))

try:
response = self.con.post(url, data=data)
Expand Down
2 changes: 1 addition & 1 deletion O365/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def _parse_resource(resource):

def build_url(self, endpoint):
""" Returns a url for a given endpoint using the protocol service url """
return '{}{}'.format(self._base_url, endpoint)
return '{}{}'.format(self._base_url, self.protocol.transform_endpoint(endpoint))

def _gk(self, keyword):
""" Alias for protocol.get_service_keyword """
Expand Down

0 comments on commit 895d795

Please sign in to comment.