]> njoseph.me Git - nimcoon.git/blame - cli_tube.nim
Throw away the binary
[nimcoon.git] / cli_tube.nim
CommitLineData
44978125
JN
1import htmlparser
2import httpClient
3import os
4import osproc
2f3c8875 5import sequtils, sugar
44978125
JN
6import strtabs
7import strutils
8import uri
9import xmltree
44978125
JN
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
39a495a9 16let supportedPlayers = @["mpv", "mplayer", "vlc"]
44978125 17
2f3c8875
JN
18type SearchResult = tuple[title: string, url: string]
19
933e339b
JN
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]
44978125 27
39a495a9
JN
28proc getYoutubePage(searchQuery: string): string =
29 let queryParam = encodeUrl(searchQuery)
44978125 30 var client = newHttpClient()
39a495a9 31 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
44978125
JN
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
2f3c8875 36proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
39a495a9 37 loadHtml(htmlFile).findAll("a").
44978125
JN
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
2f3c8875
JN
41proc presentVideoOptions(searchResults: seq[SearchResult]) =
42 for index, (title, url) in searchResults:
43 echo index, ". ", title, "\n", url, "\n"
44978125 44
39a495a9
JN
45presentVideoOptions(
46 extractTitlesAndUrls(
47 getYoutubePage(
44978125 48 paramStr(1))))