]> njoseph.me Git - nimcoon.git/blob - src/lib.nim
25a80169bbc1b8f6c8359da8b1cd18f56f2429a7
[nimcoon.git] / src / lib.nim
1 import
2 os,
3 osproc,
4 re,
5 sequtils,
6 std/[terminal],
7 strformat,
8 strutils,
9 tables
10
11 import
12 config,
13 peertube,
14 types,
15 youtube
16
17
18 let
19 processOptions = {poStdErrToStdOut, poUsePath} # Add poEchoCmd to debug
20 PEERTUBE_REGEX = re"videos\/watch\/[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}"
21
22
23 proc isInstalled(program: string): bool =
24 execProcess("which " & program).len != 0
25
26
27 proc selectMediaPlayer*(): string =
28 let availablePlayers = supportedPlayers.filter(isInstalled)
29 if len(availablePlayers) == 0:
30 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
31 raise newException(OSError, "No supported media player found")
32 else:
33 return availablePlayers[0]
34
35
36 ###############
37 # URL CLEANUP #
38 ###############
39
40 func rewriteInvidiousToYouTube*(url: string): string =
41 {.noSideEffect.}:
42 if rewriteInvidiousURLs and url.replace(".", "").contains("invidious"):
43 &"https://www.youtube.com/watch?v={url.split(\"=\")[1]}"
44 else: url
45
46
47 func urlLongen(url: string): string =
48 url.replace("youtu.be/", "www.youtube.com/watch?v=")
49
50
51 func stripZshEscaping(url: string): string = url.replace("\\", "")
52
53
54 func sanitizeURL*(url: string): string =
55 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
56
57
58 ########
59 # PLAY #
60 ########
61
62 func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
63 let musicOnly = if options["musicOnly"]: "--no-video" else: ""
64 let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
65 filterIt([url, musicOnly, fullScreen], it != "")
66
67
68 proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
69 let args = buildPlayerArgs(url, options, player)
70 if title != "":
71 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
72 if "--no-video" in args:
73 discard execShellCmd(&"{player} {args.join(\" \")}")
74 else:
75 discard execProcess(player, args=args, options=processOptions)
76
77
78 proc directPlay*(url: string, player: string, options: Table[string, bool]) =
79 let url =
80 if find(url, PEERTUBE_REGEX) != -1 and "webtorrent".isInstalled:
81 getPeerTubeMagnetLink(url)
82 else: url
83 if url.startswith("magnet:") or url.endswith(".torrent"):
84 if options["musicOnly"]:
85 # TODO Replace with WebTorrent once it supports media player options
86 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
87 else:
88 # WebTorrent is so much faster!
89 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
90 else:
91 play(player, options, url)
92
93
94 ############
95 # DOWNLOAD #
96 ############
97
98 func buildMusicDownloadArgs(url: string): seq[string] =
99 {.noSideEffect.}:
100 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
101 @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3",
102 "--audio-quality", "0", "-o", downloadLocation, url]
103
104
105 func buildVideoDownloadArgs(url: string): seq[string] =
106 {.noSideEffect.}:
107 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
108 @["-f", "best", "-o", downloadLocation, url]
109
110
111 func buildDownloadArgs(url: string, options: Options): seq[string] =
112 if options["musicOnly"]: buildMusicDownloadArgs(url)
113 else: buildVideoDownloadArgs(url)
114
115
116 proc download*(args: openArray[string], title: string) =
117 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
118 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
119
120
121 proc directDownload*(url: string, options: Options) =
122 let args = buildDownloadArgs(url, options)
123 if "aria2c".isInstalled:
124 discard execShellCmd(&"youtube-dl {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'")
125 else:
126 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
127
128 proc luckyDownload*(searchQuery: string, options: Options) =
129 let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options)
130 styledEcho "\n", fgGreen, "Searching and downloading using youtube-dl"
131 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
132
133 proc luckyPlay*(searchQuery: string, player: string, options: Options) =
134 let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options)
135 let output = execProcess(&"youtube-dl --get-url {args.join(\" \")}")
136 let url = output.split("\n")[0]
137 play(player, options, url)
138
139 ###########
140 # OPTIONS #
141 ###########
142
143 proc isValidOptions*(options: Options): bool =
144 # Check for invalid combinations of options
145 var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")]
146 result = true
147 for combination in invalidCombinations:
148 if options[combination[0]] and options[combination[1]]:
149 stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}"
150 result = false
151 # TODO Make this overridable in configuration
152 if options["autoPlay"] and not options["musicOnly"]:
153 stderr.writeLine "--music-only must be provided with --auto-play. This is to prevent binge-watching."
154 result = false
155
156
157 proc updateOptions(options: Options, newOptions: string): Options =
158 result = options
159
160 # Interactive options
161 for option in newOptions:
162 case option
163 of 'm': result["musicOnly"] = true
164 of 'f': result["fullScreen"] = true
165 of 'd': result["download"] = true
166 of 'a': result["autoPlay"] = true
167 else:
168 stderr.writeLine "Invalid option provided!"
169 quit(2)
170
171 if(not isValidOptions(result)):
172 quit(2)
173
174
175 ################
176 # PRESENTATION #
177 ################
178
179 proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
180 if options["autoPlay"]:
181 play(player, options, searchResult.url, searchResult.title)
182 handleUserInput(getAutoPlayVideo(searchResult), options, player) # inifinite playlist till user quits
183 elif options["download"]:
184 download(buildDownloadArgs(searchResult.url, options), searchResult.title)
185 else:
186 play(player, options, searchResult.url, searchResult.title)
187
188
189 proc presentVideoOptions(searchResults: SearchResults) =
190 eraseScreen()
191 for index, (title, url) in searchResults:
192 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
193
194
195 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
196 if options["feelingLucky"]: "0"
197 else:
198 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
199 stdout.styledWrite(fgYellow, "Choose video number: ")
200 readLine(stdin)
201
202
203 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
204 ##[ Continuously present options till the user quits the application
205
206 selectionRange: Currently available range to choose from depending on pagination
207 ]##
208
209 let userInput = offerSelection(searchResults, options, selectionRange)
210
211 case userInput
212 of "all":
213 for selection in selectionRange.begin .. selectionRange.until:
214 handleUserInput(searchResults[selection], options, player)
215 quit(0)
216 of "n":
217 if selectionRange.until + 1 < len(searchResults):
218 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
219 present(searchResults, options, newSelectionRange, player)
220 else:
221 present(searchResults, options, selectionRange, player)
222 of "p":
223 if selectionRange.begin > 0:
224 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
225 present(searchResults, options, newSelectionRange, player)
226 else:
227 present(searchResults, options, selectionRange, player)
228 of "q":
229 quit(0)
230 else:
231 if " " in userInput:
232 let selection = parseInt(userInput.split(" ")[0])
233 let updatedOptions = updateOptions(options, userInput.split(" ")[1])
234 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][selection]
235 handleUserInput(searchResult, updatedOptions, player)
236 else:
237 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
238 handleUserInput(searchResult, options, player)
239 if options["feelingLucky"]:
240 quit(0)
241 else:
242 present(searchResults, options, selectionRange, player)