import * as wmill from "windmill-client"
import { S3Object } from "windmill-client"
export type DynSelect_folder_id = string
// Dropdown of the account's folders (first 1000, by name).
export async function folder_id(auth: RT.Gdrive) {
const url = new URL("https://www.googleapis.com/drive/v3/files")
url.searchParams.append(
"q",
"mimeType = 'application/vnd.google-apps.folder' and trashed = false"
)
url.searchParams.append("fields", "files(id, name)")
url.searchParams.append("orderBy", "name")
url.searchParams.append("pageSize", "1000")
url.searchParams.append("supportsAllDrives", "true")
url.searchParams.append("includeItemsFromAllDrives", "true")
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${auth.token}`,
Accept: "application/json",
},
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { files } = (await response.json()) as {
files: { id: string; name: string }[]
}
return [
{ value: "root", label: "My Drive (root)" },
...files.map((f) => ({ value: f.id, label: `${f.name} (${f.id})` })),
]
}
/**
* Upload File
* Upload a file from Windmill object storage to Google Drive (any size, resumable upload). Leave the folder empty to upload to the root of My Drive. Set `convert_to` to a Google mime type (e.g. application/vnd.google-apps.document) to convert on upload.
*/
export async function main(
auth: RT.Gdrive,
file: S3Object,
name: string | undefined,
folder_id: DynSelect_folder_id | undefined,
mime_type: string | undefined,
convert_to: string | undefined
) {
const bytes = await wmill.loadS3File(file)
if (!bytes) {
throw new Error("Could not load the file from object storage")
}
const metadata: { [key: string]: any } = {
name: name || file.s3.split("/").pop(),
}
if (folder_id !== undefined && folder_id !== "")
metadata.parents = [folder_id]
if (convert_to !== undefined && convert_to !== "")
metadata.mimeType = convert_to
// 1. Open a resumable session with the metadata
const url = new URL("https://www.googleapis.com/upload/drive/v3/files")
url.searchParams.append("uploadType", "resumable")
url.searchParams.append("supportsAllDrives", "true")
const session = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${auth.token}`,
"Content-Type": "application/json; charset=UTF-8",
...(mime_type ? { "X-Upload-Content-Type": mime_type } : {}),
},
body: JSON.stringify(metadata),
})
if (!session.ok) {
throw new Error(`${session.status} ${await session.text()}`)
}
// 2. Send the bytes in a single PUT to the session URI
const response = await fetch(session.headers.get("Location")!, {
method: "PUT",
headers: {
Authorization: `Bearer ${auth.token}`,
...(mime_type ? { "Content-Type": mime_type } : {}),
},
body: bytes,
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
Submitted by hugo989 1 hour ago