Edits history of script submission #23187 for ' Move File (gdrive)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_folder_id = string
    
    // Dropdown of the account's folders (first 1000, by name).
    export async function folder_id(auth: RT.Gdrive) {
      const url = new URL("https://www.googleapis.com/drive/v3/files")
      url.searchParams.append(
        "q",
        "mimeType = 'application/vnd.google-apps.folder' and trashed = false"
      )
      url.searchParams.append("fields", "files(id, name)")
      url.searchParams.append("orderBy", "name")
      url.searchParams.append("pageSize", "1000")
      url.searchParams.append("supportsAllDrives", "true")
      url.searchParams.append("includeItemsFromAllDrives", "true")
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { files } = (await response.json()) as {
        files: { id: string; name: string }[]
      }
      return [
        { value: "root", label: "My Drive (root)" },
        ...files.map((f) => ({ value: f.id, label: `${f.name} (${f.id})` })),
      ]
    }
    
    /**
     * Move File
     * Move a file or folder into another folder: the new folder is added as its parent and every current parent is removed. Works across My Drive and shared drives the account can edit.
     */
    export async function main(
      auth: RT.Gdrive,
      file_id: string,
      folder_id: DynSelect_folder_id
    ) {
      const headers = {
        Authorization: `Bearer ${auth.token}`,
        Accept: "application/json",
      }
      const fileUrl = `https://www.googleapis.com/drive/v3/files/${file_id}`
    
      const current = await fetch(
        `${fileUrl}?fields=parents&supportsAllDrives=true`,
        { headers }
      )
      if (!current.ok) {
        throw new Error(`${current.status} ${await current.text()}`)
      }
      const { parents = [] } = (await current.json()) as { parents?: string[] }
    
      const url = new URL(fileUrl)
      url.searchParams.append("addParents", folder_id)
      const remove = parents.filter((p) => p !== folder_id)
      if (remove.length > 0)
        url.searchParams.append("removeParents", remove.join(","))
      url.searchParams.append("supportsAllDrives", "true")
      url.searchParams.append("fields", "id, name, parents, webViewLink")
    
      const response = await fetch(url, {
        method: "PATCH",
        headers: { ...headers, "Content-Type": "application/json" },
        body: "{}",
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 2 hours ago