X-Git-Url: https://njoseph.me/gitweb/nimcoon.git/blobdiff_plain/c760b5d965a7db394f2a5a2b6b03474ae1d4254f..833bfdd4c89f51e583faf39d73e89256945a139a:/clitube.nim diff --git a/clitube.nim b/clitube.nim index b6dda43..fa202d2 100644 --- a/clitube.nim +++ b/clitube.nim @@ -3,6 +3,7 @@ import httpClient import os import osproc import sequtils, sugar +import std/[terminal] import strtabs import strutils import uri @@ -14,19 +15,12 @@ let supportedPlayers = @["mpv", "mplayer", "vlc"] # Only show these many results let limit = 10 -# Hard-coded terminal colors -proc reset(): string {.procvar.} = "\e[0m" -proc bold*(s: string): string {.procvar.} = "\e[1m" & s & reset() - -proc fgMagenta*(s: string): string {.procvar.} = "\e[35m" & s & reset() -proc fgCyan*(s: string): string {.procvar.} = "\e[36m" & s & reset() - type SearchResult = tuple[title: string, url: string] proc selectMediaPlayer(): string = let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) if len(availablePlayers) == 0: - echo "Please install one of the supported media players: ", supportedPlayers + stderr.writeLine "Please install one of the supported media players: ", $supportedPlayers raise newException(OSError, "No supported media player found") else: return availablePlayers[0] @@ -35,8 +29,8 @@ proc getYoutubePage(searchQuery: string): string = let queryParam = encodeUrl(searchQuery) var client = newHttpClient() let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam) - writeFile("/tmp/cli-tube-page.html", response.body) - return "/tmp/cli-tube-page.html" + writeFile("/tmp/clitube-page.html", response.body) + return "/tmp/clitube-page.html" proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = loadHtml(htmlFile).findAll("a"). @@ -44,11 +38,19 @@ proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)] proc presentVideoOptions(searchResults: seq[SearchResult]) = - echo "\n" + echo "" for index, (title, url) in searchResults: - echo index, ". ", title.bold.fgMagenta, "\n", url.fgCyan, "\n" + styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" + +let searchResults = extractTitlesAndUrls(getYoutubePage(paramStr(1))) + +presentVideoOptions(searchResults) + +stdout.styledWrite(fgYellow, "Choose video number: ") +var number: int = parseInt(readLine(stdin)) + +var player = selectMediaPlayer() +styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title -presentVideoOptions( - extractTitlesAndUrls( - getYoutubePage( - paramStr(1)))) +# Play the video using the preferred/available media player +discard execProcess(player & " " & searchResults[number].url)