使用Google Calendar API提取即将举办的活动

时间:2015-11-29 16:30:11

标签: javascript calendar

我需要按照日期顺序从Google日历中提取前三个即将发生的事件,以便使用我正在制作的新应用(Pebble表盘)。

我已经使用Google Developers上的JavaScript快速入门创建了一个html页面来提取我需要的信息。代码如下: -

<html>
  <head>
    <script type="text/javascript">
      // Your Client ID can be retrieved from your project in the Google
      // Developer Console, https://console.developers.google.com
      var CLIENT_ID = 'CLIENT_ID_HERE';

      // This quickstart only requires read-only scope, check
      // https://developers.google.com/google-apps/calendar/auth if you want to
      // request write scope.
      var SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];

      /**
       * Check if current user has authorized this application.
       */
      function checkAuth() {
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES,
            'immediate': true
          }, handleAuthResult);
      }

      /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load Calendar client library.
          authorizeDiv.style.display = 'none';
          loadCalendarApi();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
        }
      }

      /**
       * Initiate auth flow in response to user clicking authorize button.
       *
       * @param {Event} event Button click event.
       */
      function handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      /**
       * Load Google Calendar client library. List upcoming events
       * once client library is loaded.
       */
      function loadCalendarApi() {
        gapi.client.load('calendar', 'v3', listCalendars);
      }

      /**
       * List all calendars and call listUpcomingEvents on each 
       * calendarID.
       */
      function listCalendars() 
      {
        var request = gapi.client.calendar.calendarList.list();

        request.execute(function(resp) {
          var calendars = resp.items;
          appendPre('Check Console');
          for (i=0;i<calendars.length;i++)
          {
            listUpcomingEvents(calendars[i]['id']);
          }
        });
      }

      /**
       * Print the summary and start datetime/date of the next ten events in
       * the authorized user's calendar. If no events are found an
       * appropriate message is printed.
       */
       function listUpcomingEvents(calendarID)
       {
            var calendarId = calendarID;
            var request_events = gapi.client.calendar.events.list({
              'calendarId': calendarId,
              'timeMin': (new Date()).toISOString(),
              'singleEvents': true,
              'showDeleted': false,
              'maxResults': 3,
              'orderBy': 'startTime'
            });

            request_events.execute(function(resp) {
                var events = resp.items;

                for (i = 0; i < events.length; i++) 
                {
                  var event = events[i];
                  var when = event.start.dateTime;
                  if (!when) {
                    when = event.start.date;
                  }
                  appendPre(event.summary + ' (' + when + ')');
                }
            })
       }

      /**
       * Append a pre element to the body containing the given message
       * as its text node.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to calendar</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

它在一定程度上起作用;但是,如果您有权访问多个日历,则会出现问题。它不是仅根据日期返回从任何日历中获取的三个事件,而是从每个日历中返回三个,因此如果您有5个日历,则会得到15个结果,所有结果都按日历分组,而不是按日期排序。

因此,如果有人能帮助解决以下问题,我将不胜感激: -

  1. 如何修复代码,以便我只收到NEXT即将举办的三个活动,无论它来自哪个日历?

  2. 另外,如何让输出以标准格式显示,以便在我调用时可以识别每个元素,例如"event":( "summary": "Party", "start": "date" : 2015-11-30)我不确定它是怎么回事。< / p>

  3. 非常感谢。

0 个答案:

没有答案