18 SearchResult = tuple[title: string, url: string]
19 CommandLineOptions = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
21 proc selectMediaPlayer(): string =
22 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
23 if len(availablePlayers) == 0:
24 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
25 raise newException(OSError, "No supported media player found")
27 return availablePlayers[0]
29 proc parseOptions(): CommandLineOptions =
36 for kind, key, value in getopt():
40 of cmdShortOption, cmdLongOption:
42 of "m", "music": musicOnly = true
43 of "l", "lucky": feelingLucky = true
44 of "f", "full-screen": fullScreen = true
48 return (searchQuery, musicOnly, feelingLucky, fullScreen)
50 proc getYoutubePage(searchQuery: string): string =
51 let queryParam = encodeUrl(searchQuery)
52 let client = newHttpClient()
53 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
56 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
57 parseHtml(htmlFile).findAll("a").
58 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
59 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
61 proc presentVideoOptions(searchResults: seq[SearchResult]) =
63 for index, (title, url) in searchResults:
64 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
66 proc play(player: string, args: openArray[string]) =
67 discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath, poEchoCmd})
70 proc directPlay(searchQuery: string, player: string) =
71 if "watch?" in searchQuery or "videos/watch" in searchQuery:
72 play(player, args=[searchQuery])
73 elif searchQuery.startswith("magnet:"):
74 play("peerflix", args=[searchQuery, &"--{player}"])
78 player = selectMediaPlayer()
79 (searchQuery, musicOnly, feelingLucky, fullScreen) = parseOptions()
81 if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
82 directPlay(searchQuery, player)
84 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
89 presentVideoOptions(searchResults)
90 stdout.styledWrite(fgYellow, "Choose video number: ")
91 parseInt(readLine(stdin))
93 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
95 var args = @[searchResults[number].url]
98 args.add("--no-video")
101 args.add("--fullscreen")
103 # Play the video using the preferred/available media player