Edits history of script submission #23546 for ' New or Updated File (ms_sharepoint)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    import * as wmill 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}:`
    }
    
    /**
     * New or Updated File
     * Emits the files or folders created (or, with `events`, also modified; a folder counts as modified when something inside it changes) in a site's default document library, or in another of its libraries when `drive_id` is set since the last poll, optionally only under one `folder` path (e.g. `/Reports`). The first run records the drive's current state and emits nothing. Polls the drive's delta feed because Microsoft Graph push needs a change-notification subscription renewed every few weeks against a public endpoint, which belongs in a Windmill native trigger; run this as a Scheduled Poll until then. Requires Sites.Read.All (covered by the default Sites.ReadWrite.All).
     */
    export async function main(
      auth: RT.MsSharepoint,
      site_id: DynSelect_site_id,
      events: "created" | "created_or_updated" = "created",
      kind: "files" | "folders" | "all" = "files",
      folder: string | undefined,
      drive_id: DynSelect_drive_id | undefined
    ) {
      const drive = driveUrl(site_id, drive_id)
      const state: { delta_link: string; since: string } | undefined =
        await wmill.getState()
      // Taken before the request so an item created while paging is not skipped next run
      const now = new Date().toISOString()
      const latest = `${drive}/root/delta?token=latest`
    
      // The feed can repeat an item: the last occurrence wins
      const items = new Map<string, { [key: string]: any }>()
      let deltaLink: string | undefined
      let expired = false
      let next: string | undefined = state?.delta_link ?? latest
      while (next) {
        const response = await fetch(next, {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        })
        // 410 Gone: the stored delta link is too old, so start over from the current state
        if (response.status === 410 && !expired) {
          expired = true
          items.clear()
          next = latest
          continue
        }
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
        const page = (await response.json()) as {
          value: { [key: string]: any }[]
          "@odata.nextLink"?: string
          "@odata.deltaLink"?: string
        }
        for (const item of page.value) items.set(item.id, item)
        next = page["@odata.nextLink"]
        deltaLink = page["@odata.deltaLink"] ?? deltaLink
      }
      await wmill.setState({ delta_link: deltaLink, since: now })
    
      // First run (or an expired link): only record where the feed stands
      if (!state?.delta_link || expired) return []
    
      let under = ""
      let underId: string | undefined
      if (folder != null && folder !== "" && folder !== "/") {
        under = folder.replace(/\/+$/, "")
        const response = await fetch(`${drive}/${ref(under)}?$select=id`, {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        })
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
        underId = ((await response.json()) as { id: string }).id
      }
    
      return [...items.values()].filter((item) => {
        if (item.deleted || item.root) return false
        if (kind === "files" && !item.file) return false
        if (kind === "folders" && !item.folder) return false
        if (
          events === "created" &&
          Date.parse(item.createdDateTime) < Date.parse(state.since)
        ) {
          return false
        }
        if (under === "") return true
        // parentReference.path looks like /drive/root:/Reports/2026, but the feed
        // may leave it out: direct children are then still matched by parent id
        const parent = decodeURIComponent(item.parentReference?.path ?? "").split(
          "root:"
        )[1]
        return (
          item.parentReference?.id === underId ||
          parent === under ||
          (parent ?? "").startsWith(under + "/")
        )
      })
    }
    

    Submitted by hugo989 5 hours ago