]> njoseph.me Git - nimcoon.git/blame_incremental - clitube.nim
strformat everywhere! 🥳
[nimcoon.git] / clitube.nim
... / ...
CommitLineData
1import htmlparser
2import httpClient
3import os
4import osproc
5import sequtils, sugar
6import strformat
7import std/[terminal]
8import strtabs
9import strutils
10import uri
11import xmltree
12
13# Supported video players in order of preference
14let supportedPlayers = ["mpv", "vlc"]
15
16# Only show these many results
17let limit = 10
18
19type SearchResult = tuple[title: string, url: string]
20
21proc 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
29proc 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
35proc 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
40proc 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
45let input = paramStr(1)
46let player = selectMediaPlayer()
47
48if "https://www.youtube.com" in input:
49 discard execProcess(&"{player} {input}")
50 quit(0)
51
52let searchResults = extractTitlesAndUrls(getYoutubePage(input))
53
54presentVideoOptions(searchResults)
55
56stdout.styledWrite(fgYellow, "Choose video number: ")
57let number: int = parseInt(readLine(stdin))
58
59styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
60
61# Play the video using the preferred/available media player
62discard execProcess(&"{player} {searchResults[number].url}")