Edits history of script submission #23523 for ' New or Updated File (ms_onedrive)'

  • 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"
    
    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}:`
    }
    
    /**
     * 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 your OneDrive, or in another drive 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 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,
    
      events: "created" | "created_or_updated" = "created",
      kind: "files" | "folders" | "all" = "files",
      folder: string | undefined,
      drive_id: string | undefined
    ) {
      const drive = driveUrl(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