0

Download Media

by
Published today

Download an uploaded or received media item to Windmill object storage and return its S3 reference.

Script whatsapp_business Verified

The script

Submitted by hugo989 Bun
Verified 5 hours ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3

4
/**
5
 * Download Media
6
 * Download an uploaded or received media item to Windmill object storage and return its S3 reference.
7
 */
8
export async function main(
9
  auth: RT.WhatsappBusiness,
10
  media_id: string,
11
  destination: S3Object
12
) {
13
  const apiVersion = auth.api_version || "v25.0"
14
  const metaUrl = new URL(
15
    `https://graph.facebook.com/${apiVersion}/${media_id}`
16
  )
17
  metaUrl.searchParams.append("phone_number_id", auth.phone_number_id)
18

19
  const metaResponse = await fetch(metaUrl, {
20
    headers: {
21
      Authorization: `Bearer ${auth.token}`,
22
      Accept: "application/json",
23
    },
24
  })
25
  if (!metaResponse.ok) {
26
    throw new Error(`${metaResponse.status} ${await metaResponse.text()}`)
27
  }
28
  const { url } = (await metaResponse.json()) as { url: string }
29

30
  const response = await fetch(url, {
31
    headers: {
32
      Authorization: `Bearer ${auth.token}`,
33
    },
34
  })
35
  if (!response.ok) {
36
    throw new Error(`${response.status} ${await response.text()}`)
37
  }
38

39
  await wmill.writeS3File(
40
    destination,
41
    response.body as ReadableStream<Uint8Array>
42
  )
43
  return destination
44
}
45