]>
Commit | Line | Data |
---|---|---|
1 | import htmlparser | |
2 | import httpClient | |
3 | import os | |
4 | import osproc | |
5 | import sequtils, sugar | |
6 | import strtabs | |
7 | import strutils | |
8 | import uri | |
9 | import xmltree | |
10 | ||
11 | # Supported video players in order of preference | |
12 | let supportedPlayers = @["mpv", "mplayer", "vlc"] | |
13 | ||
14 | # Hard-coded terminal colors | |
15 | proc reset(): string {.procvar.} = "\e[0m" | |
16 | proc bold*(s: string): string {.procvar.} = "\e[1m" & s & reset() | |
17 | ||
18 | proc fgMagenta*(s: string): string {.procvar.} = "\e[35m" & s & reset() | |
19 | proc fgCyan*(s: string): string {.procvar.} = "\e[36m" & s & reset() | |
20 | ||
21 | type SearchResult = tuple[title: string, url: string] | |
22 | ||
23 | proc selectMediaPlayer(): string = | |
24 | let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) | |
25 | if len(availablePlayers) == 0: | |
26 | echo "Please install one of the supported media players: ", supportedPlayers | |
27 | raise newException(OSError, "No supported media player found") | |
28 | else: | |
29 | return availablePlayers[0] | |
30 | ||
31 | proc getYoutubePage(searchQuery: string): string = | |
32 | let queryParam = encodeUrl(searchQuery) | |
33 | var client = newHttpClient() | |
34 | let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam) | |
35 | # TODO Get rid of temp file or make one temp file per user | |
36 | writeFile("/tmp/cli-tube-page.html", response.body) | |
37 | return "/tmp/cli-tube-page.html" | |
38 | ||
39 | proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = | |
40 | loadHtml(htmlFile).findAll("a"). | |
41 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
42 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) | |
43 | ||
44 | proc presentVideoOptions(searchResults: seq[SearchResult]) = | |
45 | for index, (title, url) in searchResults: | |
46 | echo index, ". ", title.bold.fgMagenta, "\n", url.fgCyan, "\n" | |
47 | ||
48 | presentVideoOptions( | |
49 | extractTitlesAndUrls( | |
50 | getYoutubePage( | |
51 | paramStr(1)))) |