import googleDrive from "../../google_drive.app.mjs";
import fs from "fs";
import stream from "stream";
import { promisify } from "util";
import { GOOGLE_DRIVE_MIME_TYPE_PREFIX } from "../../common/constants.mjs";
import googleWorkspaceExportFormats from "../google-workspace-export-formats.mjs";
import { toSingleLineString } from "../../common/utils.mjs";
export default {
key: "google_drive-download-file",
name: "Download File",
description: "Download a file. [See the documentation](https://developers.google.com/drive/api/v3/manage-downloads) for more information",
version: "0.1.7",
type: "action",
props: {
googleDrive,
drive: {
propDefinition: [
googleDrive,
"watchedDrive",
],
optional: true,
},
fileId: {
propDefinition: [
googleDrive,
"fileId",
(c) => ({
drive: c.drive,
}),
],
description: "The file to download",
},
filePath: {
type: "string",
label: "Destination File Path",
description: toSingleLineString(`
The destination file name or path [in the \`/tmp\`
directory](https://pipedream.com/docs/workflows/steps/code/nodejs/working-with-files/#the-tmp-directory)
(e.g., \`/tmp/myFile.csv\`)
`),
},
mimeType: {
type: "string",
label: "Conversion Format",
description: toSingleLineString(`
The format to which to convert the downloaded file if it is a [Google Workspace
document](https://developers.google.com/drive/api/v3/ref-export-formats)
`),
optional: true,
async options() {
const fileId = this.fileId;
if (!fileId) {
return googleWorkspaceExportFormats;
}
let file, exportFormats;
try {
([
file,
exportFormats,
] = await Promise.all([
this.googleDrive.getFile(fileId, {
fields: "mimeType",
}),
this.googleDrive.getExportFormats(),
]));
} catch (err) {
return googleWorkspaceExportFormats;
}
const mimeTypes = exportFormats[file.mimeType];
if (!mimeTypes) {
return [];
}
return exportFormats[file.mimeType].map((f) =>
googleWorkspaceExportFormats.find(
(format) => format.value === f,
) ?? f);
},
},
},
async run({ $ }) {
const fileMetadata = await this.googleDrive.getFile(this.fileId, {
fields: "name,mimeType",
});
const mimeType = fileMetadata.mimeType;
const isWorkspaceDocument = mimeType.includes(GOOGLE_DRIVE_MIME_TYPE_PREFIX);
if (isWorkspaceDocument && !this.mimeType) {
throw new Error("Conversion Format is required when File is a Google Workspace Document");
}
const file = isWorkspaceDocument
? await this.googleDrive.downloadWorkspaceFile(this.fileId, {
mimeType: this.mimeType,
})
: await this.googleDrive.getFile(this.fileId, {
alt: "media",
});
const pipeline = promisify(stream.pipeline);
const filePath = this.filePath.includes("tmp/")
? this.filePath
: `/tmp/${this.filePath}`;
await pipeline(file, fs.createWriteStream(filePath));
$.export("$summary", `Successfully downloaded the file, "${fileMetadata.name}"`);
return {
fileMetadata,
filePath,
};
},
};