]>
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 | # TODO Pretty colors in terminal | |
12 | # import terminal | |
13 | ||
14 | # Supported video players in order of preference | |
15 | # TODO Should go into a config file | |
16 | let supportedPlayers = @["mpv", "mplayer", "vlc"] | |
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 | 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 | ||
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 | # TODO Get rid of temp file or make one temp file per user | |
33 | writeFile("/tmp/cli-tube-page.html", response.body) | |
34 | return "/tmp/cli-tube-page.html" | |
35 | ||
36 | proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = | |
37 | loadHtml(htmlFile).findAll("a"). | |
38 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
39 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) | |
40 | ||
41 | proc presentVideoOptions(searchResults: seq[SearchResult]) = | |
42 | for index, (title, url) in searchResults: | |
43 | echo index, ". ", title, "\n", url, "\n" | |
44 | ||
45 | presentVideoOptions( | |
46 | extractTitlesAndUrls( | |
47 | getYoutubePage( | |
48 | paramStr(1)))) |