pagination: Fix minor regression
[nimcoon.git] / src / lib.nim
1 import
2 htmlparser,
3 httpClient,
4 os,
5 osproc,
6 sequtils,
7 sugar,
8 strformat,
9 std/[terminal],
10 strformat,
11 strtabs,
12 strutils,
13 tables,
14 uri,
15 xmltree
16
17 import config
18
19 type
20 Options* = Table[string, bool]
21 SearchResult* = tuple[title: string, url: string]
22 SearchResults* = seq[tuple[title: string, url: string]]
23 CommandLineOptions* = tuple[searchQuery: string, options: Options]
24 SelectionRange* = tuple[begin: int, until: int]
25
26 # poEchoCmd can be added to options for debugging
27 let processOptions = {poStdErrToStdOut, poUsePath}
28
29 proc selectMediaPlayer*(): string =
30 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
31 if len(availablePlayers) == 0:
32 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
33 raise newException(OSError, "No supported media player found")
34 else:
35 return availablePlayers[0]
36
37 proc getYoutubePage*(searchQuery: string): string =
38 let queryParam = encodeUrl(searchQuery)
39 let client = newHttpClient()
40 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
41 return $response.body
42
43 func extractTitlesAndUrls*(html: string): SearchResults =
44 {.noSideEffect.}:
45 parseHtml(html).findAll("a").
46 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
47 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
48
49 proc presentVideoOptions*(searchResults: SearchResults) =
50 eraseScreen()
51 for index, (title, url) in searchResults:
52 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
53
54 proc play*(player: string, args: openArray[string], title: string) =
55 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
56 if "--no-video" in args:
57 discard execShellCmd(&"{player} {args.join(\" \")}")
58 else:
59 discard execProcess(player, args=args, options=processOptions)
60
61 func buildMusicDownloadArgs*(url: string): seq[string] =
62 {.noSideEffect.}:
63 var args = @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o"]
64 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
65 args.add(downloadLocation)
66 args.add(url)
67 return args
68
69 func buildVideoDownloadArgs*(url: string): seq[string] =
70 {.noSideEffect.}:
71 var args = @["-f", "best", "-o"]
72 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
73 args.add(downloadLocation)
74 args.add(url)
75 return args
76
77 proc download*(args: openArray[string], title: string) =
78 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
79 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
80
81 func urlLongen(url: string): string =
82 url.replace("youtu.be/", "www.youtube.com/watch?v=")
83
84 func stripZshEscaping(url: string): string =
85 url.replace("\\", "")
86
87 func sanitizeURL*(url: string): string =
88 urlLongen(stripZshEscaping(url))
89
90 proc directPlay*(url: string, player: string, musicOnly: bool) =
91 if url.startswith("magnet:"):
92 if musicOnly:
93 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
94 else:
95 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
96 else:
97 if musicOnly:
98 discard execShellCmd(&"{player} --no-video {url}")
99 else:
100 discard execProcess(player, args=[url], options=processOptions)
101
102 proc directDownload*(url: string, musicOnly: bool) =
103 let args =
104 if musicOnly: buildMusicDownloadArgs(url)
105 else: buildVideoDownloadArgs(url)
106 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
107
108 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
109 if options["feelingLucky"]: "0"
110 else:
111 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
112 stdout.styledWrite(fgYellow, "Choose video number: ")
113 readLine(stdin)
114
115 # This is a pure function with no side effects
116 func buildPlayerArgs(searchResult: SearchResult, options: Table[string, bool]): seq[string] =
117 var args = @[searchResult.url]
118 if options["musicOnly"]: args.add("--no-video")
119 if options["fullScreen"]: args.add("--fullscreen")
120 return args
121
122 proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
123 if options["download"]:
124 if options["musicOnly"]:
125 download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
126 else:
127 download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
128 else:
129 play(player, buildPlayerArgs(searchResult, options), searchResult.title)
130
131 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
132 #[ Continuously present options till the user quits the application
133 selectionRange: Currently available range to choose from depending on pagination
134 ]#
135
136 let userInput = offerSelection(searchResults, options, selectionRange)
137
138 case userInput
139 of "all":
140 for selection in selectionRange.begin .. selectionRange.until:
141 handleUserInput(searchResults[selection], options, player)
142 quit(0)
143 of "n":
144 if selectionRange.until + 1 < len(searchResults):
145 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
146 present(searchResults, options, newSelectionRange, player)
147 else:
148 present(searchResults, options, selectionRange, player)
149 of "p":
150 if selectionRange.begin > 0:
151 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
152 present(searchResults, options, newSelectionRange, player)
153 else:
154 present(searchResults, options, selectionRange, player)
155 of "q":
156 quit(0)
157 else:
158 handleUserInput(searchResults[parseInt(userInput)], options, player)
159 if options["feelingLucky"]:
160 quit(0)
161 else:
162 present(searchResults, options, selectionRange, player)