]> njoseph.me Git - nimcoon.git/blame_incremental - cli_tube.nim
Use a user-defined type for search results
[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 findSupportedPlayer(): string =
21 for player in supported_players:
22 let playerBin = execProcess("which " & player)
23 if playerBin.len != 0:
24 return strip(playerBin)
25
26proc 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
34proc 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
39proc presentVideoOptions(searchResults: seq[SearchResult]) =
40 for index, (title, url) in searchResults:
41 echo index, ". ", title, "\n", url, "\n"
42
43presentVideoOptions(
44 extractTitlesAndUrls(
45 getYoutubePage(
46 paramStr(1))))