strformat everywhere! 🥳
[nimcoon.git] / clitube.nim
1 import htmlparser
2 import httpClient
3 import os
4 import osproc
5 import sequtils, sugar
6 import strformat
7 import std/[terminal]
8 import strtabs
9 import strutils
10 import uri
11 import xmltree
12
13 # Supported video players in order of preference
14 let supportedPlayers = ["mpv", "vlc"]
15
16 # Only show these many results
17 let limit = 10
18
19 type SearchResult = tuple[title: string, url: string]
20
21 proc selectMediaPlayer(): string =
22 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
23 if len(availablePlayers) == 0:
24 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
25 raise newException(OSError, "No supported media player found")
26 else:
27 return availablePlayers[0]
28
29 proc getYoutubePage(searchQuery: string): string =
30 let queryParam = encodeUrl(searchQuery)
31 let client = newHttpClient()
32 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
33 return $response.body
34
35 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
36 parseHtml(htmlFile).findAll("a").
37 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
38 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
39
40 proc presentVideoOptions(searchResults: seq[SearchResult]) =
41 echo ""
42 for index, (title, url) in searchResults:
43 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
44
45 let input = paramStr(1)
46 let player = selectMediaPlayer()
47
48 if "https://www.youtube.com" in input:
49 discard execProcess(&"{player} {input}")
50 quit(0)
51
52 let searchResults = extractTitlesAndUrls(getYoutubePage(input))
53
54 presentVideoOptions(searchResults)
55
56 stdout.styledWrite(fgYellow, "Choose video number: ")
57 let number: int = parseInt(readLine(stdin))
58
59 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
60
61 # Play the video using the preferred/available media player
62 discard execProcess(&"{player} {searchResults[number].url}")