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.

137 lines
4.6 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. # from __future__ import print_function
  2. from apiclient import discovery
  3. import datetime
  4. from googleapiclient.discovery import build
  5. from googleapiclient.errors import HttpError
  6. from oauth2client import client
  7. from oauth2client import tools
  8. from oauth2client.file import Storage
  9. from oauth2client.service_account import ServiceAccountCredentials
  10. import httplib2
  11. import os
  12. import pytz
  13. import sys
  14. import argparse
  15. import tzlocal
  16. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  17. dt_fmt = '%Y-%m-%dT%H:%M:%S'
  18. APPLICATION_NAME = 'Google Calendar API Python'
  19. def dateTime(datetime):
  20. if not datetime.tzinfo:
  21. datetime = datetime.astimezone()
  22. zone = tzlocal.get_localzone().zone
  23. datetime = datetime.isoformat(timespec='seconds')
  24. return {
  25. "timeZone":zone,
  26. "dateTime":datetime,
  27. }
  28. class api:
  29. def __init__(self,client_secret_file,credentials_dir,scopes = 'https://www.googleapis.com/auth/calendar'):
  30. self.client_secret_file = client_secret_file
  31. self.credentials_dir = credentials_dir
  32. self.scopes = scopes
  33. self._service = None
  34. self._service_settime = None
  35. self.calendars=self.get_calendars()
  36. self.ids = dict((calendar['summary'].lower(),calendar['id']) for calendar in self.calendars)
  37. def get_credentials(self):
  38. credential_path = os.path.join(self.credentials_dir,
  39. 'token.json')
  40. store = Storage(credential_path)
  41. credentials = store.get()
  42. if not credentials or credentials.invalid:
  43. flow = client.flow_from_clientsecrets(self.client_secret_file, self.scopes)
  44. flow.user_agent = APPLICATION_NAME
  45. if flags:
  46. credentials = tools.run_flow(flow, store, flags)
  47. else: # Needed only for compatibility with Python 2.6
  48. credentials = tools.run(flow, store)
  49. print('Storing credentials to ' + credential_path)
  50. return credentials
  51. def build_service(self):
  52. credentials = self.get_credentials()
  53. http = credentials.authorize(httplib2.Http())
  54. service = build('calendar', 'v3', http=http, cache_discovery=False)
  55. return service
  56. def _needs_renewal(self):
  57. now = datetime.datetime.today()
  58. if self._service_settime:
  59. return (now - self._service_settime) > datetime.timedelta(seconds = 60**2)
  60. else:
  61. return True
  62. # elif
  63. @property
  64. def service(self):
  65. if self._needs_renewal():
  66. service = self.build_service()
  67. self._service = service
  68. self._service_settime = datetime.datetime.today()
  69. return service
  70. else:
  71. return self._service
  72. def create_event(self, calendar_id, body):
  73. try:
  74. calendar_id = self.ids[calendar_id]
  75. except KeyError:
  76. pass
  77. service = self.service
  78. event = service.events().insert(calendarId=calendar_id, body=body).execute()
  79. return event['id']
  80. def update_event(self,calendar_id, event_id, body):
  81. try:
  82. calendar_id = self.ids[calendar_id]
  83. except KeyError:
  84. pass
  85. service = self.service
  86. try:
  87. event = service.events().get(calendarId=calendar_id, eventId=event_id).execute()
  88. except HttpError as e:
  89. if e.resp.status==404:
  90. return self.create_event(calendar_id, body)
  91. updated_event = service.events().update(calendarId=calendar_id, eventId=event['id'], body=body).execute()
  92. return updated_event["id"]
  93. def get_calendars(self):
  94. page_token = None
  95. cl = []
  96. while True:
  97. calendar_list = self.service.calendarList().list(pageToken=page_token).execute()
  98. cl += list(calendar_list_entry for calendar_list_entry in calendar_list['items'])
  99. page_token = calendar_list.get('nextPageToken')
  100. if not page_token:
  101. break
  102. return cl
  103. def get_events(self,id):
  104. service = self.service
  105. try:
  106. id = self.ids[id]
  107. except KeyError:
  108. pass
  109. page_token = None
  110. ret = []
  111. while True:
  112. events = service.events().list(calendarId=id, pageToken=page_token).execute()
  113. ret += events['items']
  114. page_token = events.get('nextPageToken')
  115. if not page_token:
  116. break
  117. return ret
  118. # if __name__ == "__main__":
  119. # test = api(r"X:\Users\Ralphie\Downloads\client_secret.json",r"X:\Users\Ralphie\Downloads")