20 Options* = Table[string, bool]
21 SearchResult* = tuple[title: string, url: string]
22 SearchResults* = seq[tuple[title: string, url: string]]
23 CommandLineOptions* = tuple[searchQuery: string, options: Options]
24 SelectionRange* = tuple[begin: int, until: int]
26 # poEchoCmd can be added to options for debugging
27 let processOptions = {poStdErrToStdOut, poUsePath}
29 proc selectMediaPlayer*(): string =
30 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
31 if len(availablePlayers) == 0:
32 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
33 raise newException(OSError, "No supported media player found")
35 return availablePlayers[0]
37 proc getYoutubePage*(searchQuery: string): string =
38 let queryParam = encodeUrl(searchQuery)
39 let client = newHttpClient()
40 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
43 func extractTitlesAndUrls*(html: string): SearchResults =
45 parseHtml(html).findAll("a").
46 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
47 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
49 proc presentVideoOptions*(searchResults: SearchResults) =
51 for index, (title, url) in searchResults:
52 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
54 proc play*(player: string, args: openArray[string], title: string) =
55 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
56 if "--no-video" in args:
57 discard execShellCmd(&"{player} {args.join(\" \")}")
59 discard execProcess(player, args=args, options=processOptions)
61 func buildMusicDownloadArgs*(url: string): seq[string] =
63 var args = @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o"]
64 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
65 args.add(downloadLocation)
69 func buildVideoDownloadArgs*(url: string): seq[string] =
71 var args = @["-f", "best", "-o"]
72 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
73 args.add(downloadLocation)
77 proc download*(args: openArray[string], title: string) =
78 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
79 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
81 func urlLongen(url: string): string =
82 url.replace("youtu.be/", "www.youtube.com/watch?v=")
84 func stripZshEscaping(url: string): string =
87 func sanitizeURL*(url: string): string =
88 urlLongen(stripZshEscaping(url))
90 proc directPlay*(url: string, player: string, musicOnly: bool) =
91 if url.startswith("magnet:"):
93 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
95 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
98 discard execShellCmd(&"{player} --no-video {url}")
100 discard execProcess(player, args=[url], options=processOptions)
102 proc directDownload*(url: string, musicOnly: bool) =
104 if musicOnly: buildMusicDownloadArgs(url)
105 else: buildVideoDownloadArgs(url)
106 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
108 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
109 if options["feelingLucky"]: "0"
111 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
112 stdout.styledWrite(fgYellow, "Choose video number: ")
115 # This is a pure function with no side effects
116 func buildPlayerArgs(searchResult: SearchResult, options: Table[string, bool]): seq[string] =
117 var args = @[searchResult.url]
118 if options["musicOnly"]: args.add("--no-video")
119 if options["fullScreen"]: args.add("--fullscreen")
122 proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
123 if options["download"]:
124 if options["musicOnly"]:
125 download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
127 download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
129 play(player, buildPlayerArgs(searchResult, options), searchResult.title)
131 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
132 #[ Continuously present options till the user quits the application
133 selectionRange: Currently available range to choose from depending on pagination
136 let userInput = offerSelection(searchResults, options, selectionRange)
140 for selection in selectionRange.begin .. selectionRange.until:
141 handleUserInput(searchResults[selection], options, player)
144 if selectionRange.until + 1 < len(searchResults):
145 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
146 present(searchResults, options, newSelectionRange, player)
148 present(searchResults, options, selectionRange, player)
150 if selectionRange.begin > 0:
151 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
152 present(searchResults, options, newSelectionRange, player)
154 present(searchResults, options, selectionRange, player)
158 handleUserInput(searchResults[parseInt(userInput)], options, player)
159 if options["feelingLucky"]:
162 present(searchResults, options, selectionRange, player)