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