import htmlparser
import httpClient
import os
import osproc
import sequtils, sugar
import std/[terminal]
import strtabs
import strutils
import uri
import xmltree
# Supported video players in order of preference
let supportedPlayers = @["mpv", "mplayer", "vlc"]
# Only show these many results
let limit = 10
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
raise newException(OSError, "No supported media player found")
else:
return availablePlayers[0]
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/clitube-page.html", response.body)
return "/tmp/clitube-page.html"
proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
loadHtml(htmlFile).findAll("a").
filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
proc presentVideoOptions(searchResults: seq[SearchResult]) =
echo ""
for index, (title, url) in searchResults:
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
# Play the video using the preferred/available media player
discard execProcess(player & " " & searchResults[number].url)