在Javascript中通过Google云端硬盘API处理更改时,如何区分打开的文件和添加的文件?

fcwjkofz  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(95)

我试图从一个特定的谷歌驱动器文件夹中获取更改。
https://developers.google.com/drive/api/v3/reference/changes
当我向文件夹添加新文件时,我成功地接收到回调。但是,当我单击打开文件时,我也接收到回调,这不是预期的行为。我希望仅在添加新文件时接收回调。
为了避免在打开文件时收到通知,我使用urlArray作为解决方案。然而,这不是一个理想的解决方案。

我想知道在drive.changes.list响应中是否有方法区分打开文件和添加文件。

let token;
const folderId = "...............";

// An array to store URLs of the newly added files in the Google Drive folder
let urlArray = [];

const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

async function loadSavedCredentialsIfExist() {
  .....
}

async function saveCredentials(client) {
  .....
}

async function authorize() {
  .....
}

// Function to fetch changes in the Google Drive folder
async function fetchChanges(authClient) {
  const drive = google.drive({version: 'v3', auth: authClient});
  try {
    do {
      const res = await drive.changes.list({
        pageToken: token,
        spaces: 'drive',
        fields: '*'
      });
      if (res.data.changes.length > 0) {
        const lastChanges = res.data.changes[res.data.changes.length - 1];

        // Check if the last added file is not trashed, belongs to the specified folder, and its URL is not already in the array
        if (lastChanges.file.parents && lastChanges.file.parents[0] === folderId && !lastChanges.file.trashed && !urlArray.includes(lastChanges.fileId)) {
          urlArray.push(lastChanges.fileId);
          const imageUrl = `https://drive.google.com/uc?id=${lastChanges.fileId}`;
          console.log(imageUrl);
        }
      }
      token = res.data.newStartPageToken;
      return token;
    } while (token);
  } catch (err) {
    throw err;
  }
}

// This function sets up a channel to watch for changes to a specific Google Drive folder using a webhook.
async function watchChanges(authClient) {
  const resource = {
    kind: "api#channel",
    id: uuid(),
    type: 'webhook',
    address: 'https://myDomain/webhooks/drive',
    payload: true,
    resourceId: folderId,
    expiration: '1680969600000'
  };
  const drive = google.drive({ version: 'v3', auth: authClient });
  try {
    const res = await drive.changes.getStartPageToken({});
    token = res.data.startPageToken;

    const response = await drive.changes.watch({
      supportsAllDrives: true,
      supportsTeamDrives: true,
      pageToken: token,
      requestBody: resource
    });
    console.log(response.data);

  } catch (err) {
    throw err;
  }
}

app.get('/', function (req, res) {
  authorize().then(watchChanges).catch(console.error);
})

// Handle the post request sent by the Google Drive API when a new file is added
app.post('/webhooks/drive', function (req, res) {
  res.status(200).send('OK');
  authorize().then(fetchChanges).catch(console.error);
});

app.listen(3000)
mkshixfv

mkshixfv1#

对于google drive webhook,你可以看到X-Goog-Resource-State头文件。
触发通知的新资源状态。可能的值:同步、添加、删除、更新、回收站、取消回收站或更改。
https://developers.google.com/drive/api/guides/push

相关问题