]>
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 findSupportedPlayer(): string = | |
21 | for player in supported_players: | |
22 | let playerBin = execProcess("which " & player) | |
23 | if playerBin.len != 0: | |
24 | return strip(playerBin) | |
25 | ||
26 | proc getYoutubePage(searchQuery: string): string = | |
27 | let queryParam = encodeUrl(searchQuery) | |
28 | var client = newHttpClient() | |
29 | let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam) | |
30 | # TODO Get rid of temp file or make one temp file per user | |
31 | writeFile("/tmp/cli-tube-page.html", response.body) | |
32 | return "/tmp/cli-tube-page.html" | |
33 | ||
34 | proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = | |
35 | loadHtml(htmlFile).findAll("a"). | |
36 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
37 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) | |
38 | ||
39 | proc presentVideoOptions(searchResults: seq[SearchResult]) = | |
40 | for index, (title, url) in searchResults: | |
41 | echo index, ". ", title, "\n", url, "\n" | |
42 | ||
43 | presentVideoOptions( | |
44 | extractTitlesAndUrls( | |
45 | getYoutubePage( | |
46 | paramStr(1)))) |