Edits history of script submission #23530 for ' Download File (ms_sharepoint)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import * as wmill from "windmill-client"
    import { S3Object } from "windmill-client"
    
    const graph = "https://graph.microsoft.com/v1.0"
    
    export type DynSelect_site_id = string
    
    export async function site_id(auth: RT.MsSharepoint) {
      const response = await fetch(
        `${graph}/sites?search=*&$select=id,displayName,webUrl&$top=200`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { value } = (await response.json()) as {
        value: { id: string; displayName: string; webUrl: string }[]
      }
      return value.map((s) => ({
        value: s.id,
        label: `${s.displayName} (${s.webUrl})`,
      }))
    }
    
    export type DynSelect_drive_id = string
    
    export async function drive_id(auth: RT.MsSharepoint, site_id: string) {
      const response = await fetch(
        `${graph}/sites/${site_id}/drives?$select=id,name`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { value } = (await response.json()) as {
        value: { id: string; name: string }[]
      }
      return value.map((d) => ({ value: d.id, label: d.name }))
    }
    
    // The site's default document library, or the library given by drive_id
    function driveUrl(site_id: string, drive_id: string | undefined) {
      return drive_id != null && drive_id !== ""
        ? `${graph}/drives/${encodeURIComponent(drive_id)}`
        : `${graph}/sites/${site_id}/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 a site's default document library, or in another of its libraries 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 Sites.Read.All (covered by the default Sites.ReadWrite.All).
     */
    export async function main(
      auth: RT.MsSharepoint,
      site_id: DynSelect_site_id,
      item: string,
      destination: S3Object,
      convert_to_pdf: boolean = false,
      drive_id: DynSelect_drive_id | undefined
    ) {
      const drive = driveUrl(site_id, 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