Sincronizando as alterações na videoconferência do Agenda

Os usuários podem atualizar ou excluir livremente eventos do Google Agenda. Se um usuário atualizar um evento após a criação de uma videoconferência, talvez seu complemento precise responder à alteração atualizando os dados da videoconferência. Se o sistema de videoconferência de terceiros depender do controle dos dados do evento, não atualizar a videoconferência em relação a uma mudança poderá tornar a videoconferência inutilizável e resultar em uma experiência insatisfatória para o usuário.

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

O procedimento geral de sincronização é o seguinte:

  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 gatilho executa uma função de gatilho no projeto de 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 solicitações de API de terceiros.
  5. Um novo token de sincronização é armazenado para que a próxima execução do acionador 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 vai precisar criar um gatilho instalável que responda a alterações de eventos na agenda, se o acionador ainda não existir.

Depois de criar o acionador, a inicialização precisa terminar com a criação do token de sincronização inicial. Para isso, execute a função de gatilho diretamente.

Criar um gatilho do Agenda

Para sincronizar, seu complemento precisa detectar quando um evento do Google Agenda que tem uma conferência anexada muda. Isso é feito criando um gatilho instalável EventUpdated. Seu complemento precisa apenas de um gatilho para cada agenda e pode criá-lo de maneira programática.

Um bom momento para criar um acionador é quando o usuário cria a primeira videoconferência, já que ele está começando a usar o complemento. Depois de criar uma conferência e verificar que não há erro, seu complemento deverá verificar se o acionador existe para esse usuário e, caso contrário, criá-lo.

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

As funções de acionamento são executadas quando o Apps Script detecta uma condição que faz com que um acionador seja disparado. Os acionadores EventUpdated do 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 de Calendar.Events.list() para o 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 do acionador é executada sem um token de sincronização válido, ela recua em uma sincronização completa. As sincronizações completas tentam recuperar todos os eventos em uma janela de tempo predeterminada para gerar um novo token de sincronização válido.

  2. Cada evento modificado é examinado para determinar se tem uma videoconferê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ária uma modificação da videoconferência associada. Por exemplo, se um evento foi excluído, o complemento provavelmente deve excluir a videoconferência também.
  4. Todas as alterações necessárias na videoconferência são feitas fazendo 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(). O token de sincronização pode ser encontrado na última página de resultados retornados pela chamada Calendar.Events.list().

Atualizar 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ê optar por fazer isso, faça a atualização do 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 impede 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 as 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.

  }
}