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