How To Enable Google Drive File Change Notifications via Apps Script

How To Enable Google Drive File Change Notifications via Apps Script

Are you looking for a solution that notifies you right away if any important Google Drive spreadsheets are changed or accidentally deleted? The good news is that Google Drive has an Application Programming Interface (API) that makes it simple to build a watch mechanism for tracking changes in any file, whether it a document, presentation, or even a PDF. This enables you to receive immediate updates if the file’s rights or content change.

This tutorial will show you how to use the power of Google Apps Script to set up watch notifications for any file in your Google Drive.

Setup a File Watch in Google Drive:

To launch the Apps Script editor, just put “script.new” into your browser. Then, enter the following code to create a watch. The file’s unique ID and the webhook’s URL, which will be used to send alerts whenever the file is modified, are both required by this code.

const API_BASE_URL = 'https://www.googleapis.com/drive/v3';
const SUBSCRIPTION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

/**
 * Initiates a subscription to receive notifications about changes to a Google Drive file.
 *
 * @param {string} fileId - The ID of the file to be monitored for changes.
 * @param {string} webhookUrl - The URL to which notifications will be sent.
 * @returns {void}
 */
const startSubscription = (fileId, webhookUrl) => {
  try {
    // Prepare the payload for the channel subscription
    const channelPayload = {
      id: Utilities.getUuid(), // Generate a unique ID for the channel
      address: webhookUrl,
      expiration: Date.now() + SUBSCRIPTION_DURATION_MS,
      type: 'web_hook',
      token: `fileId=${fileId}&source=labnol.org`,
    };

    // Construct the API endpoint URL for initiating the subscription
    const endPoint = Utilities.formatString(`${API_BASE_URL}/files/%s/watch?supportsAllDrives=true`, fileId);

    // Invoke the Drive API to initiate the subscription
    const response = UrlFetchApp.fetch(endPoint, {
      method: 'POST',
      contentType: 'application/json',
      headers: {
        Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
      },
      payload: JSON.stringify(channelPayload), // Convert payload to JSON string
    });

    // Parse the response to extract subscription information
    const { id, resourceId } = JSON.parse(response);

    // Store subscription information in script properties
    const subscriptions = { id, resourceId, fileId, webhookUrl };
    PropertiesService.getScriptProperties().setProperty('subscriptions', JSON.stringify(subscriptions));
  } catch (error) {
    // Handle errors that may occur during subscription setup
    console.error(`Error initiating subscription: ${error.message}`);
  }
};
Initialize Drive Watch Trigger:

A file watch often lasts for about one hour. SUBSCRIPTION_DURATION_MS is used to increase this time frame to a more practical 24 hours. While a watch that lasts forever isn’t practical, we can set up a time-based trigger in Apps Script to have the watch renew itself automatically once every 24 hours.

const initializeWatchApp = () => {
  const fileId = '<<Drive File Id>>';
  const webhookUrl = 'https://<<Webhook URL>>';

  startSubscription(fileId, webhookUrl);

  ScriptApp.getProjectTriggers().forEach((trigger) => {
    ScriptApp.deleteTrigger(trigger);
  });

  ScriptApp.newTrigger('triggerRenewSubscription').timeBased().everyHours(24).create();

  // Adding the necessary Drive Scope
  const file = DriveApp.getFileById(fileId);
  console.log(`Push notifications activated for ${file.getName()}`);
};
Renew File Watch Automatically:

The channel subscriptions for receiving notifications about updates to certain Google Drive files are created and renewed by the trigger function. Instead of using the Google Drive API’s Drive’s older v2 version, it makes use of the UrlFetchApp.fetch function.Files.watch is a service.

Before establishing a new watch, active subscriptions are manually cancelled to avoid receiving duplicate notifications for the same file.

const triggerRenewSubscription = () => {
  try {
    // Retrieve subscription information from script properties
    const data = PropertiesService.getScriptProperties().getProperty('subscriptions');
    const subscriptions = JSON.parse(data);
    const { resourceId, id, fileId, webhookUrl } = subscriptions;

    // Stop the current subscription
    UrlFetchApp.fetch(`${API_BASE_URL}/channels/stop`, {
      method: 'POST',
      contentType: 'application/json',
      headers: {
        Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
      },
      payload: JSON.stringify({ id, resourceId }),
    });

    // Start a new subscription with the same details
    startSubscription(fileId, webhookUrl);

    console.log('Channel subscription renewed successfully!');
  } catch (error) {
    console.error(`Error renewing subscription: ${error.message}`);
  }
};
Handline watch notfications:

Services like webhook.site or requestbin.com may be used to test webhook alerts for file changes. In addition, you may control POST notifications from the Drive API by turning a Google Script into a web application. However, keep in mind that Drive alerts contain information in the X-Goog-Channel-ID, X-Goog-Channel-Token, and X-Goog-Resource-State headers of the request and that Apps Script is unable to read the header of an incoming web request.

You are now prepared to easily set up and manage real-time notifications for file changes in your Google Drive thanks to our detailed guide. Thanks to the strength of Google Apps Script and the Drive API, be informed and in charge!

Leave a Comment