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 atualiza um evento após criar uma conferência para ele, seu complemento pode precisar e responder à alteração atualizando os dados da videoconferência. Se as de videoconferência de terceiros depende do acompanhamento dos dados do evento, não atualizar a conferência devido a uma alteração no evento pode renderizá-la inutilizáveis e resultam em uma experiência ruim para o usuário.

O processo de manter os dados da videoconferência atualizados com as alterações o evento do Google Agenda é chamado de sincronização. Você pode sincronizar as alterações de eventos criar um Apps Script acionador instalável que é disparado sempre que eventos forem alterados em uma determinada agenda. Infelizmente, o gatilho não informar quais eventos foram alterados e não é possível limitá-lo apenas a eventos com conferências que você criou. Em vez disso, você deve solicitar uma lista de todas as alterações feitas em uma agenda desde a última sincronização, filtre pelos lista de eventos e faça 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 gatilho executa uma função de gatilho no seu projeto de complemento.
  3. A função de gatilho examina o conjunto de alterações de eventos desde o último a sincronização e determina se alguma requer a atualização de um fornecedor conferência.
  4. As atualizações necessárias são feitas nas videoconferências solicitações de API.
  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

Assim que o complemento criar uma videoconferência em um sistema de terceiros, ele criará um gatilho instalável. que responde mudanças em eventos nesta agenda, se o acionador ainda não existir.

Depois de criar o gatilho, a inicialização deve terminar criando o arquivo token de sincronização. Isso é feito executando a função de gatilho diretamente.

Criar um gatilho do Google Agenda

Para sincronizar, seu complemento precisa detectar quando um evento do Google Agenda com uma videoconferência for alterada. Para isso, crie um objeto EventUpdated gatilho instalável. Seu complemento precisa apenas de um acionador para cada agenda e pode criá-las de maneira programática.

Um bom momento para criar um gatilho é quando o usuário criar sua primeira conferência, porque o usuário começa a usar o complemento. Depois criar uma videoconferência e verificar se há erros, seu complemento deve verificar se o gatilho existe para este usuário e, caso não o crie.

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 causa um gatilho para disparar. EventUpdated Gatilhos do Agenda disparar quando um usuário cria, modifica ou exclui qualquer evento de uma determinada agenda.

Implemente a função de gatilho usada pelo complemento. Esta função de gatilho deve fazer o seguinte:

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

    Quando a função de gatilho é executada sem um token de sincronização válido, ela retorna em uma sincronização completa. As sincronizações completas tentam recuperar todos os eventos em um período definido para gerar uma sincronização válida com base no token correto anterior.

  2. Cada evento modificado é examinado para determinar se tem um evento conferência externa.
  3. Se um evento tiver uma conferência, ele será examinado para ver o que foi alterado. Dependendo da mudança, uma modificação da conferência associada pode necessário. Por exemplo, se um evento for excluído, o complemento deverá provavelmente também excluiria a conferê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 por o método Calendar.Events.list(). Este token de sincronização é encontrado na última página de resultados retornados pela chamada de Calendar.Events.list().

Atualizando o evento do Google Agenda

Em alguns casos, você pode querer atualizar o evento do Google Agenda ao realizar uma sincronização. Se optar por fazer isso, atualize o evento com o evento Serviço avançado do Google Agenda solicitação. Certifique-se de usar atualização condicional com um cabeçalho If-Match. Isso impede que as alterações sejam acidentalmente excesso de alterações simultâneas feitas pelo usuário em outro cliente.

Exemplo

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

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

  }
}