Continuously keep playing till I press "q"
[nimcoon.git] / lib.nim
CommitLineData
d65a1dcf
JN
1import
2 htmlparser,
3 httpClient,
4 osproc,
5 sequtils,
6 sugar,
7 strformat,
8 std/[terminal],
9 strtabs,
10 strutils,
11 uri,
12 xmltree
13
14import config
15
16type
17 SearchResult* = tuple[title: string, url: string]
18 CommandLineOptions* = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
19
20proc selectMediaPlayer*(): string =
21 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
22 if len(availablePlayers) == 0:
23 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
24 raise newException(OSError, "No supported media player found")
25 else:
26 return availablePlayers[0]
27
28proc getYoutubePage*(searchQuery: string): string =
29 let queryParam = encodeUrl(searchQuery)
30 let client = newHttpClient()
31 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
32 return $response.body
33
4a0587e2
JN
34func extractTitlesAndUrls*(html: string): seq[SearchResult] =
35 {.noSideEffect.}:
36 parseHtml(html).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)]
d65a1dcf
JN
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
45proc play*(player: string, args: openArray[string]) =
46 # poEchoCmd can be added to options for debugging
47 discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath})
d65a1dcf
JN
48
49func urlLongen(url: string): string =
50 url.replace("youtu.be/", "www.youtube.com/watch?v=")
51
52func stripZshEscaping(url: string): string =
53 url.replace("\\", "")
54
55func sanitizeURL*(url: string): string =
56 urlLongen(stripZshEscaping(url))
57
58proc directPlay*(searchQuery: string, player: string) =
fe1a5856
JN
59 let url = sanitizeURL(searchQuery)
60 if searchQuery.startswith("magnet:"):
61 play("peerflix", args=[url, &"--{player}"])
62 else:
63 play(player, args=[url])