]> njoseph.me Git - nimcoon.git/blame - src/youtube.nim
youtube: Use a different Invidious instance
[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()
28 let response = get(client, &"{invidiousInstance}/api/v1/search?q={queryParam}")
29 let jsonData = parseJson($response.body)
fc3b0d35
JN
30 if jsonData.kind == JObject: # Could be a 403 error
31 stdout.styledWrite(fgRed, $response.body)
32 quit(1)
33 if len(jsonData) == 0:
34 stdout.styledWrite(fgRed, "Got empty response from Invidious instance")
35 quit(2)
e08e5cbe 36 var searchResults: SearchResults = @[]
a2d28598
JN
37 for item in jsonData:
38 if item["type"].getStr() == "video":
5f9cdfef 39 searchResults.add((item["title"].getStr(), makeUrl(item["videoId"].getStr())))
a2d28598 40 elif item["type"].getStr() == "playlist":
5f9cdfef 41 searchResults.add((item["title"].getStr(), makeUrl(item["playlistId"].getStr())))
a2d28598 42 # Not handling type = channel for now
e08e5cbe 43 searchResults
5f9cdfef
JN
44
45proc getAutoPlayVideo*(searchResult: SearchResult): SearchResult =
46 # Take a search result and fetch its first recommendation
47 let videoId = searchResult.url.split("=")[1]
48 let client = newHttpClient()
49 let response = get(client, &"{invidiousInstance}/api/v1/videos/{videoId}")
50 let jsonData = parseJson($response.body)
51 let firstRecommendation = jsonData["recommendedVideos"][0]
52 (firstRecommendation["title"].getStr(), makeUrl(firstRecommendation["videoId"].getStr()))