]> njoseph.me Git - nimcoon.git/blob - lib.nim
Continuously keep playing till I press "q"
[nimcoon.git] / lib.nim
1 import
2 htmlparser,
3 httpClient,
4 osproc,
5 sequtils,
6 sugar,
7 strformat,
8 std/[terminal],
9 strtabs,
10 strutils,
11 uri,
12 xmltree
13
14 import config
15
16 type
17 SearchResult* = tuple[title: string, url: string]
18 CommandLineOptions* = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
19
20 proc 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
28 proc 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
34 func 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)]
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 proc play*(player: string, args: openArray[string]) =
46 # poEchoCmd can be added to options for debugging
47 discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath})
48
49 func urlLongen(url: string): string =
50 url.replace("youtu.be/", "www.youtube.com/watch?v=")
51
52 func stripZshEscaping(url: string): string =
53 url.replace("\\", "")
54
55 func sanitizeURL*(url: string): string =
56 urlLongen(stripZshEscaping(url))
57
58 proc directPlay*(searchQuery: string, player: string) =
59 let url = sanitizeURL(searchQuery)
60 if searchQuery.startswith("magnet:"):
61 play("peerflix", args=[url, &"--{player}"])
62 else:
63 play(player, args=[url])