]>
Commit | Line | Data |
---|---|---|
d65a1dcf | 1 | import |
e9f0c7d0 | 2 | os, |
d65a1dcf | 3 | osproc, |
c12cc641 | 4 | re, |
d65a1dcf | 5 | sequtils, |
d65a1dcf | 6 | std/[terminal], |
e9f0c7d0 | 7 | strformat, |
d65a1dcf | 8 | strutils, |
e08e5cbe | 9 | tables |
d65a1dcf | 10 | |
e08e5cbe JN |
11 | import |
12 | config, | |
6697cfd2 | 13 | peertube, |
5f9cdfef JN |
14 | types, |
15 | youtube | |
d65a1dcf | 16 | |
b44b6494 | 17 | |
b44b6494 | 18 | let |
6697cfd2 | 19 | processOptions = {poStdErrToStdOut, poUsePath} # Add poEchoCmd to debug |
b44b6494 JN |
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 | ||
c12cc641 JN |
22 | |
23 | proc isInstalled(program: string): bool = | |
24 | execProcess("which " & program).len != 0 | |
9e6b8568 | 25 | |
b44b6494 | 26 | |
d65a1dcf | 27 | proc selectMediaPlayer*(): string = |
c12cc641 | 28 | let availablePlayers = supportedPlayers.filter(isInstalled) |
d65a1dcf JN |
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 | ||
b44b6494 | 35 | |
6697cfd2 JN |
36 | ############### |
37 | # URL CLEANUP # | |
38 | ############### | |
c12cc641 | 39 | |
6697cfd2 JN |
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 | |
b44b6494 | 45 | |
d65a1dcf | 46 | |
6697cfd2 JN |
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 | ######## | |
a2d28598 | 61 | |
d36e2201 | 62 | func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] = |
046c2cc3 JN |
63 | let musicOnly = if options["musicOnly"]: "--no-video" else: "" |
64 | let fullScreen = if options["fullScreen"]: "--fullscreen" else: "" | |
55b0cae7 | 65 | filterIt([url, musicOnly, fullScreen], it != "") |
d36e2201 | 66 | |
b44b6494 | 67 | |
d36e2201 JN |
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 | |
e71f26f3 JN |
72 | if "--no-video" in args: |
73 | discard execShellCmd(&"{player} {args.join(\" \")}") | |
74 | else: | |
a2d28598 | 75 | discard execProcess(player, args=args, options=processOptions) |
d65a1dcf | 76 | |
b44b6494 | 77 | |
6697cfd2 JN |
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 | ||
b44b6494 | 98 | func buildMusicDownloadArgs(url: string): seq[string] = |
9a8ef4ad | 99 | {.noSideEffect.}: |
9a8ef4ad | 100 | let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'" |
b44b6494 JN |
101 | @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", |
102 | "--audio-quality", "0", "-o", downloadLocation, url] | |
103 | ||
9a8ef4ad | 104 | |
b44b6494 | 105 | func buildVideoDownloadArgs(url: string): seq[string] = |
9a8ef4ad | 106 | {.noSideEffect.}: |
9a8ef4ad | 107 | let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'" |
55b0cae7 | 108 | @["-f", "best", "-o", downloadLocation, url] |
9a8ef4ad | 109 | |
b44b6494 | 110 | |
6697cfd2 JN |
111 | func buildDownloadArgs(url: string, options: Options): seq[string] = |
112 | if options["musicOnly"]: buildMusicDownloadArgs(url) | |
113 | else: buildVideoDownloadArgs(url) | |
114 | ||
115 | ||
e9f0c7d0 JN |
116 | proc download*(args: openArray[string], title: string) = |
117 | styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title | |
118 | discard execShellCmd(&"youtube-dl {args.join(\" \")}") | |
119 | ||
b44b6494 | 120 | |
6697cfd2 JN |
121 | proc directDownload*(url: string, options: Options) = |
122 | let args = buildDownloadArgs(url, options) | |
123 | if "aria2c".isInstalled: | |
0c2f0385 JN |
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(\" \")}") | |
13a4017d | 127 | |
6697cfd2 JN |
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(\" \")}") | |
b44b6494 | 132 | |
6697cfd2 JN |
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) | |
13a4017d | 138 | |
6697cfd2 JN |
139 | ########### |
140 | # OPTIONS # | |
141 | ########### | |
b44b6494 | 142 | |
9ed70b9e JN |
143 | proc isValidOptions*(options: Options): bool = |
144 | # Check for invalid combinations of options | |
5f9cdfef | 145 | var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")] |
9ed70b9e JN |
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 | |
5f9cdfef JN |
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 | |
9ed70b9e JN |
155 | |
156 | ||
157 | proc updateOptions(options: Options, newOptions: string): Options = | |
158 | result = options | |
159 | ||
5f9cdfef | 160 | # Interactive options |
9ed70b9e JN |
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 | |
5f9cdfef | 166 | of 'a': result["autoPlay"] = true |
9ed70b9e | 167 | else: |
5f9cdfef | 168 | stderr.writeLine "Invalid option provided!" |
9ed70b9e JN |
169 | quit(2) |
170 | ||
171 | if(not isValidOptions(result)): | |
172 | quit(2) | |
173 | ||
174 | ||
6697cfd2 JN |
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 | ||
13a4017d | 203 | proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) = |
55b0cae7 JN |
204 | ##[ Continuously present options till the user quits the application |
205 | ||
206 | selectionRange: Currently available range to choose from depending on pagination | |
207 | ]## | |
13a4017d JN |
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) | |
ebae91b4 JN |
220 | else: |
221 | present(searchResults, options, selectionRange, player) | |
13a4017d JN |
222 | of "p": |
223 | if selectionRange.begin > 0: | |
224 | let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit) | |
225 | present(searchResults, options, newSelectionRange, player) | |
ebae91b4 JN |
226 | else: |
227 | present(searchResults, options, selectionRange, player) | |
13a4017d JN |
228 | of "q": |
229 | quit(0) | |
230 | else: | |
9ed70b9e JN |
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) | |
13a4017d JN |
239 | if options["feelingLucky"]: |
240 | quit(0) | |
241 | else: | |
242 | present(searchResults, options, selectionRange, player) |