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