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