]> njoseph.me Git - nimcoon.git/blame_incremental - cli_tube.nim
Throw away the binary
[nimcoon.git] / cli_tube.nim
... / ...
CommitLineData
1import htmlparser
2import httpClient
3import os
4import osproc
5import sequtils, sugar
6import strtabs
7import strutils
8import uri
9import 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
16let supportedPlayers = @["mpv", "mplayer", "vlc"]
17
18type SearchResult = tuple[title: string, url: string]
19
20proc 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
28proc 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
36proc 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
41proc presentVideoOptions(searchResults: seq[SearchResult]) =
42 for index, (title, url) in searchResults:
43 echo index, ". ", title, "\n", url, "\n"
44
45presentVideoOptions(
46 extractTitlesAndUrls(
47 getYoutubePage(
48 paramStr(1))))