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