You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.2 KiB

  1. import datetime
  2. from googleapiclient.discovery import build
  3. from oauth2client import client
  4. from oauth2client import tools
  5. from oauth2client.file import Storage
  6. import httplib2
  7. import os
  8. import argparse
  9. from gapi import config
  10. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  11. HOUR = datetime.timedelta(seconds=60 ** 2)
  12. class API:
  13. def __init__(
  14. self,
  15. service,
  16. scopes,
  17. app_name,
  18. client_secret_file=os.path.join(config.state_dir, "client_secret.json"),
  19. credentials_dir=config.state_dir,
  20. version="v3",
  21. ):
  22. self.service_name = service
  23. self.app_name = app_name
  24. self.client_secret_file = client_secret_file
  25. self.credentials_dir = credentials_dir
  26. self.scopes = scopes
  27. self._service = None
  28. self._service_settime = None
  29. self.version = version
  30. def get_credentials(self):
  31. credential_path = os.path.join(self.credentials_dir, "token.json")
  32. store = Storage(credential_path)
  33. credentials = store.get()
  34. if not credentials or credentials.invalid:
  35. flow = client.flow_from_clientsecrets(self.client_secret_file, self.scopes)
  36. flow.user_agent = self.app_name
  37. if flags:
  38. credentials = tools.run_flow(flow, store, flags)
  39. else:
  40. credentials = tools.run(flow, store)
  41. print("Storing credentials to " + credential_path)
  42. return credentials
  43. def build_service(self):
  44. credentials = self.get_credentials()
  45. http = credentials.authorize(httplib2.Http())
  46. service = build(
  47. self.service_name, self.version, http=http, cache_discovery=False
  48. )
  49. return service
  50. def _needs_renewal(self):
  51. now = datetime.datetime.today()
  52. if self._service_settime:
  53. return (now - self._service_settime) > HOUR
  54. else:
  55. return True
  56. @property
  57. def service(self):
  58. if self._needs_renewal():
  59. service = self.build_service()
  60. self._service = service
  61. self._service_settime = datetime.datetime.today()
  62. return service
  63. else:
  64. return self._service