]> njoseph.me Git - nimcoon.git/blame - cli_tube.nim
Use a user-defined type for search results
[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
39a495a9 20proc findSupportedPlayer(): string =
44978125 21 for player in supported_players:
39a495a9
JN
22 let playerBin = execProcess("which " & player)
23 if playerBin.len != 0:
24 return strip(playerBin)
44978125 25
39a495a9
JN
26proc getYoutubePage(searchQuery: string): string =
27 let queryParam = encodeUrl(searchQuery)
44978125 28 var client = newHttpClient()
39a495a9 29 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
44978125
JN
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
2f3c8875 34proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
39a495a9 35 loadHtml(htmlFile).findAll("a").
44978125
JN
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
2f3c8875
JN
39proc presentVideoOptions(searchResults: seq[SearchResult]) =
40 for index, (title, url) in searchResults:
41 echo index, ". ", title, "\n", url, "\n"
44978125 42
39a495a9
JN
43presentVideoOptions(
44 extractTitlesAndUrls(
45 getYoutubePage(
44978125 46 paramStr(1))))