正在同步處理日曆活動變更

使用者可以隨意更新或刪除 Google 日曆活動。如果使用者在為活動建立會議後更新活動,外掛程式可能需要更新會議資料,以回應這項變更。如果第三方會議系統需要追蹤活動資料,但您未在活動變更時更新會議,會議可能會無法使用,導致使用者體驗不佳。

將會議資料與 Google 日曆活動的變更內容保持同步的程序,稱為「同步」。您可以建立 Apps Script 可安裝的觸發條件,在特定日曆中的活動變更時觸發,藉此同步處理活動變更。很抱歉,觸發條件不會回報哪些活動有變更,而且您無法將觸發條件限制為僅適用於您建立的會議活動。您必須改為要求自上次同步以來對日曆所做的所有變更清單,篩選活動清單,然後據此進行更新。

一般同步程序如下:

  1. 使用者首次建立會議時,系統會啟動同步程序。
  2. 每當使用者建立、更新或刪除日曆活動時,觸發條件就會在外掛程式專案中執行觸發函式
  3. 觸發函式會檢查上次同步處理後的一組事件變更,並判斷是否有任何變更需要更新相關聯的第三方會議。
  4. 透過第三方 API 要求,對會議進行任何必要更新。
  5. 系統會儲存新的同步權杖,因此下次執行觸發程序時,只需要檢查行事曆的最新變更。

初始化同步

外掛程式在第三方系統上成功建立會議後,應建立可安裝的觸發條件,以便回應這個日曆中的事件變更 (如果觸發條件尚不存在)。

建立觸發條件後,初始化作業應會建立初始同步權杖,方法是直接執行觸發函式。

建立日曆觸發條件

如要同步處理,外掛程式必須偵測到附加會議的日曆活動何時變更。方法是建立EventUpdated 可安裝的觸發條件。外掛程式只需要為每個日曆設定一個觸發條件,並以程式輔助方式建立。

使用者建立第一場會議時,就是建立觸發條件的好時機,因為使用者此時會開始使用外掛程式。建立會議並確認沒有錯誤後,外掛程式應檢查使用者是否有觸發條件,如果沒有,則應建立觸發條件。

實作同步觸發函式

當 Apps Script 偵測到導致觸發條件觸發的條件時,就會執行觸發函式。EventUpdated 日曆觸發條件:使用者在指定日曆中建立、修改或刪除任何活動時,系統會觸發這類條件。

您必須實作外掛程式使用的觸發函式。這個觸發函式應執行下列操作:

  1. 使用 syncToken 進行日曆進階服務 Calendar.Events.list() 呼叫,擷取自上次同步以來變更的活動清單。使用同步權杖可減少外掛程式必須檢查的事件數量。

    如果觸發函式在執行時沒有有效的同步權杖,就會退回完整同步。完整同步作業只會嘗試在指定時間範圍內擷取所有事件,以便產生新的有效同步權杖。

  2. 系統會檢查每個修改過的活動,判斷是否與第三方會議相關聯。
  3. 如果活動有會議,系統會檢查變更內容。 視變更而定,您可能需要修改相關會議。舉例來說,如果刪除活動,外掛程式可能也應一併刪除會議。
  4. 如要變更會議,請對第三方系統發出 API 呼叫。
  5. 完成所有必要變更後,請儲存 Calendar.Events.list() 方法傳回的 nextSyncToken。這個同步符記位於 Calendar.Events.list() 呼叫傳回的最後一頁結果中。

更新 Google 日曆活動

在某些情況下,您可能會想在執行同步作業時更新 Google 日曆活動。如果選擇這麼做,請使用適當的 Google 日曆進階服務要求更新活動。請務必使用條件式更新,並搭配 If-Match 標頭。這樣可避免您的變更意外覆寫使用者在其他用戶端所做的並行變更。

範例

以下範例說明如何設定日曆活動及其相關會議的同步功能。

/**
 *  Initializes syncing of conference data by creating a sync trigger and
 *  sync token if either does not exist yet.
 *
 *  @param {String} calendarId The ID of the Google Calendar.
 */
function initializeSyncing(calendarId) {
  // Create a syncing trigger if it doesn't exist yet.
  createSyncTrigger(calendarId);

  // Perform an event sync to create the initial sync token.
  syncEvents({'calendarId': calendarId});
}

/**
 *  Creates a sync trigger if it does not exist yet.
 *
 *  @param {String} calendarId The ID of the Google Calendar.
 */
function createSyncTrigger(calendarId) {
  // Check to see if the trigger already exists; if does, return.
  var allTriggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < allTriggers.length; i++) {
    var trigger = allTriggers[i];
    if (trigger.getTriggerSourceId() == calendarId) {
      return;
    }
  }

  // Trigger does not exist, so create it. The trigger calls the
  // 'syncEvents()' trigger function when it fires.
  var trigger = ScriptApp.newTrigger('syncEvents')
      .forUserCalendar(calendarId)
      .onEventUpdated()
      .create();
}

/**
 *  Sync events for the given calendar; this is the syncing trigger
 *  function. If a sync token already exists, this retrieves all events
 *  that have been modified since the last sync, then checks each to see
 *  if an associated conference needs to be updated and makes any required
 *  changes. If the sync token does not exist or is invalid, this
 *  retrieves future events modified in the last 24 hours instead. In
 *  either case, a new sync token is created and stored.
 *
 *  @param {Object} e If called by a event updated trigger, this object
 *      contains the Google Calendar ID, authorization mode, and
 *      calling trigger ID. Only the calendar ID is actually used here,
 *      however.
 */
function syncEvents(e) {
  var calendarId = e.calendarId;
  var properties = PropertiesService.getUserProperties();
  var syncToken = properties.getProperty('syncToken');

  var options;
  if (syncToken) {
    // There's an existing sync token, so configure the following event
    // retrieval request to only get events that have been modified
    // since the last sync.
    options = {
      syncToken: syncToken
    };
  } else {
    // No sync token, so configure to do a 'full' sync instead. In this
    // example only recently updated events are retrieved in a full sync.
    // A larger time window can be examined during a full sync, but this
    // slows down the script execution. Consider the trade-offs while
    // designing your add-on.
    var now = new Date();
    var yesterday = new Date();
    yesterday.setDate(now.getDate() - 1);
    options = {
      timeMin: now.toISOString(),          // Events that start after now...
      updatedMin: yesterday.toISOString(), // ...and were modified recently
      maxResults: 50,   // Max. number of results per page of responses
      orderBy: 'updated'
    }
  }

  // Examine the list of updated events since last sync (or all events
  // modified after yesterday if the sync token is missing or invalid), and
  // update any associated conferences as required.
  var events;
  var pageToken;
  do {
    try {
      options.pageToken = pageToken;
      events = Calendar.Events.list(calendarId, options);
    } catch (err) {
      // Check to see if the sync token was invalidated by the server;
      // if so, perform a full sync instead.
      if (err.message ===
            "Sync token is no longer valid, a full sync is required.") {
        properties.deleteProperty('syncToken');
        syncEvents(e);
        return;
      } else {
        throw new Error(err.message);
      }
    }

    // Read through the list of returned events looking for conferences
    // to update.
    if (events.items && events.items.length > 0) {
      for (var i = 0; i < events.items.length; i++) {
         var calEvent = events.items[i];
         // Check to see if there is a record of this event has a
         // conference that needs updating.
         if (eventHasConference(calEvent)) {
           updateConference(calEvent, calEvent.conferenceData.conferenceId);
         }
      }
    }

    pageToken = events.nextPageToken;
  } while (pageToken);

  // Record the new sync token.
  if (events.nextSyncToken) {
    properties.setProperty('syncToken', events.nextSyncToken);
  }
}

/**
 *  Returns true if the specified event has an associated conference
 *  of the type managed by this add-on; retuns false otherwise.
 *
 *  @param {Object} calEvent The Google Calendar event object, as defined by
 *      the Calendar API.
 *  @return {boolean}
 */
function eventHasConference(calEvent) {
  var name = calEvent.conferenceData.conferenceSolution.name || null;

  // This version checks if the conference data solution name matches the
  // one of the solution names used by the add-on. Alternatively you could
  // check the solution's entry point URIs or other solution-specific
  // information.
  if (name) {
    if (name === "My Web Conference" ||
        name === "My Recorded Web Conference") {
      return true;
    }
  }
  return false;
}

/**
 *  Update a conference based on new Google Calendar event information.
 *  The exact implementation of this function is highly dependant on the
 *  details of the third-party conferencing system, so only a rough outline
 *  is shown here.
 *
 *  @param {Object} calEvent The Google Calendar event object, as defined by
 *      the Calendar API.
 *  @param {String} conferenceId The ID used to identify the conference on
 *      the third-party conferencing system.
 */
function updateConference(calEvent, conferenceId) {
  // Check edge case: the event was cancelled
  if (calEvent.status === 'cancelled' || eventHasConference(calEvent)) {
    // Use the third-party API to delete the conference too.


  } else {
    // Extract any necessary information from the event object, then
    // make the appropriate third-party API requests to update the
    // conference with that information.

  }
}