Consolidate playing into one function
[nimcoon.git] / clitube.nim
1 import
2 htmlparser,
3 httpClient,
4 logging,
5 parseopt,
6 osproc,
7 sequtils,
8 sugar,
9 strformat,
10 std/[terminal],
11 strtabs,
12 strutils,
13 uri,
14 xmltree
15
16 import preferences
17
18 type
19 SearchResult = tuple[title: string, url: string]
20 CommandLineOptions = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool]
21
22 let logger = newConsoleLogger()
23 setLogFilter(lvlInfo)
24
25 proc selectMediaPlayer(): string =
26 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
27 if len(availablePlayers) == 0:
28 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
29 raise newException(OSError, "No supported media player found")
30 else:
31 return availablePlayers[0]
32
33 proc parseOptions(): CommandLineOptions =
34 var
35 searchQuery = ""
36 musicOnly = false
37 feelingLucky = false
38
39 for kind, key, value in getopt():
40 case kind
41 of cmdArgument:
42 searchQuery = key
43 of cmdShortOption, cmdLongOption:
44 case key
45 of "m", "music": musicOnly = true
46 of "l", "lucky": feelingLucky = true
47 of cmdEnd:
48 discard
49
50 return (searchQuery, musicOnly, feelingLucky)
51
52 proc getYoutubePage(searchQuery: string): string =
53 let queryParam = encodeUrl(searchQuery)
54 let client = newHttpClient()
55 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
56 return $response.body
57
58 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
59 parseHtml(htmlFile).findAll("a").
60 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
61 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
62
63 proc presentVideoOptions(searchResults: seq[SearchResult]) =
64 echo ""
65 for index, (title, url) in searchResults:
66 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
67
68 proc play(command: string) =
69 logger.log(lvlDebug, &"Executing: ${command}")
70 discard execProcess(command)
71 quit(0)
72
73 proc directPlay(searchQuery: string, player: string) =
74 if "watch?" in searchQuery or "videos/watch" in searchQuery :
75 play(&"{player} {searchQuery}")
76 elif searchQuery.startswith("magnet:"):
77 play(&"peerflix \"{searchQuery}\" --{player}")
78
79 proc main() =
80 let
81 player = selectMediaPlayer()
82 (searchQuery, musicOnly, feelingLucky) = parseOptions()
83
84 directPlay(searchQuery, player)
85
86 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
87
88 let number =
89 if feelingLucky: 0
90 else:
91 presentVideoOptions(searchResults)
92 stdout.styledWrite(fgYellow, "Choose video number: ")
93 parseInt(readLine(stdin))
94
95 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
96
97 var command = @[player, searchResults[number].url]
98
99 if musicOnly:
100 command.add("--no-video")
101
102 # Play the video using the preferred/available media player
103 play(command.join(" "))
104
105 main()