15 type SearchResult = tuple[title: string, url: string]
17 proc selectMediaPlayer(): string =
18 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
19 if len(availablePlayers) == 0:
20 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
21 raise newException(OSError, "No supported media player found")
23 return availablePlayers[0]
25 proc getYoutubePage(searchQuery: string): string =
26 let queryParam = encodeUrl(searchQuery)
27 let client = newHttpClient()
28 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
31 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
32 parseHtml(htmlFile).findAll("a").
33 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
34 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
36 proc presentVideoOptions(searchResults: seq[SearchResult]) =
38 for index, (title, url) in searchResults:
39 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
41 let player = selectMediaPlayer()
46 for kind, key, value in getopt():
50 of cmdShortOption, cmdLongOption:
52 of "m", "music": musicOnly = true
56 let noVideo = if musicOnly: "--no-video" else: ""
58 if "https://www.youtube.com" in searchQuery:
59 discard execProcess(&"{player} {searchQuery}")
63 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
65 presentVideoOptions(searchResults)
67 stdout.styledWrite(fgYellow, "Choose video number: ")
68 let number = parseInt(readLine(stdin))
70 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
72 # Play the video using the preferred/available media player
73 discard execProcess(&"{player} {noVideo} {searchResults[number].url}")