gcal.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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/projet-wdm-gcal.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, 'projet-wdm-gcal.json')
  34. store = oauth2client.file.Storage(credential_path)
  35. credentials = store.get()
  36. if not credentials or credentials.invalid:
  37. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  38. flow.user_agent = APPLICATION_NAME
  39. if flags:
  40. credentials = tools.run_flow(flow, store, flags)
  41. else: # Needed only for compatibility with Python 2.6
  42. credentials = tools.run(flow, store)
  43. print('Storing credentials to ' + credential_path)
  44. return credentials
  45. def find_list_event_gcal(events):
  46. list_event = []
  47. if not events:
  48. print('No upcoming events found.')
  49. return list_event
  50. for event in events:
  51. if 'dateTime' in event['start']:
  52. # replace last ':' by ''
  53. start = event['start']['dateTime']
  54. start = start.rsplit(':', 1)
  55. start = "".join(start)
  56. date = datetime.strptime(start, '%Y-%m-%dT%H:%M:%S%z')
  57. else:
  58. # TODO strptime, quel est le format dans ce cas ?
  59. date = event['start']['date']
  60. date = date.replace(tzinfo = None)
  61. location = event.get('location', b'')
  62. if (not isinstance(location,str)):
  63. location = location.decode()
  64. description = event.get('description', 'no description')
  65. if (not isinstance(description,str)):
  66. description = description.decode()
  67. list_event.append(Event('gcal_' + event['id'], date, location, description))
  68. return list_event
  69. def get_list_event_gcal():
  70. """Shows basic usage of the Google Calendar API.
  71. Creates a Google Calendar API service object and outputs a list of the next
  72. 10 events on the user's calendar.
  73. """
  74. credentials = get_credentials()
  75. http = credentials.authorize(httplib2.Http())
  76. service = discovery.build('calendar', 'v3', http=http)
  77. now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
  78. print('Getting the upcoming 10 events from Google Calendar...')
  79. eventsResult = service.events().list(
  80. calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
  81. orderBy='startTime').execute()
  82. events = eventsResult.get('items', [])
  83. return find_list_event_gcal(events)