Edits history of script submission #23027 for ' Modify Labels (gmail)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynMultiselect_add_label_ids = string[]
    export type DynMultiselect_remove_label_ids = string[]
    
    async function listLabels(auth: RT.Gmail) {
      const response = await fetch(
        "https://gmail.googleapis.com/gmail/v1/users/me/labels",
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { labels } = (await response.json()) as {
        labels: { id: string; name: string }[]
      }
      return labels.map((l) => ({
        value: l.id,
        label: l.name === l.id ? l.id : `${l.name} (${l.id})`,
      }))
    }
    
    // Dropdowns of the mailbox's system and user labels.
    export async function add_label_ids(auth: RT.Gmail) {
      return listLabels(auth)
    }
    export async function remove_label_ids(auth: RT.Gmail) {
      return listLabels(auth)
    }
    
    /**
     * Modify Labels
     * Add and/or remove labels on up to 1000 messages at once. Covers archive (remove INBOX), mark read (remove UNREAD), mark unread (add UNREAD), star (add STARRED), trash (add TRASH) and applying user labels.
     */
    export async function main(
      auth: RT.Gmail,
      message_ids: string[],
      add_label_ids: DynMultiselect_add_label_ids | undefined,
      remove_label_ids: DynMultiselect_remove_label_ids | undefined
    ) {
      const response = await fetch(
        "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify",
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            ids: message_ids,
            addLabelIds: add_label_ids ?? [],
            removeLabelIds: remove_label_ids ?? [],
          }),
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      // batchModify returns an empty body on success.
      return { success: true }
    }
    

    Submitted by hugo989 4 hours ago