Upload captions or subtitles

Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. One caption or subtitle file per language is allowed.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Upload captions or subtitles
8
 * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. One caption or subtitle file per language is allowed.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  language: string,
13
  identifier: string,
14
  account_identifier: string,
15
  body: { file: string; [k: string]: unknown }
16
) {
17
  const url = new URL(
18
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/stream/${identifier}/captions/${language}`
19
  );
20

21
  const formData = new FormData();
22
  for (const [k, v] of Object.entries(body)) {
23
    if (v !== undefined && v !== "") {
24
      formData.append(k, String(v));
25
    }
26
  }
27
  const response = await fetch(url, {
28
    method: "PUT",
29
    headers: {
30
      "X-AUTH-EMAIL": auth.email,
31
      "X-AUTH-KEY": auth.key,
32
      Authorization: "Bearer " + auth.token,
33
    },
34
    body: formData,
35
  });
36
  if (!response.ok) {
37
    const text = await response.text();
38
    throw new Error(`${response.status} ${text}`);
39
  }
40
  return await response.json();
41
}
42