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