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