]> njoseph.me Git - nimcoon.git/blame - clitube.nim
Get rid of all global state mutation
[nimcoon.git] / clitube.nim
CommitLineData
6ff2dbac
JN
1import
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
44978125 14
2f0b8428 15import preferences
c760b5d9 16
121e06b2
JN
17type
18 SearchResult = tuple[title: string, url: string]
19 CommandLineOptions = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool]
2f3c8875 20
933e339b
JN
21proc selectMediaPlayer(): string =
22 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
23 if len(availablePlayers) == 0:
b40b7243 24 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
933e339b
JN
25 raise newException(OSError, "No supported media player found")
26 else:
27 return availablePlayers[0]
44978125 28
121e06b2
JN
29proc 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
39a495a9
JN
48proc getYoutubePage(searchQuery: string): string =
49 let queryParam = encodeUrl(searchQuery)
485b1053 50 let client = newHttpClient()
b40b7243 51 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
485b1053 52 return $response.body
44978125 53
2f3c8875 54proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
485b1053 55 parseHtml(htmlFile).findAll("a").
44978125 56 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
c760b5d9 57 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
44978125 58
2f3c8875 59proc presentVideoOptions(searchResults: seq[SearchResult]) =
efcc0441 60 echo ""
2f3c8875 61 for index, (title, url) in searchResults:
3d5bf3fd 62 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
44978125 63
121e06b2
JN
64proc 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
73proc 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
efcc0441 90
121e06b2 91 var command = @[player, searchResults[number].url]
efcc0441 92
121e06b2
JN
93 if musicOnly:
94 command.add("--no-video")
a2319a3f 95
121e06b2
JN
96 # Play the video using the preferred/available media player
97 discard execProcess(command.join(" "))
a2319a3f 98
121e06b2 99main()