gcal.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from __future__ import print_function
  2. import httplib2
  3. import os
  4. from apiclient import discovery
  5. import oauth2client
  6. from oauth2client import client
  7. from oauth2client import tools
  8. from event import Event
  9. from datetime import datetime
  10. import pytz
  11. utc=pytz.UTC
  12. try:
  13. import argparse
  14. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  15. except ImportError:
  16. flags = None
  17. # If modifying these scopes, delete your previously saved credentials
  18. # at ~/.credentials/calendar-python-quickstart.json
  19. SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
  20. CLIENT_SECRET_FILE = 'client_secret.json'
  21. APPLICATION_NAME = 'Google Calendar API Python'
  22. def get_credentials():
  23. """Gets valid user credentials from storage.
  24. If nothing has been stored, or if the stored credentials are invalid,
  25. the OAuth2 flow is completed to obtain the new credentials.
  26. Returns:
  27. Credentials, the obtained credential.
  28. """
  29. home_dir = os.path.expanduser('~')
  30. credential_dir = os.path.join(home_dir, '.credentials')
  31. if not os.path.exists(credential_dir):
  32. os.makedirs(credential_dir)
  33. credential_path = os.path.join(credential_dir,
  34. 'calendar-python-quickstart.json')
  35. store = oauth2client.file.Storage(credential_path)
  36. credentials = store.get()
  37. if not credentials or credentials.invalid:
  38. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  39. flow.user_agent = APPLICATION_NAME
  40. if flags:
  41. credentials = tools.run_flow(flow, store, flags)
  42. else: # Needed only for compatibility with Python 2.6
  43. credentials = tools.run(flow, store)
  44. print('Storing credentials to ' + credential_path)
  45. return credentials
  46. def find_list_event_gcal(events):
  47. list_event = []
  48. if not events:
  49. print('No upcoming events found.')
  50. return list_event
  51. for event in events:
  52. if 'dateTime' in event['start']:
  53. # replace last ':' by ''
  54. start = event['start']['dateTime']
  55. start = start.rsplit(':', 1)
  56. start = "".join(start)
  57. date = datetime.strptime(start, '%Y-%m-%dT%H:%M:%S%z')
  58. else:
  59. # TODO strptime, quel est le format dans ce cas ?
  60. date = event['start']['date']
  61. date = date.replace(tzinfo = None)
  62. location = event.get('location', b'')
  63. if (not isinstance(location,str)):
  64. location = location.decode()
  65. description = event.get('description', 'no description')
  66. if (not isinstance(description,str)):
  67. description = description.decode()
  68. list_event.append(Event('gcal_' + event['id'], date, location, description))
  69. return list_event
  70. def get_list_event_gcal():
  71. """Shows basic usage of the Google Calendar API.
  72. Creates a Google Calendar API service object and outputs a list of the next
  73. 10 events on the user's calendar.
  74. """
  75. credentials = get_credentials()
  76. http = credentials.authorize(httplib2.Http())
  77. service = discovery.build('calendar', 'v3', http=http)
  78. now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
  79. print('Getting the upcoming 10 events...')
  80. eventsResult = service.events().list(
  81. calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
  82. orderBy='startTime').execute()
  83. events = eventsResult.get('items', [])
  84. return find_list_event_gcal(events)