]> njoseph.me Git - nimcoon.git/blob - src/lib.nim
Be a nimble package
[nimcoon.git] / src / 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 let processOptions = {poStdErrToStdOut, poUsePath}
21
22 proc 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
30 proc 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
36 func 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").
40 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
41
42 proc 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
47 proc play*(player: string, args: openArray[string], title: string) =
48 # poEchoCmd can be added to options for debugging
49 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
50 discard execProcess(player, args=args, options=processOptions)
51
52 func urlLongen(url: string): string =
53 url.replace("youtu.be/", "www.youtube.com/watch?v=")
54
55 func stripZshEscaping(url: string): string =
56 url.replace("\\", "")
57
58 func sanitizeURL*(url: string): string =
59 urlLongen(stripZshEscaping(url))
60
61 proc directPlay*(searchQuery: string, player: string) =
62 let url = sanitizeURL(searchQuery)
63 if searchQuery.startswith("magnet:"):
64 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
65 else:
66 discard execProcess(player, args=[url], options=processOptions)