]> njoseph.me Git - nimcoon.git/blob - src/lib.nim
30334588040993ba0a5c1d5fb900048ad855205c
[nimcoon.git] / src / lib.nim
1 import
2 htmlparser,
3 httpClient,
4 json,
5 os,
6 osproc,
7 re,
8 sequtils,
9 std/[terminal],
10 strformat,
11 strformat,
12 strtabs,
13 strutils,
14 sugar,
15 tables,
16 uri,
17 xmltree
18
19 import config
20
21
22 type
23 Options* = Table[string, bool]
24 SearchResult* = tuple[title: string, url: string]
25 SearchResults* = seq[tuple[title: string, url: string]]
26 CommandLineOptions* = tuple[searchQuery: string, options: Options]
27 SelectionRange* = tuple[begin: int, until: int]
28
29
30 let
31 processOptions = {poStdErrToStdOut, poUsePath} # poEchoCmd can be added to options for debugging
32 PEERTUBE_REGEX = re"videos\/watch\/[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}"
33
34
35 proc isInstalled(program: string): bool =
36 execProcess("which " & program).len != 0
37
38
39 proc selectMediaPlayer*(): string =
40 let availablePlayers = supportedPlayers.filter(isInstalled)
41 if len(availablePlayers) == 0:
42 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
43 raise newException(OSError, "No supported media player found")
44 else:
45 return availablePlayers[0]
46
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 $response.body
53
54
55 proc getPeerTubeMagnetLink(url: string): string =
56 ## Gets the magnet link of the best possible resolution from PeerTube
57 let uuid = url.substr(find(url, PEERTUBE_REGEX) + "videos/watch/".len)
58 let domainName = url.substr(8, find(url, '/', start=8) - 1)
59 let apiURL = &"https://{domainName}/api/v1/videos/{uuid}"
60 let client = newHttpClient()
61 let response = get(client, apiURL)
62 let jsonNode = parseJson($response.body)
63 jsonNode["files"][0]["magnetUri"].getStr()
64
65
66 func extractTitlesAndUrls*(html: string): SearchResults =
67 {.noSideEffect.}:
68 parseHtml(html).findAll("a").
69 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
70 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
71
72
73 proc presentVideoOptions*(searchResults: SearchResults) =
74 eraseScreen()
75 for index, (title, url) in searchResults:
76 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
77
78
79 func isPlaylist(url: string): bool =
80 ##[ Identifies if video is part of a playlist.
81 Only YouTube playlists are supported for now. ]##
82 "www.youtube.com" in url and "&list=" in url
83
84
85 func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
86 let url =
87 # Playlists are only supported by MPV player. VLC needs a plugin.
88 if isPlaylist(url) and player == "mpv":
89 "https://www.youtube.com/playlist?" & url.split('&')[1]
90 else: url
91 let musicOnly = if options["musicOnly"]: "--no-video" else: ""
92 let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
93 filterIt([url, musicOnly, fullScreen], it != "")
94
95
96 proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
97 let args = buildPlayerArgs(url, options, player)
98 if title != "":
99 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
100 if "--no-video" in args:
101 discard execShellCmd(&"{player} {args.join(\" \")}")
102 else:
103 discard execProcess(player, args=args, options=processOptions)
104
105
106 func buildMusicDownloadArgs(url: string): seq[string] =
107 {.noSideEffect.}:
108 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
109 @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3",
110 "--audio-quality", "0", "-o", downloadLocation, url]
111
112
113 func buildVideoDownloadArgs(url: string): seq[string] =
114 {.noSideEffect.}:
115 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
116 @["-f", "best", "-o", downloadLocation, url]
117
118
119 proc download*(args: openArray[string], title: string) =
120 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
121 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
122
123
124 func urlLongen(url: string): string = url.replace("youtu.be/", "www.youtube.com/watch?v=")
125
126
127 func rewriteInvidiousToYouTube(url: string): string =
128 {.noSideEffect.}:
129 if rewriteInvidiousURLs: url.replace("invidio.us", "www.youtube.com") else: url
130
131
132 func stripZshEscaping(url: string): string = url.replace("\\", "")
133
134
135 func sanitizeURL*(url: string): string =
136 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
137
138
139 proc directPlay*(url: string, player: string, options: Table[string, bool]) =
140 let url =
141 if find(url, PEERTUBE_REGEX) != -1 and isInstalled("webtorrent"):
142 getPeerTubeMagnetLink(url)
143 else: url
144 if url.startswith("magnet:") or url.endswith(".torrent"):
145 if options["musicOnly"]:
146 # TODO Replace with WebTorrent once it supports media player options
147 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
148 else:
149 # WebTorrent is so much faster!
150 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
151 else:
152 play(player, options, url)
153
154
155 proc directDownload*(url: string, musicOnly: bool) =
156 let args =
157 if musicOnly: buildMusicDownloadArgs(url)
158 else: buildVideoDownloadArgs(url)
159 if isInstalled("aria2c"):
160 discard execShellCmd(&"youtube-dl {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'")
161 else:
162 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
163
164
165 proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
166 if options["feelingLucky"]: "0"
167 else:
168 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
169 stdout.styledWrite(fgYellow, "Choose video number: ")
170 readLine(stdin)
171
172
173 proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
174 if options["download"]:
175 if options["musicOnly"]:
176 download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
177 else:
178 download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
179 else:
180 play(player, options, searchResult.url, searchResult.title)
181
182
183 proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
184 ##[ Continuously present options till the user quits the application
185
186 selectionRange: Currently available range to choose from depending on pagination
187 ]##
188
189 let userInput = offerSelection(searchResults, options, selectionRange)
190
191 case userInput
192 of "all":
193 for selection in selectionRange.begin .. selectionRange.until:
194 handleUserInput(searchResults[selection], options, player)
195 quit(0)
196 of "n":
197 if selectionRange.until + 1 < len(searchResults):
198 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
199 present(searchResults, options, newSelectionRange, player)
200 else:
201 present(searchResults, options, selectionRange, player)
202 of "p":
203 if selectionRange.begin > 0:
204 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
205 present(searchResults, options, newSelectionRange, player)
206 else:
207 present(searchResults, options, selectionRange, player)
208 of "q":
209 quit(0)
210 else:
211 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
212 handleUserInput(searchResult, options, player)
213 if options["feelingLucky"]:
214 quit(0)
215 else:
216 present(searchResults, options, selectionRange, player)