]> njoseph.me Git - nimcoon.git/blobdiff - src/youtube.nim
YouTube auto-play
[nimcoon.git] / src / youtube.nim
index 3457062f8bf7eeddab312e01e8ec182612f3d2fb..a83e23372fb21b6e66822648812bf60ef062aacf 100644 (file)
@@ -2,6 +2,7 @@ import
   httpClient,
   json,
   strformat,
+  strutils,
   uri
 
 import
@@ -10,13 +11,17 @@ import
 
 
 discard """
-Using Invidious API to retrieve the search results but playing the results directly from YouTube.
 
-API reference:
-https://github.com/iv-org/documentation/blob/master/API.md#get-apiv1search
+Invidious API reference:
+https://github.com/iv-org/documentation/blob/master/API.md
 """
 
+func makeUrl(videoId: string): string =
+  "https://www.youtube.com/watch?v=" & videoId
+
+
 proc getSearchResults*(searchQuery: string): SearchResults =
+  # Using Invidious API to retrieve the search results but playing the results directly from YouTube.
   let queryParam = encodeUrl(searchQuery)
   let client = newHttpClient()
   let response = get(client, &"{invidiousInstance}/api/v1/search?q={queryParam}")
@@ -24,8 +29,17 @@ proc getSearchResults*(searchQuery: string): SearchResults =
   var searchResults: SearchResults = @[]
   for item in jsonData:
     if item["type"].getStr() == "video":
-      searchResults.add((item["title"].getStr(), "https://www.youtube.com/watch?v=" & item["videoId"].getStr()))
+      searchResults.add((item["title"].getStr(), makeUrl(item["videoId"].getStr())))
     elif item["type"].getStr() == "playlist":
-      searchResults.add((item["title"].getStr(), "https://www.youtube.com/watch?v=" & item["playlistId"].getStr()))
+      searchResults.add((item["title"].getStr(), makeUrl(item["playlistId"].getStr())))
     # Not handling type = channel for now
   searchResults
+
+proc getAutoPlayVideo*(searchResult: SearchResult): SearchResult =
+  # Take a search result and fetch its first recommendation
+  let videoId = searchResult.url.split("=")[1]
+  let client = newHttpClient()
+  let response = get(client, &"{invidiousInstance}/api/v1/videos/{videoId}")
+  let jsonData = parseJson($response.body)
+  let firstRecommendation = jsonData["recommendedVideos"][0]
+  (firstRecommendation["title"].getStr(), makeUrl(firstRecommendation["videoId"].getStr()))