-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyoutube-transcript.js
More file actions
54 lines (45 loc) · 1.28 KB
/
youtube-transcript.js
File metadata and controls
54 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { YoutubeTranscript } from 'youtube-transcript';
import { decode } from 'html-entities';
const headers = {
"Content-Type": ["text/plain"],
"Access-Control-Allow-Origin": ["*"],
"Access-Control-Allow-Methods": ["POST", "OPTIONS"],
"Access-Control-Allow-Headers": ["Content-Type", "Auth-Token"]
};
export async function handle(event, _context, _cb) {
// CORS preflight
if (event.httpMethod === 'OPTIONS') {
return {
statusCode: 204,
headers
};
}
const authToken = event.headers['Auth-Token'];
if (!authToken || authToken !== process.env.AUTH_TOKEN) {
return { statusCode: 401 };
}
if (!event.body) {
return { statusCode: 400 };
}
try {
const transcript = await getTranscript(event.body);
return {
body: transcript,
headers,
statusCode: 200,
};
} catch (error) {
return {
body: `Error: ${error.message}`,
headers,
statusCode: 500,
};
}
}
export async function getTranscript(videoUrlOrId) {
const captions = await YoutubeTranscript.fetchTranscript(videoUrlOrId);
const encodedTranscript = captions.map(c => c.text).join(' ');
const onceDecodedTranscript = decode(encodedTranscript);
const twiceDecodedTranscript = decode(onceDecodedTranscript);
return twiceDecodedTranscript;
}