Beispiel #1
0
    def _event_counts(self, time, user):
        """Retrieves a daily count of events using the Google Calendar API."""

        # Create an authorized connection to the API.
        storage = GoogleCalendarStorage(user.id)
        credentials = storage.get()
        if not credentials:
            error('No valid Google Calendar credentials.')
            return Counter()
        authed_http = credentials.authorize(http=build_http())
        service = discovery.build(API_NAME, API_VERSION, http=authed_http,
                                  cache_discovery=False)

        # Process calendar events for each day of the current month.
        first_date = time.replace(day=1, hour=0, minute=0, second=0,
                                  microsecond=0)
        _, last_day = monthrange(time.year, time.month)
        last_date = first_date.replace(day=last_day)
        page_token = None
        event_counts = Counter()
        while True:
            # Request this month's events.
            request = service.events().list(calendarId=CALENDAR_ID,
                                            timeMin=first_date.isoformat(),
                                            timeMax=last_date.isoformat(),
                                            singleEvents=True,
                                            pageToken=page_token)
            try:
                response = request.execute()
            except HttpAccessTokenRefreshError as e:
                warning('Google Calendar request failed: %s' % e)
                return Counter()

            # Iterate over the events from the current page.
            for event in response['items']:
                try:
                    # Count regular events.
                    start = parse(event['start']['dateTime'])
                    end = parse(event['end']['dateTime'])
                    for day in self._days_range(start, end):
                        event_counts[day] += 1
                except KeyError:
                    pass

                try:
                    # Count all-day events.
                    start = datetime.strptime(event['start']['date'],
                                              '%Y-%m-%d')
                    end = datetime.strptime(event['end']['date'], '%Y-%m-%d')
                    for day in self._days_range(start, end):
                        event_counts[day] += 1
                except KeyError:
                    pass

            # Move to the next page or stop.
            page_token = response.get('nextPageToken')
            if not page_token:
                break

        return event_counts
Beispiel #2
0
def oauth_step2(key, scope, code):
    """Exchanges and saves the OAuth credentials."""

    # Use scope-specific token exchange and storage steps.
    if scope == GOOGLE_CALENDAR_SCOPE:
        credentials = _google_calendar_step2(key, code)
        storage = GoogleCalendarStorage(key)
        credentials.set_store(storage)
        try:
            credentials.refresh(build_http())
        except HttpAccessTokenRefreshError as e:
            storage.delete()
            error('Token refresh error: %s' % e)
    else:
        error('Unknown OAuth scope: %s' % scope)
Beispiel #3
0
def hello_get(key):
    """Responds with a form for editing user data."""

    # Look up any existing user data.
    calendar_storage = GoogleCalendarStorage(key)
    calendar_credentials = calendar_storage.get()

    # Force a Google Calendar credentials refresh to get the latest status.
    if calendar_credentials:
        try:
            calendar_credentials.refresh(build_http())
        except HttpAccessTokenRefreshError as e:
            error('Calendar token refresh error: %s' % e)
            calendar_storage.delete()
            calendar_credentials = None

    calendar_connected = calendar_credentials is not None
    return render_template(HELLO_TEMPLATE, key=key, user=Firestore().user(key),
                           calendar_connected=calendar_connected,
                           calendar_connect_url=google_calendar_step1(key),
                           calendar_disconnect_url=ACCOUNT_ACCESS_URL)