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