f69813dbf4566702e67cacd161e6ca545e80e026
[nimcoon.git] / nimcoon.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, fullScreen: 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 fullScreen = false
39
40 for kind, key, value in getopt():
41 case kind
42 of cmdArgument:
43 searchQuery = key
44 of cmdShortOption, cmdLongOption:
45 case key
46 of "m", "music": musicOnly = true
47 of "l", "lucky": feelingLucky = true
48 of "f", "full-screen": fullScreen = true
49 of cmdEnd:
50 discard
51
52 return (searchQuery, musicOnly, feelingLucky, fullScreen)
53
54 proc getYoutubePage(searchQuery: string): string =
55 let queryParam = encodeUrl(searchQuery)
56 let client = newHttpClient()
57 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
58 return $response.body
59
60 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
61 parseHtml(htmlFile).findAll("a").
62 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
63 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
64
65 proc presentVideoOptions(searchResults: seq[SearchResult]) =
66 echo ""
67 for index, (title, url) in searchResults:
68 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
69
70 proc play(command: string) =
71 logger.log(lvlDebug, &"Executing: ${command}")
72 discard execProcess(command)
73 quit(0)
74
75 proc directPlay(searchQuery: string, player: string) =
76 if "watch?" in searchQuery or "videos/watch" in searchQuery :
77 play(&"{player} {searchQuery}")
78 elif searchQuery.startswith("magnet:"):
79 play(&"peerflix \"{searchQuery}\" --{player}")
80
81 proc main() =
82 let
83 player = selectMediaPlayer()
84 (searchQuery, musicOnly, feelingLucky, fullScreen) = parseOptions()
85
86 if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
87 directPlay(searchQuery, player)
88
89 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
90
91 let number =
92 if feelingLucky: 0
93 else:
94 presentVideoOptions(searchResults)
95 stdout.styledWrite(fgYellow, "Choose video number: ")
96 parseInt(readLine(stdin))
97
98 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
99
100 var command = @[player, searchResults[number].url]
101
102 if musicOnly:
103 command.add("--no-video")
104
105 if fullScreen:
106 if player == "cvlc":
107 command.add("--fullscreen")
108 if player == "mpv":
109 command.add("--fs")
110
111 # Play the video using the preferred/available media player
112 play(command.join(" "))
113
114 main()