Methods to Allow Push Notifications for File Adjustments in Google Drive with Apps Script

Shubham
6 Min Read

Are you in search of a technique to obtain notifications in real-time when an vital spreadsheet in your Google Drive get modified or is accidently deleted by generally? Nicely, Google Drive gives an API that will help you arrange a watch on any file in your Google Drive be it a doc, presentation or perhaps a PDF file. This implies you could obtain immediate notifications each time the content material and even permissions of that file adjustments.

This tutorial explains how one can setup watch notifications on any file in your Google Drive with the assistance of Google Apps Script.

Setup a File Watch in Google Drive

To get began, sort script.new within the browser to open the Apps Script editor and add the code beneath to create a watch. You’d want the distinctive ID of the Google Drive file and the webhook URL the place the notifications can be ship when the file will get modified.

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

/**
 * Begins a subscription for receiving notifications about adjustments to a Google Drive file.
 *
 * @param {string} fileId - The ID of the file to look at for adjustments.
 * @param {string} webhookUrl - The URL the place notifications will likely be despatched.
 * @returns {void}
 */
const startSubscription = (fileId, webhookUrl) => {
  strive {
    // Put together the payload for the channel subscription
    const channelPayload = {
      id: Utilities.getUuid(), // Generate a novel ID for the channel
      deal with: webhookUrl,
      expiration: Date.now() + SUBSCRIPTION_DURATION_MS,
      sort: 'web_hook',
      token: `fileId=${fileId}&supply=labnol.org`,
    };

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

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

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

    // Retailer subscription info in script properties
    const subscriptions = { id, resourceId, fileId, webhookUrl };
    PropertiesService.getScriptProperties().setProperty('subscriptions', JSON.stringify(subscriptions));
  } catch (error) {
    // Deal with errors that may happen throughout subscription setup
    console.error(`Error beginning subscription: ${error.message}`);
  }
};

Initialize Drive Watch Set off

By default, a file watch expires in an hour. To increase this length to 24 hours, we’ll use the SUBSCRIPTION_DURATION_MS variable. Please word that there’s no technique to arrange an indefinite watch. We’ll thus setup a time-based set off in Apps Script to robotically renew the watch each 24 hours.

const initializeWatchApp = () => {
  const fileId = '<>';
  const webhookUrl = 'https://<>';

  startSubscription(fileId, webhookUrl);

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

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

  // Used so as to add the required Drive Scope
  const file = DriveApp.getFileById(fileId);
  console.log(`Push notifications activated for ${file.getName()}`);
};

Renew File Watch Robotically

The set off capabilities manages the method of making and renewing channel subscriptions for receiving notifications about adjustments to particular information in Google Drive. It leverages UrlFetchApp.fetch technique as an alternative of the Drive.Information.watch service because the latter makes use of the older model v2 of Google Drive API.

Since we don’t need a number of notifications for a similar file, we manually cease any present subscriptions for a file earlier than including a brand new watch.

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

    // Cease the present subscription
    UrlFetchApp.fetch(`${API_BASE_URL}/channels/cease`, {
      technique: 'POST',
      contentType: 'utility/json',
      headers: {
        Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
      },
      payload: JSON.stringify({ id, resourceId }),
    });

    // Begin a brand new subscription with the identical particulars
    startSubscription(fileId, webhookUrl);

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

Handline watch notfications

You could use an internet service like webhook.website or requestbin.com to check webhook notifications for file adjustments.

Additionally it is attainable to publish a Google Script as an internet app to deal with POST notifications from the Drive API however there’s a limitation – Apps Script can’t learn the header of an incoming net require and Drive notifications embrace the information within the X-Goog-Channel-ID, X-Goog-Channel-Token and X-Goog-Useful resource-State headers of the request.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *