Edits history of script submission #23034 for ' Share File (gdrive)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Share File
     * Grant access to a file or folder by creating a permission: a user or group (by email), a whole Google Workspace domain, or anyone with the link. `owner` transfers ownership (user only, same domain for Workspace accounts).
     */
    export async function main(
      auth: RT.Gdrive,
      file_id: string,
      type: "user" | "group" | "domain" | "anyone",
      role:
        "reader" | "commenter" | "writer" | "fileOrganizer" | "organizer" | "owner",
      email_address: string | undefined,
      domain: string | undefined,
      allow_file_discovery: boolean = false,
      send_notification_email: boolean = true,
      email_message: string | undefined
    ) {
      const url = new URL(
        `https://www.googleapis.com/drive/v3/files/${file_id}/permissions`
      )
      url.searchParams.append("supportsAllDrives", "true")
      if (role === "owner") url.searchParams.append("transferOwnership", "true")
      // Notification emails only apply to user and group grants.
      if (type === "user" || type === "group") {
        url.searchParams.append(
          "sendNotificationEmail",
          String(send_notification_email)
        )
        if (
          send_notification_email &&
          email_message !== undefined &&
          email_message !== ""
        )
          url.searchParams.append("emailMessage", email_message)
      }
    
      const body: { [key: string]: any } = { type, role }
      if (type === "user" || type === "group") body.emailAddress = email_address
      if (type === "domain") body.domain = domain
      if (type === "domain" || type === "anyone")
        body.allowFileDiscovery = allow_file_discovery
    
      const response = await fetch(url, {
        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()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 1 hour ago