]> njoseph.me Git - nimcoon.git/blame_incremental - clitube.nim
Add limit option with default set to 10 results
[nimcoon.git] / clitube.nim
... / ...
CommitLineData
1import htmlparser
2import httpClient
3import os
4import osproc
5import sequtils, sugar
6import strtabs
7import strutils
8import uri
9import xmltree
10
11# Supported video players in order of preference
12let supportedPlayers = @["mpv", "mplayer", "vlc"]
13
14# Only show these many results
15let limit = 10
16
17# Hard-coded terminal colors
18proc reset(): string {.procvar.} = "\e[0m"
19proc bold*(s: string): string {.procvar.} = "\e[1m" & s & reset()
20
21proc fgMagenta*(s: string): string {.procvar.} = "\e[35m" & s & reset()
22proc fgCyan*(s: string): string {.procvar.} = "\e[36m" & s & reset()
23
24type SearchResult = tuple[title: string, url: string]
25
26proc 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]
33
34proc getYoutubePage(searchQuery: string): string =
35 let queryParam = encodeUrl(searchQuery)
36 var client = newHttpClient()
37 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
38 writeFile("/tmp/cli-tube-page.html", response.body)
39 return "/tmp/cli-tube-page.html"
40
41proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
42 loadHtml(htmlFile).findAll("a").
43 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
44 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
45
46proc presentVideoOptions(searchResults: seq[SearchResult]) =
47 echo "\n"
48 for index, (title, url) in searchResults:
49 echo index, ". ", title.bold.fgMagenta, "\n", url.fgCyan, "\n"
50
51presentVideoOptions(
52 extractTitlesAndUrls(
53 getYoutubePage(
54 paramStr(1))))