]> njoseph.me Git - nimcoon.git/blame_incremental - clitube.nim
Use std/[terminal] library for CLI colors
[nimcoon.git] / clitube.nim
... / ...
CommitLineData
1import htmlparser
2import httpClient
3import os
4import osproc
5import sequtils, sugar
6import std/[terminal]
7import strtabs
8import strutils
9import uri
10import xmltree
11
12# Supported video players in order of preference
13let supportedPlayers = @["mpv", "mplayer", "vlc"]
14
15# Only show these many results
16let limit = 10
17
18type SearchResult = tuple[title: string, url: string]
19
20proc selectMediaPlayer(): string =
21 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
22 if len(availablePlayers) == 0:
23 echo "Please install one of the supported media players: ", supportedPlayers
24 raise newException(OSError, "No supported media player found")
25 else:
26 return availablePlayers[0]
27
28proc getYoutubePage(searchQuery: string): string =
29 let queryParam = encodeUrl(searchQuery)
30 var client = newHttpClient()
31 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
32 writeFile("/tmp/clitube-page.html", response.body)
33 return "/tmp/clitube-page.html"
34
35proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
36 loadHtml(htmlFile).findAll("a").
37 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
38 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
39
40proc presentVideoOptions(searchResults: seq[SearchResult]) =
41 echo ""
42 for index, (title, url) in searchResults:
43 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
44
45let searchResults = extractTitlesAndUrls(getYoutubePage(paramStr(1)))
46
47presentVideoOptions(searchResults)
48
49stdout.styledWrite(fgYellow, "Choose video number: ")
50var number: int = parseInt(readLine(stdin))
51
52var player = selectMediaPlayer()
53styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
54
55# Play the video using the preferred/available media player
56discard execProcess(player & " " & searchResults[number].url)