19 SearchResult = tuple[title: string, url: string]
20 CommandLineOptions = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
22 proc selectMediaPlayer(): string =
23 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
24 if len(availablePlayers) == 0:
25 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
26 raise newException(OSError, "No supported media player found")
28 return availablePlayers[0]
30 proc parseOptions(): CommandLineOptions =
37 for kind, key, value in getopt():
41 of cmdShortOption, cmdLongOption:
43 of "m", "music": musicOnly = true
44 of "l", "lucky": feelingLucky = true
45 of "f", "full-screen": fullScreen = true
49 return (searchQuery, musicOnly, feelingLucky, fullScreen)
51 proc getYoutubePage(searchQuery: string): string =
52 let queryParam = encodeUrl(searchQuery)
53 let client = newHttpClient()
54 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
57 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
58 parseHtml(htmlFile).findAll("a").
59 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
60 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
62 proc presentVideoOptions(searchResults: seq[SearchResult]) =
64 for index, (title, url) in searchResults:
65 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
67 proc play(player: string, args: openArray[string]) =
68 discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath, poEchoCmd})
71 proc directPlay(searchQuery: string, player: string) =
72 if "watch?" in searchQuery or "videos/watch" in searchQuery:
73 play(player, args=[searchQuery])
74 elif searchQuery.startswith("magnet:"):
75 play("peerflix", args=[searchQuery, &"--{player}"])
79 player = selectMediaPlayer()
80 (searchQuery, musicOnly, feelingLucky, fullScreen) = parseOptions()
82 if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
83 directPlay(searchQuery, player)
85 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
90 presentVideoOptions(searchResults)
91 stdout.styledWrite(fgYellow, "Choose video number: ")
92 parseInt(readLine(stdin))
94 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
96 var args = @[searchResults[number].url]
99 args.add(playerOptions[player]["musicOnly"])
102 args.add(playerOptions[player]["fullScreen"])
104 # Play the video using the preferred/available media player