Use stderr.writeLine to print error messages
[nimcoon.git] / clitube.nim
1 import htmlparser
2 import httpClient
3 import os
4 import osproc
5 import sequtils, sugar
6 import std/[terminal]
7 import strtabs
8 import strutils
9 import uri
10 import xmltree
11
12 # Supported video players in order of preference
13 let supportedPlayers = @["mpv", "mplayer", "vlc"]
14
15 # Only show these many results
16 let limit = 10
17
18 type SearchResult = tuple[title: string, url: string]
19
20 proc selectMediaPlayer(): string =
21 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
22 if len(availablePlayers) == 0:
23 stderr.writeLine "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
28 proc 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
35 proc 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
40 proc 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
45 let searchResults = extractTitlesAndUrls(getYoutubePage(paramStr(1)))
46
47 presentVideoOptions(searchResults)
48
49 stdout.styledWrite(fgYellow, "Choose video number: ")
50 var number: int = parseInt(readLine(stdin))
51
52 var player = selectMediaPlayer()
53 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
54
55 # Play the video using the preferred/available media player
56 discard execProcess(player & " " & searchResults[number].url)