]> njoseph.me Git - nimcoon.git/blame - src/lib.nim
Shift from youtube-dl to yt-dlp
[nimcoon.git] / src / lib.nim
CommitLineData
d65a1dcf 1import
e9f0c7d0 2 os,
d65a1dcf 3 osproc,
c12cc641 4 re,
d65a1dcf 5 sequtils,
d65a1dcf 6 std/[terminal],
e9f0c7d0 7 strformat,
d65a1dcf 8 strutils,
e08e5cbe 9 tables
d65a1dcf 10
e08e5cbe
JN
11import
12 config,
6697cfd2 13 peertube,
5f9cdfef
JN
14 types,
15 youtube
d65a1dcf 16
b44b6494 17
b44b6494 18let
6697cfd2 19 processOptions = {poStdErrToStdOut, poUsePath} # Add poEchoCmd to debug
b44b6494
JN
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
c12cc641
JN
22
23proc isInstalled(program: string): bool =
24 execProcess("which " & program).len != 0
9e6b8568 25
b44b6494 26
d65a1dcf 27proc selectMediaPlayer*(): string =
c12cc641 28 let availablePlayers = supportedPlayers.filter(isInstalled)
d65a1dcf
JN
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
b44b6494 35
d7f4645c
JN
36proc printTitle(action: string, title: string) =
37 styledEcho "\n", fgGreen, &"{action} ", styleBright, fgMagenta, title
38
39
6697cfd2
JN
40###############
41# URL CLEANUP #
42###############
c12cc641 43
6697cfd2
JN
44func rewriteInvidiousToYouTube*(url: string): string =
45 {.noSideEffect.}:
46 if rewriteInvidiousURLs and url.replace(".", "").contains("invidious"):
47 &"https://www.youtube.com/watch?v={url.split(\"=\")[1]}"
48 else: url
b44b6494 49
d65a1dcf 50
6697cfd2
JN
51func urlLongen(url: string): string =
52 url.replace("youtu.be/", "www.youtube.com/watch?v=")
53
54
55func stripZshEscaping(url: string): string = url.replace("\\", "")
56
57
58func sanitizeURL*(url: string): string =
59 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
60
61
62########
63# PLAY #
64########
a2d28598 65
d36e2201 66func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
046c2cc3
JN
67 let musicOnly = if options["musicOnly"]: "--no-video" else: ""
68 let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
55b0cae7 69 filterIt([url, musicOnly, fullScreen], it != "")
d36e2201 70
b44b6494 71
d36e2201
JN
72proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
73 let args = buildPlayerArgs(url, options, player)
74 if title != "":
d7f4645c 75 printTitle("Playing", title)
e71f26f3
JN
76 if "--no-video" in args:
77 discard execShellCmd(&"{player} {args.join(\" \")}")
78 else:
a2d28598 79 discard execProcess(player, args=args, options=processOptions)
d65a1dcf 80
b44b6494 81
6697cfd2
JN
82proc directPlay*(url: string, player: string, options: Table[string, bool]) =
83 let url =
84 if find(url, PEERTUBE_REGEX) != -1 and "webtorrent".isInstalled:
85 getPeerTubeMagnetLink(url)
86 else: url
87 if url.startswith("magnet:") or url.endswith(".torrent"):
88 if options["musicOnly"]:
89 # TODO Replace with WebTorrent once it supports media player options
90 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
91 else:
92 # WebTorrent is so much faster!
93 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
94 else:
95 play(player, options, url)
96
97
98############
99# DOWNLOAD #
100############
101
b44b6494 102func buildMusicDownloadArgs(url: string): seq[string] =
9a8ef4ad 103 {.noSideEffect.}:
9a8ef4ad 104 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
b44b6494
JN
105 @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3",
106 "--audio-quality", "0", "-o", downloadLocation, url]
107
9a8ef4ad 108
b44b6494 109func buildVideoDownloadArgs(url: string): seq[string] =
9a8ef4ad 110 {.noSideEffect.}:
9a8ef4ad 111 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
55b0cae7 112 @["-f", "best", "-o", downloadLocation, url]
9a8ef4ad 113
b44b6494 114
6697cfd2
JN
115func buildDownloadArgs(url: string, options: Options): seq[string] =
116 if options["musicOnly"]: buildMusicDownloadArgs(url)
117 else: buildVideoDownloadArgs(url)
118
119
e9f0c7d0 120proc download*(args: openArray[string], title: string) =
d7f4645c 121 printTitle("Downloading", title)
f4db2dfe 122 discard execShellCmd(&"yt-dlp {args.join(\" \")}")
e9f0c7d0 123
b44b6494 124
6697cfd2
JN
125proc directDownload*(url: string, options: Options) =
126 let args = buildDownloadArgs(url, options)
127 if "aria2c".isInstalled:
f4db2dfe 128 discard execShellCmd(&"yt-dlp {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'")
0c2f0385 129 else:
f4db2dfe 130 discard execShellCmd(&"yt-dlp {args.join(\" \")}")
13a4017d 131
6697cfd2 132proc luckyDownload*(searchQuery: string, options: Options) =
f4db2dfe
JN
133 let args = @[&"ytsearch1:\"{searchQuery}\""] & buildDownloadArgs("", options)
134 let title = execProcess(&"yt-dlp --get-title {args.join(\" \")}").split("\n")[0]
d7f4645c 135 download(args, title)
b44b6494 136
6697cfd2
JN
137proc luckyPlay*(searchQuery: string, player: string, options: Options) =
138 let args = @[&"ytsearch:\"{searchQuery}\""] & buildDownloadArgs("", options)
f4db2dfe 139 let output = execProcess(&"yt-dlp --get-url --get-title {args.join(\" \")}").split("\n")
d7f4645c
JN
140 let
141 title = output[0]
142 url = &"\"{output[1]}\""
143 play(player, options, url, title)
13a4017d 144
6697cfd2
JN
145###########
146# OPTIONS #
147###########
b44b6494 148
9ed70b9e
JN
149proc isValidOptions*(options: Options): bool =
150 # Check for invalid combinations of options
5f9cdfef 151 var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen"), ("download", "autoPlay")]
9ed70b9e
JN
152 result = true
153 for combination in invalidCombinations:
154 if options[combination[0]] and options[combination[1]]:
155 stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}"
156 result = false
5f9cdfef
JN
157 # TODO Make this overridable in configuration
158 if options["autoPlay"] and not options["musicOnly"]:
159 stderr.writeLine "--music-only must be provided with --auto-play. This is to prevent binge-watching."
160 result = false
9ed70b9e
JN
161
162
163proc updateOptions(options: Options, newOptions: string): Options =
164 result = options
165
5f9cdfef 166 # Interactive options
9ed70b9e
JN
167 for option in newOptions:
168 case option
169 of 'm': result["musicOnly"] = true
170 of 'f': result["fullScreen"] = true
171 of 'd': result["download"] = true
5f9cdfef 172 of 'a': result["autoPlay"] = true
9ed70b9e 173 else:
5f9cdfef 174 stderr.writeLine "Invalid option provided!"
9ed70b9e
JN
175 quit(2)
176
177 if(not isValidOptions(result)):
178 quit(2)
179
180
6697cfd2
JN
181################
182# PRESENTATION #
183################
184
185proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
186 if options["autoPlay"]:
187 play(player, options, searchResult.url, searchResult.title)
188 handleUserInput(getAutoPlayVideo(searchResult), options, player) # inifinite playlist till user quits
189 elif options["download"]:
190 download(buildDownloadArgs(searchResult.url, options), searchResult.title)
191 else:
192 play(player, options, searchResult.url, searchResult.title)
193
194
195proc presentVideoOptions(searchResults: SearchResults) =
196 eraseScreen()
197 for index, (title, url) in searchResults:
198 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
199
200
201proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
202 if options["feelingLucky"]: "0"
203 else:
204 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
205 stdout.styledWrite(fgYellow, "Choose video number: ")
206 readLine(stdin)
207
208
13a4017d 209proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
55b0cae7
JN
210 ##[ Continuously present options till the user quits the application
211
212 selectionRange: Currently available range to choose from depending on pagination
213 ]##
13a4017d
JN
214
215 let userInput = offerSelection(searchResults, options, selectionRange)
216
217 case userInput
218 of "all":
219 for selection in selectionRange.begin .. selectionRange.until:
220 handleUserInput(searchResults[selection], options, player)
221 quit(0)
222 of "n":
223 if selectionRange.until + 1 < len(searchResults):
224 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
225 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
226 else:
227 present(searchResults, options, selectionRange, player)
13a4017d
JN
228 of "p":
229 if selectionRange.begin > 0:
230 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
231 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
232 else:
233 present(searchResults, options, selectionRange, player)
13a4017d
JN
234 of "q":
235 quit(0)
236 else:
9ed70b9e
JN
237 if " " in userInput:
238 let selection = parseInt(userInput.split(" ")[0])
239 let updatedOptions = updateOptions(options, userInput.split(" ")[1])
240 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][selection]
241 handleUserInput(searchResult, updatedOptions, player)
242 else:
243 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
244 handleUserInput(searchResult, options, player)
13a4017d
JN
245 if options["feelingLucky"]:
246 quit(0)
247 else:
248 present(searchResults, options, selectionRange, player)