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]
40 func rewriteInvidiousToYouTube*(url: string): string =
42 if rewriteInvidiousURLs and url.replace(".", "").contains("invidious"):
43 &"https://www.youtube.com/watch?v={url.split(\"=\")[1]}"
47 func urlLongen(url: string): string =
48 url.replace("youtu.be/", "www.youtube.com/watch?v=")
51 func stripZshEscaping(url: string): string = url.replace("\\", "")
54 func sanitizeURL*(url: string): string =
55 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
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 != "")
68 proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
69 let args = buildPlayerArgs(url, options, player)
71 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
72 if "--no-video" in args:
73 discard execShellCmd(&"{player} {args.join(\" \")}")
75 discard execProcess(player, args=args, options=processOptions)
78 proc directPlay*(url: string, player: string, options: Table[string, bool]) =
80 if find(url, PEERTUBE_REGEX) != -1 and "webtorrent".isInstalled:
81 getPeerTubeMagnetLink(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")
88 # WebTorrent is so much faster!
89 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
91 play(player, options, url)
98 func buildMusicDownloadArgs(url: string): seq[string] =
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]
105 func buildVideoDownloadArgs(url: string): seq[string] =
107 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
108 @["-f", "best", "-o", downloadLocation, url]
111 func buildDownloadArgs(url: string, options: Options): seq[string] =
112 if options["musicOnly"]: buildMusicDownloadArgs(url)
113 else: buildVideoDownloadArgs(url)
116 proc download*(args: openArray[string], title: string) =
117 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
118 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
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'")
126 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
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(\" \")}")
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)
143 proc isValidOptions*(options: Options): bool =
144 # Check for invalid combinations of options
145 var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")]
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]}"
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."
157 proc updateOptions(options: Options, newOptions: string): Options =
160 # Interactive options
161 for option in newOptions:
163 of 'm': result["musicOnly"] = true
164 of 'f': result["fullScreen"] = true
165 of 'd': result["download"] = true
166 of 'a': result["autoPlay"] = true
168 stderr.writeLine "Invalid option provided!"
171 if(not isValidOptions(result)):
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)
186 play(player, options, searchResult.url, searchResult.title)
189 proc presentVideoOptions(searchResults: SearchResults) =
191 for index, (title, url) in searchResults:
192 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
195 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
196 if options["feelingLucky"]: "0"
198 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
199 stdout.styledWrite(fgYellow, "Choose video number: ")
203 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
204 ##[ Continuously present options till the user quits the application
206 selectionRange: Currently available range to choose from depending on pagination
209 let userInput = offerSelection(searchResults, options, selectionRange)
213 for selection in selectionRange.begin .. selectionRange.until:
214 handleUserInput(searchResults[selection], options, player)
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)
221 present(searchResults, options, selectionRange, player)
223 if selectionRange.begin > 0:
224 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
225 present(searchResults, options, newSelectionRange, player)
227 present(searchResults, options, selectionRange, player)
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)
237 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
238 handleUserInput(searchResult, options, player)
239 if options["feelingLucky"]:
242 present(searchResults, options, selectionRange, player)