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}"
23 proc isInstalled(program: string): bool =
24 execProcess("which " & program).len != 0
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")
33 return availablePlayers[0]
36 proc printTitle(action: string, title: string) =
37 styledEcho "\n", fgGreen, &"{action} ", styleBright, fgMagenta, title
44 func rewriteInvidiousToYouTube*(url: string): string =
46 if rewriteInvidiousURLs and url.replace(".", "").contains("invidious"):
47 &"https://www.youtube.com/watch?v={url.split(\"=\")[1]}"
51 func urlLongen(url: string): string =
52 url.replace("youtu.be/", "www.youtube.com/watch?v=")
55 func stripZshEscaping(url: string): string = url.replace("\\", "")
58 func sanitizeURL*(url: string): string =
59 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
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 != "")
72 proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
73 let args = buildPlayerArgs(url, options, player)
75 printTitle("Playing", title)
76 if "--no-video" in args:
77 discard execShellCmd(&"{player} {args.join(\" \")}")
79 discard execProcess(player, args=args, options=processOptions)
82 proc directPlay*(url: string, player: string, options: Table[string, bool]) =
84 if find(url, PEERTUBE_REGEX) != -1 and "webtorrent".isInstalled:
85 getPeerTubeMagnetLink(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")
92 # WebTorrent is so much faster!
93 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
95 play(player, options, url)
102 func buildMusicDownloadArgs(url: string): seq[string] =
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]
109 func buildVideoDownloadArgs(url: string): seq[string] =
111 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
112 @["-f", "best", "-o", downloadLocation, url]
115 func buildDownloadArgs(url: string, options: Options): seq[string] =
116 if options["musicOnly"]: buildMusicDownloadArgs(url)
117 else: buildVideoDownloadArgs(url)
120 proc download*(args: openArray[string], title: string) =
121 printTitle("Downloading", title)
122 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
125 proc directDownload*(url: string, options: Options) =
126 let args = buildDownloadArgs(url, options)
127 if "aria2c".isInstalled:
128 discard execShellCmd(&"youtube-dl {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'")
130 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
132 proc luckyDownload*(searchQuery: string, options: Options) =
133 let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options)
134 let title = execProcess(&"youtube-dl --get-title {args.join(\" \")}").split("\n")[0]
135 download(args, title)
137 proc luckyPlay*(searchQuery: string, player: string, options: Options) =
138 let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options)
139 let output = execProcess(&"youtube-dl --get-url --get-title {args.join(\" \")}").split("\n")
142 url = &"\"{output[1]}\""
143 play(player, options, url, title)
149 proc isValidOptions*(options: Options): bool =
150 # Check for invalid combinations of options
151 var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")]
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]}"
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."
163 proc updateOptions(options: Options, newOptions: string): Options =
166 # Interactive options
167 for option in newOptions:
169 of 'm': result["musicOnly"] = true
170 of 'f': result["fullScreen"] = true
171 of 'd': result["download"] = true
172 of 'a': result["autoPlay"] = true
174 stderr.writeLine "Invalid option provided!"
177 if(not isValidOptions(result)):
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)
192 play(player, options, searchResult.url, searchResult.title)
195 proc presentVideoOptions(searchResults: SearchResults) =
197 for index, (title, url) in searchResults:
198 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
201 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
202 if options["feelingLucky"]: "0"
204 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
205 stdout.styledWrite(fgYellow, "Choose video number: ")
209 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
210 ##[ Continuously present options till the user quits the application
212 selectionRange: Currently available range to choose from depending on pagination
215 let userInput = offerSelection(searchResults, options, selectionRange)
219 for selection in selectionRange.begin .. selectionRange.until:
220 handleUserInput(searchResults[selection], options, player)
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)
227 present(searchResults, options, selectionRange, player)
229 if selectionRange.begin > 0:
230 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
231 present(searchResults, options, newSelectionRange, player)
233 present(searchResults, options, selectionRange, player)
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)
243 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
244 handleUserInput(searchResult, options, player)
245 if options["feelingLucky"]:
248 present(searchResults, options, selectionRange, player)