--- /dev/null
+import
+ httpClient,
+ json,
+ strformat,
+ strutils,
+ sequtils,
+ uri
+
+import types
+
+proc getYouTubePage(searchQuery: string): string =
+ let queryParam = encodeUrl(searchQuery)
+ let client = newHttpClient()
+ let response = get(client, &"https://www.youtube.com/results?search_query={queryParam}")
+ $response.body
+
+
+proc getSearchResults*(searchQuery: string): SearchResults =
+ let html = getYouTubePage(searchQuery)
+ let lines = html.split('\n').filterIt(it.contains("ytInitialData"))
+ let line = lines[0]
+ let jsonString = line.split('=', maxsplit=1)[1].strip().strip(chars={';'})
+ let jsonData = parseJson(jsonString)
+
+ let videos = jsonData["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"]
+
+ var searchResults: SearchResults = @[]
+
+ for video in videos:
+ if video.hasKey("videoRenderer"):
+ let title = ($video["videoRenderer"]["title"]["runs"][0]["text"]).strip(chars={'"'})
+ let videoId = ($video["videoRenderer"]["videoId"]).strip(chars={'"'})
+ let videoUrl = &"https://www.youtube.com/watch?v={videoId}"
+ searchResults.add((title, videoUrl))
+
+ elif video.hasKey("playlistRenderer"):
+ let title = ($video["playlistRenderer"]["title"]["simpleText"]).strip(chars={'"'})
+ let playlistId = ($video["playlistRenderer"]["playlistId"]).strip(chars={'"'})
+ let playlistUrl = &"https://www.youtube.com/playlist?list={playlistId}"
+ searchResults.add((title, playlistUrl))
+
+ searchResults