import * as wmill from "windmill-client"
import { S3Object } from "windmill-client"
const graph = "https://graph.microsoft.com/v1.0"
function driveUrl(drive_id: string | undefined) {
return drive_id != null && drive_id !== ""
? `${graph}/drives/${encodeURIComponent(drive_id)}`
: `${graph}/me/drive`
}
// An item is addressed by its id, or by a path from the drive root starting with "/"
function ref(item: string | undefined) {
if (item == null || item === "" || item === "/") return "root"
if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}`
const path = item
.replace(/\/+$/, "")
.split("/")
.map(encodeURIComponent)
.join("/")
return `root:${path}:`
}
/**
* Download File
* Download a file in your OneDrive, or in another drive when `drive_id` is set to Windmill object storage and return its S3 reference. `item` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). `convert_to_pdf` converts Office documents (docx, xlsx, pptx and others) to PDF on the way out. Requires Files.Read (covered by the default Files.ReadWrite); a drive that is not your own needs Files.Read.All.
*/
export async function main(
auth: RT.MsOnedrive,
item: string,
destination: S3Object,
convert_to_pdf: boolean = false,
drive_id: string | undefined
) {
const drive = driveUrl(drive_id)
const url = new URL(`${drive}/${ref(item)}/content`)
if (convert_to_pdf) url.searchParams.append("format", "pdf")
// Graph answers 302 to a pre-authenticated download URL, which fetch follows
const response = await fetch(url, {
headers: { Authorization: `Bearer ${auth.token}` },
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
await wmill.writeS3File(
destination,
response.body as ReadableStream<Uint8Array>
)
return destination
}
Submitted by hugo989 5 hours ago