]> njoseph.me Git - nimcoon.git/blob - src/youtube.nim
YouTube auto-play
[nimcoon.git] / src / youtube.nim
1 import
2 httpClient,
3 json,
4 strformat,
5 strutils,
6 uri
7
8 import
9 config,
10 types
11
12
13 discard """
14
15 Invidious API reference:
16 https://github.com/iv-org/documentation/blob/master/API.md
17 """
18
19 func makeUrl(videoId: string): string =
20 "https://www.youtube.com/watch?v=" & videoId
21
22
23 proc getSearchResults*(searchQuery: string): SearchResults =
24 # Using Invidious API to retrieve the search results but playing the results directly from YouTube.
25 let queryParam = encodeUrl(searchQuery)
26 let client = newHttpClient()
27 let response = get(client, &"{invidiousInstance}/api/v1/search?q={queryParam}")
28 let jsonData = parseJson($response.body)
29 var searchResults: SearchResults = @[]
30 for item in jsonData:
31 if item["type"].getStr() == "video":
32 searchResults.add((item["title"].getStr(), makeUrl(item["videoId"].getStr())))
33 elif item["type"].getStr() == "playlist":
34 searchResults.add((item["title"].getStr(), makeUrl(item["playlistId"].getStr())))
35 # Not handling type = channel for now
36 searchResults
37
38 proc getAutoPlayVideo*(searchResult: SearchResult): SearchResult =
39 # Take a search result and fetch its first recommendation
40 let videoId = searchResult.url.split("=")[1]
41 let client = newHttpClient()
42 let response = get(client, &"{invidiousInstance}/api/v1/videos/{videoId}")
43 let jsonData = parseJson($response.body)
44 let firstRecommendation = jsonData["recommendedVideos"][0]
45 (firstRecommendation["title"].getStr(), makeUrl(firstRecommendation["videoId"].getStr()))