Sincronizando as alterações de conferência da agenda

Os usuários podem atualizar ou excluir os próprios eventos do Google Agenda livremente. Se um usuário atualizar um evento depois de criar uma videoconferência para ele, talvez o complemento precise responder à alteração atualizando os dados da videoconferência. Se o sistema de videoconferência de terceiros depender do acompanhamento dos dados do evento, não atualizar a videoconferência sobre uma alteração no evento poderá inutilizá-la e prejudicar a experiência do usuário.

O processo de manter os dados da videoconferência atualizados com as alterações no evento do Google Agenda é chamado de sincronização. Para sincronizar alterações de eventos, crie um acionador instalável do Apps Script que é disparado sempre que os eventos são alterados em uma determinada agenda. Infelizmente, o acionador não informa quais eventos foram alterados, e não é possível limitá-lo apenas a eventos com conferências que você criou. Em vez disso, é necessário solicitar uma lista de todas as mudanças feitas em uma agenda desde a última sincronização, filtrar a lista de eventos e fazer as atualizações necessárias.

Este é o procedimento geral de sincronização:

  1. Na primeira vez que um usuário cria uma videoconferência, o processo de sincronização é inicializado.
  2. Sempre que o usuário cria, atualiza ou exclui um dos eventos da Agenda, o acionador executa uma função de acionador no projeto do complemento.
  3. A função de gatilho examina o conjunto de alterações de eventos desde a última sincronização e determina se alguma requer a atualização de uma conferência de terceiros associada.
  4. As atualizações necessárias são feitas nas conferências por meio de solicitações de API de terceiros.
  5. Um novo token de sincronização é armazenado para que a próxima execução do acionador só precise examinar as alterações mais recentes na agenda.

Inicializar a sincronização

Depois que o complemento criar uma videoconferência em um sistema de terceiros, ele precisará criar um acionador instalável que responderá a alterações de eventos nessa agenda, se o acionador ainda não existir.

Depois de criar o gatilho, a inicialização precisa ser concluída com a criação do token de sincronização inicial. Isso é feito executando a função de gatilho diretamente.

Criar um gatilho do Google Agenda

Para fazer a sincronização, seu complemento precisa detectar quando um evento do Agenda com uma conferência anexada é alterado. Para isso, crie um gatilho instalável EventUpdated. Seu complemento precisa apenas de um acionador para cada agenda e pode criá-los de maneira programática.

Um bom momento para criar um gatilho é quando o usuário criar a primeira videoconferência, já que o usuário está começando a usar o complemento. Depois de criar uma videoconferência e verificar se há erros, seu complemento precisa verificar se o acionador existe para esse usuário e se ele não existe.

Implementar uma função de gatilho de sincronização

As funções do acionador são executadas quando o Apps Script detecta uma condição que faz com que um acionador seja disparado. Os acionadores EventUpdated da Agenda são disparados quando um usuário cria, modifica ou exclui qualquer evento em uma agenda especificada.

Implemente a função de gatilho usada pelo complemento. Essa função de gatilho precisa fazer o seguinte:

  1. Faça uma chamada Calendar.Events.list() do serviço avançado do Google Agenda usando um syncToken para recuperar uma lista de eventos que mudaram desde a última sincronização. Ao usar um token de sincronização, você reduz o número de eventos que o complemento precisa examinar.

    Quando a função de acionamento é executada sem um token de sincronização válido, ela retorna para uma sincronização completa. As sincronizações completas tentam recuperar todos os eventos em um período prescrita para gerar um novo token de sincronização válido.

  2. Cada evento modificado é examinado para determinar se há uma conferência de terceiros associada.
  3. Se um evento tiver uma conferência, ele será examinado para ver o que foi alterado. Dependendo da mudança, pode ser necessário modificar a videoconferência associada. Por exemplo, se um evento foi excluído, o complemento provavelmente excluirá também a videoconferência.
  4. Todas as alterações necessárias na conferência são feitas com chamadas de API para o sistema de terceiros.
  5. Depois de fazer todas as mudanças necessárias, armazene o nextSyncToken retornado pelo método Calendar.Events.list(). Esse token de sincronização é encontrado na última página de resultados retornados pela chamada Calendar.Events.list().

Atualizando o evento do Google Agenda

Em alguns casos, pode ser necessário atualizar o evento do Google Agenda ao realizar uma sincronização. Se você decidir fazer isso, atualize o evento com a solicitação apropriada do serviço avançado do Google Agenda. Use a atualização condicional com um cabeçalho If-Match. Isso evita que as alterações substituam acidentalmente as alterações simultâneas feitas pelo usuário em um cliente diferente.

Exemplo

O exemplo a seguir mostra como configurar a sincronização de eventos da agenda e das conferências associadas a eles.

/**
 *  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.

  }
}