]>
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"w\/[0-9a-zA-z]{22}" | |
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, options["musicOnly"]) | |
86 | else: url | |
87 | if url.startswith("magnet:") or url.endswith(".torrent"): | |
88 | if options["musicOnly"]: | |
89 | discard execShellCmd(&"webtorrent '{url}' --{player} --player-args='--no-video'") | |
90 | else: | |
91 | discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions) | |
92 | else: | |
93 | play(player, options, url) | |
94 | ||
95 | ||
96 | ############ | |
97 | # DOWNLOAD # | |
98 | ############ | |
99 | ||
100 | func buildMusicDownloadArgs(url: string): seq[string] = | |
101 | {.noSideEffect.}: | |
102 | let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'" | |
103 | @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", | |
104 | "--audio-quality", "0", "-o", downloadLocation, url] | |
105 | ||
106 | ||
107 | func buildVideoDownloadArgs(url: string): seq[string] = | |
108 | {.noSideEffect.}: | |
109 | let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'" | |
110 | @["-f", "best", "-o", downloadLocation, url] | |
111 | ||
112 | ||
113 | func buildDownloadArgs(url: string, options: Options): seq[string] = | |
114 | if options["musicOnly"]: buildMusicDownloadArgs(url) | |
115 | else: buildVideoDownloadArgs(url) | |
116 | ||
117 | ||
118 | proc download*(args: openArray[string], title: string) = | |
119 | printTitle("Downloading", title) | |
120 | discard execShellCmd(&"yt-dlp {args.join(\" \")}") | |
121 | ||
122 | ||
123 | proc directDownload*(url: string, options: Options) = | |
124 | let args = buildDownloadArgs(url, options) | |
125 | if "aria2c".isInstalled: | |
126 | discard execShellCmd(&"yt-dlp {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'") | |
127 | else: | |
128 | discard execShellCmd(&"yt-dlp {args.join(\" \")}") | |
129 | ||
130 | proc luckyDownload*(searchQuery: string, options: Options) = | |
131 | let args = @[&"ytsearch1:\"{searchQuery}\""] & buildDownloadArgs("", options) | |
132 | let title = execProcess(&"yt-dlp --get-title {args.join(\" \")}").split("\n")[0] | |
133 | download(args, title) | |
134 | ||
135 | proc luckyPlay*(searchQuery: string, player: string, options: Options) = | |
136 | let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options) | |
137 | let output = execProcess(&"yt-dlp --get-url --get-title {args.join(\" \")}").split("\n") | |
138 | let | |
139 | title = output[0] | |
140 | url = &"\"{output[1]}\"" | |
141 | play(player, options, url, title) | |
142 | ||
143 | ########### | |
144 | # OPTIONS # | |
145 | ########### | |
146 | ||
147 | proc isValidOptions*(options: Options): bool = | |
148 | # Check for invalid combinations of options | |
149 | var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")] | |
150 | result = true | |
151 | for combination in invalidCombinations: | |
152 | if options[combination[0]] and options[combination[1]]: | |
153 | stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}" | |
154 | result = false | |
155 | # TODO Make this overridable in configuration | |
156 | if options["autoPlay"] and not options["musicOnly"]: | |
157 | stderr.writeLine "--music-only must be provided with --auto-play. This is to prevent binge-watching." | |
158 | result = false | |
159 | ||
160 | ||
161 | proc updateOptions(options: Options, newOptions: string): Options = | |
162 | result = options | |
163 | ||
164 | # Interactive options | |
165 | for option in newOptions: | |
166 | case option | |
167 | of 'm': result["musicOnly"] = true | |
168 | of 'f': result["fullScreen"] = true | |
169 | of 'd': result["download"] = true | |
170 | of 'a': result["autoPlay"] = true | |
171 | else: | |
172 | stderr.writeLine "Invalid option provided!" | |
173 | quit(2) | |
174 | ||
175 | if(not isValidOptions(result)): | |
176 | quit(2) | |
177 | ||
178 | ||
179 | ################ | |
180 | # PRESENTATION # | |
181 | ################ | |
182 | ||
183 | proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) = | |
184 | if options["autoPlay"]: | |
185 | play(player, options, searchResult.url, searchResult.title) | |
186 | handleUserInput(getAutoPlayVideo(searchResult), options, player) # inifinite playlist till user quits | |
187 | elif options["download"]: | |
188 | download(buildDownloadArgs(searchResult.url, options), searchResult.title) | |
189 | else: | |
190 | play(player, options, searchResult.url, searchResult.title) | |
191 | ||
192 | ||
193 | proc presentVideoOptions(searchResults: SearchResults) = | |
194 | eraseScreen() | |
195 | for index, (title, url) in searchResults: | |
196 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n" | |
197 | ||
198 | ||
199 | proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string = | |
200 | if options["feelingLucky"]: "0" | |
201 | else: | |
202 | presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until]) | |
203 | stdout.styledWrite(fgYellow, "Choose video number: ") | |
204 | readLine(stdin) | |
205 | ||
206 | ||
207 | proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) = | |
208 | ##[ Continuously present options till the user quits the application | |
209 | ||
210 | selectionRange: Currently available range to choose from depending on pagination | |
211 | ]## | |
212 | ||
213 | let userInput = offerSelection(searchResults, options, selectionRange) | |
214 | ||
215 | case userInput | |
216 | of "all": | |
217 | for selection in selectionRange.begin .. selectionRange.until: | |
218 | handleUserInput(searchResults[selection], options, player) | |
219 | quit(0) | |
220 | of "n": | |
221 | if selectionRange.until + 1 < len(searchResults): | |
222 | let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit)) | |
223 | present(searchResults, options, newSelectionRange, player) | |
224 | else: | |
225 | present(searchResults, options, selectionRange, player) | |
226 | of "p": | |
227 | if selectionRange.begin > 0: | |
228 | let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit) | |
229 | present(searchResults, options, newSelectionRange, player) | |
230 | else: | |
231 | present(searchResults, options, selectionRange, player) | |
232 | of "q": | |
233 | quit(0) | |
234 | else: | |
235 | if " " in userInput: | |
236 | let selection = parseInt(userInput.split(" ")[0]) | |
237 | let updatedOptions = updateOptions(options, userInput.split(" ")[1]) | |
238 | let searchResult = searchResults[selectionRange.begin .. selectionRange.until][selection] | |
239 | handleUserInput(searchResult, updatedOptions, player) | |
240 | else: | |
241 | let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)] | |
242 | handleUserInput(searchResult, options, player) | |
243 | if options["feelingLucky"]: | |
244 | quit(0) | |
245 | else: | |
246 | present(searchResults, options, selectionRange, player) |