]> njoseph.me Git - nimcoon.git/blame - src/youtube.nim
update TODO list
[nimcoon.git] / src / youtube.nim
CommitLineData
e08e5cbe
JN
1import
2 httpClient,
3 json,
fc3b0d35 4 std/[terminal],
e08e5cbe 5 strformat,
5f9cdfef 6 strutils,
e08e5cbe
JN
7 uri
8
a2d28598
JN
9import
10 config,
11 types
e08e5cbe
JN
12
13
a2d28598 14discard """
e08e5cbe 15
5f9cdfef
JN
16Invidious API reference:
17https://github.com/iv-org/documentation/blob/master/API.md
a2d28598 18"""
e08e5cbe 19
5f9cdfef
JN
20func makeUrl(videoId: string): string =
21 "https://www.youtube.com/watch?v=" & videoId
22
23
a2d28598 24proc getSearchResults*(searchQuery: string): SearchResults =
5f9cdfef 25 # Using Invidious API to retrieve the search results but playing the results directly from YouTube.
a2d28598
JN
26 let queryParam = encodeUrl(searchQuery)
27 let client = newHttpClient()
eacdf44b 28 client.headers = newHttpHeaders({"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"})
a2d28598
JN
29 let response = get(client, &"{invidiousInstance}/api/v1/search?q={queryParam}")
30 let jsonData = parseJson($response.body)
fc3b0d35
JN
31 if jsonData.kind == JObject: # Could be a 403 error
32 stdout.styledWrite(fgRed, $response.body)
33 quit(1)
34 if len(jsonData) == 0:
35 stdout.styledWrite(fgRed, "Got empty response from Invidious instance")
36 quit(2)
e08e5cbe 37 var searchResults: SearchResults = @[]
a2d28598
JN
38 for item in jsonData:
39 if item["type"].getStr() == "video":
5f9cdfef 40 searchResults.add((item["title"].getStr(), makeUrl(item["videoId"].getStr())))
a2d28598 41 elif item["type"].getStr() == "playlist":
5f9cdfef 42 searchResults.add((item["title"].getStr(), makeUrl(item["playlistId"].getStr())))
a2d28598 43 # Not handling type = channel for now
e08e5cbe 44 searchResults
5f9cdfef
JN
45
46proc getAutoPlayVideo*(searchResult: SearchResult): SearchResult =
47 # Take a search result and fetch its first recommendation
48 let videoId = searchResult.url.split("=")[1]
49 let client = newHttpClient()
50 let response = get(client, &"{invidiousInstance}/api/v1/videos/{videoId}")
51 let jsonData = parseJson($response.body)
52 let firstRecommendation = jsonData["recommendedVideos"][0]
53 (firstRecommendation["title"].getStr(), makeUrl(firstRecommendation["videoId"].getStr()))