]> njoseph.me Git - nimcoon.git/blob - src/youtube.nim
update TODO list
[nimcoon.git] / src / youtube.nim
1 import
2 httpClient,
3 json,
4 std/[terminal],
5 strformat,
6 strutils,
7 uri
8
9 import
10 config,
11 types
12
13
14 discard """
15
16 Invidious API reference:
17 https://github.com/iv-org/documentation/blob/master/API.md
18 """
19
20 func makeUrl(videoId: string): string =
21 "https://www.youtube.com/watch?v=" & videoId
22
23
24 proc getSearchResults*(searchQuery: string): SearchResults =
25 # Using Invidious API to retrieve the search results but playing the results directly from YouTube.
26 let queryParam = encodeUrl(searchQuery)
27 let client = newHttpClient()
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"})
29 let response = get(client, &"{invidiousInstance}/api/v1/search?q={queryParam}")
30 let jsonData = parseJson($response.body)
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)
37 var searchResults: SearchResults = @[]
38 for item in jsonData:
39 if item["type"].getStr() == "video":
40 searchResults.add((item["title"].getStr(), makeUrl(item["videoId"].getStr())))
41 elif item["type"].getStr() == "playlist":
42 searchResults.add((item["title"].getStr(), makeUrl(item["playlistId"].getStr())))
43 # Not handling type = channel for now
44 searchResults
45
46 proc 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()))