18 SearchResult* = tuple[title: string, url: string]
19 Options* = Table[string, bool]
20 CommandLineOptions* = tuple[searchQuery: string, options: Options]
22 let processOptions = {poStdErrToStdOut, poUsePath}
24 proc selectMediaPlayer*(): string =
25 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
26 if len(availablePlayers) == 0:
27 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
28 raise newException(OSError, "No supported media player found")
30 return availablePlayers[0]
32 proc getYoutubePage*(searchQuery: string): string =
33 let queryParam = encodeUrl(searchQuery)
34 let client = newHttpClient()
35 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
38 func extractTitlesAndUrls*(html: string): seq[SearchResult] =
40 parseHtml(html).findAll("a").
41 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
42 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
44 proc presentVideoOptions*(searchResults: seq[SearchResult]) =
46 for index, (title, url) in searchResults:
47 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
49 proc play*(player: string, args: openArray[string], title: string) =
50 # poEchoCmd can be added to options for debugging
51 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
52 discard execProcess(player, args=args, options=processOptions)
54 func urlLongen(url: string): string =
55 url.replace("youtu.be/", "www.youtube.com/watch?v=")
57 func stripZshEscaping(url: string): string =
60 func sanitizeURL*(url: string): string =
61 urlLongen(stripZshEscaping(url))
63 proc directPlay*(searchQuery: string, player: string) =
64 let url = sanitizeURL(searchQuery)
65 if searchQuery.startswith("magnet:"):
66 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
68 discard execProcess(player, args=[url], options=processOptions)