]> njoseph.me Git - nimcoon.git/blame - src/lib.nim
Be a nimble package
[nimcoon.git] / src / 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
9e6b8568
JN
20let processOptions = {poStdErrToStdOut, poUsePath}
21
d65a1dcf
JN
22proc selectMediaPlayer*(): string =
23 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
24 if len(availablePlayers) == 0:
25 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
26 raise newException(OSError, "No supported media player found")
27 else:
28 return availablePlayers[0]
29
30proc getYoutubePage*(searchQuery: string): string =
31 let queryParam = encodeUrl(searchQuery)
32 let client = newHttpClient()
33 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
34 return $response.body
35
4a0587e2
JN
36func extractTitlesAndUrls*(html: string): seq[SearchResult] =
37 {.noSideEffect.}:
38 parseHtml(html).findAll("a").
39 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
72720bec 40 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
d65a1dcf
JN
41
42proc presentVideoOptions*(searchResults: seq[SearchResult]) =
43 echo ""
44 for index, (title, url) in searchResults:
45 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
46
9e6b8568 47proc play*(player: string, args: openArray[string], title: string) =
d65a1dcf 48 # poEchoCmd can be added to options for debugging
9e6b8568
JN
49 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
50 discard execProcess(player, args=args, options=processOptions)
d65a1dcf
JN
51
52func urlLongen(url: string): string =
53 url.replace("youtu.be/", "www.youtube.com/watch?v=")
54
55func stripZshEscaping(url: string): string =
56 url.replace("\\", "")
57
58func sanitizeURL*(url: string): string =
59 urlLongen(stripZshEscaping(url))
60
61proc directPlay*(searchQuery: string, player: string) =
fe1a5856
JN
62 let url = sanitizeURL(searchQuery)
63 if searchQuery.startswith("magnet:"):
9e6b8568 64 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
fe1a5856 65 else:
3ba7018e 66 discard execProcess(player, args=[url], options=processOptions)