Edits history of script submission #23524 for ' Copy File or Folder (ms_sharepoint)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    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}:`
    }
    
    async function folderId(
      token: string,
      drive: string,
      folder: string
    ): Promise<string> {
      if (!folder.startsWith("/")) return folder
      const response = await fetch(`${drive}/${ref(folder)}?$select=id`, {
        headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      return ((await response.json()) as { id: string }).id
    }
    
    /**
     * Copy File or Folder
     * Copy a file or folder into another folder, optionally under a new name and into another drive (`destination_drive_id`). `item` and `destination_folder` are each an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). Graph copies asynchronously: with `wait` the script polls for up to a minute, returns the final status with the new item's `resourceId` and fails if the copy failed (e.g. a name clash), otherwise it returns the `monitor_url` right away. Requires Sites.ReadWrite.All (a connection default).
     */
    export async function main(
      auth: RT.MsSharepoint,
      site_id: DynSelect_site_id,
      item: string,
      destination_folder: string | undefined,
      new_name: string | undefined,
      destination_drive_id: string | undefined,
      wait: boolean = true,
      drive_id: DynSelect_drive_id | undefined
    ) {
      const drive = driveUrl(site_id, drive_id)
      const body: { [key: string]: any } = {}
      if (new_name != null && new_name !== "") body.name = new_name
      const otherDrive = destination_drive_id != null && destination_drive_id !== ""
      if (otherDrive || (destination_folder != null && destination_folder !== "")) {
        const destinationDrive = otherDrive
          ? `${graph}/drives/${encodeURIComponent(destination_drive_id!)}`
          : drive
        body.parentReference = {
          id: await folderId(
            auth.token,
            destinationDrive,
            destination_folder || "/"
          ),
        }
        if (otherDrive) body.parentReference.driveId = destination_drive_id
      }
    
      const response = await fetch(`${drive}/${ref(item)}/copy`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(body),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      // 202 Accepted with an empty body; Location is a pre-authenticated monitor URL
      const monitor_url = response.headers.get("Location")
      if (!wait || !monitor_url) return { monitor_url }
    
      let status: { [key: string]: any } = {}
      for (let i = 0; i < 30; i++) {
        const poll = await fetch(monitor_url, { redirect: "manual" })
        // A finished copy may instead redirect to the new item
        if (poll.status >= 300 && poll.status < 400) {
          const resourceId = poll.headers
            .get("Location")
            ?.match(/\/items\/([^/?#:]+)/)?.[1]
          return { status: "completed", resourceId, monitor_url }
        }
        if (!poll.ok) throw new Error(`${poll.status} ${await poll.text()}`)
        status = await poll.json()
        if (status.status === "failed") throw new Error(JSON.stringify(status))
        if (status.status === "completed") break
        await new Promise((resolve) => setTimeout(resolve, 2000))
      }
      return { ...status, monitor_url }
    }
    

    Submitted by hugo989 5 hours ago