0

Download File

by
Published today

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.

Script ms_onedrive Verified

The script

Submitted by hugo989 Bun
Verified 5 hours ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3

4
const graph = "https://graph.microsoft.com/v1.0"
5

6
function driveUrl(drive_id: string | undefined) {
7
  return drive_id != null && drive_id !== ""
8
    ? `${graph}/drives/${encodeURIComponent(drive_id)}`
9
    : `${graph}/me/drive`
10
}
11

12
// An item is addressed by its id, or by a path from the drive root starting with "/"
13
function ref(item: string | undefined) {
14
  if (item == null || item === "" || item === "/") return "root"
15
  if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}`
16
  const path = item
17
    .replace(/\/+$/, "")
18
    .split("/")
19
    .map(encodeURIComponent)
20
    .join("/")
21
  return `root:${path}:`
22
}
23

24
/**
25
 * Download File
26
 * 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.
27
 */
28
export async function main(
29
  auth: RT.MsOnedrive,
30

31
  item: string,
32
  destination: S3Object,
33
  convert_to_pdf: boolean = false,
34
  drive_id: string | undefined
35
) {
36
  const drive = driveUrl(drive_id)
37
  const url = new URL(`${drive}/${ref(item)}/content`)
38
  if (convert_to_pdf) url.searchParams.append("format", "pdf")
39

40
  // Graph answers 302 to a pre-authenticated download URL, which fetch follows
41
  const response = await fetch(url, {
42
    headers: { Authorization: `Bearer ${auth.token}` },
43
  })
44

45
  if (!response.ok) {
46
    throw new Error(`${response.status} ${await response.text()}`)
47
  }
48

49
  await wmill.writeS3File(
50
    destination,
51
    response.body as ReadableStream<Uint8Array>
52
  )
53
  return destination
54
}
55