Skip to content

Commit

Permalink
request azure authorization token every 5mn, fixes #111
Browse files Browse the repository at this point in the history
  • Loading branch information
luc wastiaux committed Jul 5, 2020
1 parent edd363a commit bb32d9a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
18 changes: 16 additions & 2 deletions awesometts/service/azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"""

import time
import datetime
import requests
from xml.etree import ElementTree
from .base import Service
Expand Down Expand Up @@ -165,7 +166,8 @@ class Azure(Service):
"""

__slots__ = [
'access_token'
'access_token',
'access_token_timestamp'
]

NAME = "Microsoft Azure"
Expand Down Expand Up @@ -235,13 +237,25 @@ def get_token(self, subscription_key, region):
}
response = requests.post(fetch_token_url, headers=headers)
self.access_token = str(response.text)
self.access_token_timestamp = datetime.datetime.now()
self._logger.debug(f'requested access_token')

def token_refresh_required(self):
if self.access_token == None:
self._logger.debug(f'no token, must request')
return True
time_diff = datetime.datetime.now() - self.access_token_timestamp
if time_diff.total_seconds() > 300:
self._logger.debug(f'time_diff: {time_diff}, requesting token')
return True
return False

def run(self, text, options, path):
"""Downloads from Azure API directly to an MP3."""

region = options['region']
subscription_key = options['key']
if self.access_token == None:
if self.token_refresh_required():
self.get_token(subscription_key, region)

voice = options['voice']
Expand Down
2 changes: 2 additions & 0 deletions tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import magic # to verify file types
import os
import sys
import time

class Success(Exception):
pass
Expand Down Expand Up @@ -184,6 +185,7 @@ def run_service_testcases(self, svc_id, test_cases, extra_option_keys=[], lowerc
self.logger.info(f'Default options for service {svc_id}: {options}')

for test_case in test_cases:
# time.sleep(3) # used this to test azure token refresh code
options['voice'] = test_case['voice']
# set extra option keys
for extra_option_key in extra_option_keys:
Expand Down

0 comments on commit bb32d9a

Please sign in to comment.