This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube.js
63 lines (61 loc) · 1.76 KB
/
youtube.js
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
55
56
57
58
59
60
61
62
63
/**
* @typedef {Object} Result
* @property {string} id
* @property {string} title
* @property {string} thumbnail
* @property {string} views
* @property {string} publishedAt
* @property {string} description
* @property {string} channelTitle
*
*/
/**
* Searches YouTube for a query
* @param {string} query
* @returns {Promise<Array<{Result}>}
*/
export async function searchYoutube(query) {
// This key is the hardcoded, public one used internally on youtube.com
const apiKey = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
const endpoint = `https://www.youtube.com/youtubei/v1/search?key=${apiKey}`
const response = await fetch(endpoint, {
method: 'POST',
body: JSON.stringify({
query,
// This is the magic sauce that makes it work
context: {
client: {
clientName: 'WEB',
clientVersion: '2.20201002.02.01',
},
},
}),
})
if (response.status !== 200) throw new Error(response.statusText)
const json = await response.json()
const parsed = parseYoutubeResponse(json)
return parsed
}
/**
* Parses the response from the youtube v1 search endpoint
* @param {Object} json
* @returns {Array<Result>}
*/
function parseYoutubeResponse(json) {
const items =
json.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents[0].itemSectionRenderer
.contents
return items
.filter((x) => x.videoRenderer)
.map((x) => {
return {
id: x.videoRenderer.videoId,
title: x.videoRenderer.title.runs[0].text,
thumbnail: x.videoRenderer.thumbnail.thumbnails[0].url,
views: x.videoRenderer.viewCountText.simpleText,
publishedAt: x.videoRenderer.publishedTimeText?.simpleText,
description: x.videoRenderer.descriptionSnippet?.runs[0].text,
channelTitle: x.videoRenderer.ownerText.runs[0].text,
}
})
}