import common from "../common-webhook.mjs";
import {
GOOGLE_DRIVE_NOTIFICATION_ADD,
GOOGLE_DRIVE_NOTIFICATION_CHANGE,
GOOGLE_DRIVE_NOTIFICATION_UPDATE,
} from "../../common/constants.mjs";
export default {
...common,
key: "google_drive-new-or-modified-folders",
name: "New or Modified Folders (Instant)",
description: "Emit new event when a folder is created or modified in the selected Drive",
version: "0.1.8",
type: "source",
dedupe: "unique",
hooks: {
async deploy() {
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - 30);
const timeString = daysAgo.toISOString();
const args = this.getListFilesOpts({
q: `mimeType = "application/vnd.google-apps.folder" and modifiedTime > "${timeString}" and trashed = false`,
fields: "files(id, mimeType)",
pageSize: 5,
});
const { files } = await this.googleDrive.listFilesInPage(null, args);
await this.processChanges(files);
},
...common.hooks,
},
methods: {
...common.methods,
_getLastModifiedTimeForFile(fileId) {
return this.db.get(fileId);
},
_setModifiedTimeForFile(fileId, modifiedTime) {
this.db.set(fileId, modifiedTime);
},
getUpdateTypes() {
return [
GOOGLE_DRIVE_NOTIFICATION_ADD,
GOOGLE_DRIVE_NOTIFICATION_CHANGE,
GOOGLE_DRIVE_NOTIFICATION_UPDATE,
];
},
generateMeta(data, ts) {
const {
id: fileId,
name: summary,
} = data;
return {
id: `${fileId}-${ts}`,
summary,
ts,
};
},
async getChanges(headers) {
if (!headers) {
return {
change: { },
};
}
const resourceUri = headers["x-goog-resource-uri"];
const metadata = await this.googleDrive.getFileMetadata(`${resourceUri}&fields=*`);
return {
...metadata,
change: {
state: headers["x-goog-resource-state"],
resourceURI: headers["x-goog-resource-uri"],
changed: headers["x-goog-changed"],
},
};
},
async processChanges(changedFiles, headers) {
const files = changedFiles.filter(
(file) => file.mimeType === "application/vnd.google-apps.folder",
);
for (const file of files) {
const fileInfo = await this.googleDrive.getFile(file.id);
const lastModifiedTimeForFile = this._getLastModifiedTimeForFile(file.id);
const modifiedTime = Date.parse(fileInfo.modifiedTime);
if (lastModifiedTimeForFile == modifiedTime) continue;
const changes = await this.getChanges(headers);
const eventToEmit = {
file: fileInfo,
...changes,
};
const meta = this.generateMeta(fileInfo, modifiedTime);
this.$emit(eventToEmit, meta);
this._setModifiedTimeForFile(file.id, modifiedTime);
}
},
},
};