]> njoseph.me Git - nimcoon.git/blame - src/lib.nim
pagination: Fix minor regression
[nimcoon.git] / src / lib.nim
CommitLineData
d65a1dcf
JN
1import
2 htmlparser,
3 httpClient,
e9f0c7d0 4 os,
d65a1dcf
JN
5 osproc,
6 sequtils,
7 sugar,
8 strformat,
9 std/[terminal],
e9f0c7d0 10 strformat,
d65a1dcf
JN
11 strtabs,
12 strutils,
6f161e0b 13 tables,
d65a1dcf
JN
14 uri,
15 xmltree
16
17import config
18
19type
6f161e0b 20 Options* = Table[string, bool]
e9f0c7d0 21 SearchResult* = tuple[title: string, url: string]
13a4017d 22 SearchResults* = seq[tuple[title: string, url: string]]
6f161e0b 23 CommandLineOptions* = tuple[searchQuery: string, options: Options]
e6561dc9 24 SelectionRange* = tuple[begin: int, until: int]
d65a1dcf 25
e9f0c7d0 26# poEchoCmd can be added to options for debugging
e4a68706 27let processOptions = {poStdErrToStdOut, poUsePath}
9e6b8568 28
d65a1dcf
JN
29proc 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
37proc 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
13a4017d 43func extractTitlesAndUrls*(html: string): SearchResults =
4a0587e2
JN
44 {.noSideEffect.}:
45 parseHtml(html).findAll("a").
46 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
72720bec 47 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
d65a1dcf 48
13a4017d 49proc presentVideoOptions*(searchResults: SearchResults) =
17955bba 50 eraseScreen()
d65a1dcf
JN
51 for index, (title, url) in searchResults:
52 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
53
9e6b8568 54proc play*(player: string, args: openArray[string], title: string) =
9e6b8568 55 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
e71f26f3
JN
56 if "--no-video" in args:
57 discard execShellCmd(&"{player} {args.join(\" \")}")
58 else:
59 discard execProcess(player, args=args, options=processOptions)
d65a1dcf 60
9a8ef4ad
JN
61func 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
69func 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
e9f0c7d0
JN
77proc download*(args: openArray[string], title: string) =
78 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
79 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
80
d65a1dcf
JN
81func urlLongen(url: string): string =
82 url.replace("youtu.be/", "www.youtube.com/watch?v=")
83
84func stripZshEscaping(url: string): string =
85 url.replace("\\", "")
86
87func sanitizeURL*(url: string): string =
88 urlLongen(stripZshEscaping(url))
89
811928a7 90proc directPlay*(url: string, player: string, musicOnly: bool) =
9a8ef4ad 91 if url.startswith("magnet:"):
811928a7
JN
92 if musicOnly:
93 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
94 else:
95 discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
fe1a5856 96 else:
811928a7
JN
97 if musicOnly:
98 discard execShellCmd(&"{player} --no-video {url}")
99 else:
100 discard execProcess(player, args=[url], options=processOptions)
101
102proc directDownload*(url: string, musicOnly: bool) =
103 let args =
104 if musicOnly: buildMusicDownloadArgs(url)
105 else: buildVideoDownloadArgs(url)
9a8ef4ad 106 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
13a4017d
JN
107
108proc 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
116func 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
122proc 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
131proc 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)
ebae91b4
JN
147 else:
148 present(searchResults, options, selectionRange, player)
13a4017d
JN
149 of "p":
150 if selectionRange.begin > 0:
151 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
152 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
153 else:
154 present(searchResults, options, selectionRange, player)
13a4017d
JN
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)