]>
Commit | Line | Data |
---|---|---|
e08e5cbe JN |
1 | import |
2 | httpClient, | |
3 | json, | |
4 | strformat, | |
5 | strutils, | |
6 | sequtils, | |
7 | uri | |
8 | ||
9 | import types | |
10 | ||
11 | proc getYouTubePage(searchQuery: string): string = | |
12 | let queryParam = encodeUrl(searchQuery) | |
13 | let client = newHttpClient() | |
14 | let response = get(client, &"https://www.youtube.com/results?search_query={queryParam}") | |
15 | $response.body | |
16 | ||
17 | ||
18 | proc getSearchResults*(searchQuery: string): SearchResults = | |
19 | let html = getYouTubePage(searchQuery) | |
20 | let lines = html.split('\n').filterIt(it.contains("ytInitialData")) | |
21 | let line = lines[0] | |
22 | let jsonString = line.split('=', maxsplit=1)[1].strip().strip(chars={';'}) | |
23 | let jsonData = parseJson(jsonString) | |
24 | ||
25 | let videos = jsonData["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"] | |
26 | ||
27 | var searchResults: SearchResults = @[] | |
28 | ||
29 | for video in videos: | |
30 | if video.hasKey("videoRenderer"): | |
31 | let title = ($video["videoRenderer"]["title"]["runs"][0]["text"]).strip(chars={'"'}) | |
32 | let videoId = ($video["videoRenderer"]["videoId"]).strip(chars={'"'}) | |
33 | let videoUrl = &"https://www.youtube.com/watch?v={videoId}" | |
34 | searchResults.add((title, videoUrl)) | |
35 | ||
36 | elif video.hasKey("playlistRenderer"): | |
37 | let title = ($video["playlistRenderer"]["title"]["simpleText"]).strip(chars={'"'}) | |
38 | let playlistId = ($video["playlistRenderer"]["playlistId"]).strip(chars={'"'}) | |
39 | let playlistUrl = &"https://www.youtube.com/playlist?list={playlistId}" | |
40 | searchResults.add((title, playlistUrl)) | |
41 | ||
42 | searchResults |