54259e2d9f7d08237c3bb73ec51e30fb9751167a
[nimcoon.git] / src / lib.nim
1 import
2 htmlparser,
3 httpClient,
4 os,
5 osproc,
6 sequtils,
7 sugar,
8 strformat,
9 std/[terminal],
10 strformat,
11 strtabs,
12 strutils,
13 tables,
14 uri,
15 xmltree
16
17 import config
18
19 type
20 Options* = Table[string, bool]
21 SearchResult* = tuple[title: string, url: string]
22 CommandLineOptions* = tuple[searchQuery: string, options: Options]
23 SelectionRange* = tuple[begin: int, until: int]
24
25 # poEchoCmd can be added to options for debugging
26 let processOptions = {poStdErrToStdOut, poUsePath}
27
28 proc selectMediaPlayer*(): string =
29 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
30 if len(availablePlayers) == 0:
31 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
32 raise newException(OSError, "No supported media player found")
33 else:
34 return availablePlayers[0]
35
36 proc getYoutubePage*(searchQuery: string): string =
37 let queryParam = encodeUrl(searchQuery)
38 let client = newHttpClient()
39 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
40 return $response.body
41
42 func extractTitlesAndUrls*(html: string): seq[SearchResult] =
43 {.noSideEffect.}:
44 parseHtml(html).findAll("a").
45 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
46 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
47
48 proc presentVideoOptions*(searchResults: seq[SearchResult]) =
49 eraseScreen()
50 for index, (title, url) in searchResults:
51 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
52
53 proc play*(player: string, args: openArray[string], title: string) =
54 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
55 if "--no-video" in args:
56 discard execShellCmd(&"{player} {args.join(\" \")}")
57 else:
58 discard execProcess(player, args=args, options=processOptions)
59
60 func buildMusicDownloadArgs*(url: string): seq[string] =
61 {.noSideEffect.}:
62 var args = @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o"]
63 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
64 args.add(downloadLocation)
65 args.add(url)
66 return args
67
68 func buildVideoDownloadArgs*(url: string): seq[string] =
69 {.noSideEffect.}:
70 var args = @["-f", "best", "-o"]
71 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
72 args.add(downloadLocation)
73 args.add(url)
74 return args
75
76 proc download*(args: openArray[string], title: string) =
77 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
78 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
79
80 func urlLongen(url: string): string =
81 url.replace("youtu.be/", "www.youtube.com/watch?v=")
82
83 func stripZshEscaping(url: string): string =
84 url.replace("\\", "")
85
86 func sanitizeURL*(url: string): string =
87 urlLongen(stripZshEscaping(url))
88
89 proc directPlay*(url: string, player: string, musicOnly: bool) =
90 if url.startswith("magnet:"):
91 if musicOnly:
92 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
93 else:
94 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
95 else:
96 if musicOnly:
97 discard execShellCmd(&"{player} --no-video {url}")
98 else:
99 discard execProcess(player, args=[url], options=processOptions)
100
101 proc directDownload*(url: string, musicOnly: bool) =
102 let args =
103 if musicOnly: buildMusicDownloadArgs(url)
104 else: buildVideoDownloadArgs(url)
105 discard execShellCmd(&"youtube-dl {args.join(\" \")}")