]> njoseph.me Git - nimcoon.git/blame - src/lib.nim
emacs: Some refactoring
[nimcoon.git] / src / lib.nim
CommitLineData
d65a1dcf 1import
d65a1dcf 2 httpClient,
c12cc641 3 json,
e9f0c7d0 4 os,
d65a1dcf 5 osproc,
c12cc641 6 re,
d65a1dcf 7 sequtils,
d65a1dcf 8 std/[terminal],
e9f0c7d0 9 strformat,
d65a1dcf 10 strutils,
e08e5cbe 11 tables
d65a1dcf 12
e08e5cbe
JN
13import
14 config,
15 types
d65a1dcf 16
b44b6494 17
b44b6494 18let
86e6cb72 19 processOptions = {poStdErrToStdOut, poUsePath} # poEchoCmd can be added to options for debugging
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
c12cc641 36proc getPeerTubeMagnetLink(url: string): string =
86e6cb72 37 ## Gets the magnet link of the best possible resolution from PeerTube
c12cc641
JN
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
b44b6494 46
13a4017d 47proc presentVideoOptions*(searchResults: SearchResults) =
17955bba 48 eraseScreen()
d65a1dcf 49 for index, (title, url) in searchResults:
86e6cb72 50 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, " ", url, "\n"
d65a1dcf 51
d36e2201 52func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
046c2cc3
JN
53 let musicOnly = if options["musicOnly"]: "--no-video" else: ""
54 let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
55b0cae7 55 filterIt([url, musicOnly, fullScreen], it != "")
d36e2201 56
b44b6494 57
d36e2201
JN
58proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
59 let args = buildPlayerArgs(url, options, player)
60 if title != "":
61 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
e71f26f3
JN
62 if "--no-video" in args:
63 discard execShellCmd(&"{player} {args.join(\" \")}")
64 else:
26229fac 65 discard startProcess(player, args=args, options=processOptions)
d65a1dcf 66
b44b6494
JN
67
68func buildMusicDownloadArgs(url: string): seq[string] =
9a8ef4ad 69 {.noSideEffect.}:
9a8ef4ad 70 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
b44b6494
JN
71 @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3",
72 "--audio-quality", "0", "-o", downloadLocation, url]
73
9a8ef4ad 74
b44b6494 75func buildVideoDownloadArgs(url: string): seq[string] =
9a8ef4ad 76 {.noSideEffect.}:
9a8ef4ad 77 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
55b0cae7 78 @["-f", "best", "-o", downloadLocation, url]
9a8ef4ad 79
b44b6494 80
e9f0c7d0
JN
81proc download*(args: openArray[string], title: string) =
82 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
83 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
84
b44b6494 85
55b0cae7 86func urlLongen(url: string): string = url.replace("youtu.be/", "www.youtube.com/watch?v=")
d65a1dcf 87
b44b6494
JN
88
89func rewriteInvidiousToYouTube(url: string): string =
90 {.noSideEffect.}:
91 if rewriteInvidiousURLs: url.replace("invidio.us", "www.youtube.com") else: url
92
93
c30c694e 94func stripZshEscaping(url: string): string = url.replace("\\", "")
d65a1dcf 95
b44b6494
JN
96
97func sanitizeURL*(url: string): string =
98 rewriteInvidiousToYouTube(urlLongen(stripZshEscaping(url)))
99
d65a1dcf 100
d36e2201 101proc directPlay*(url: string, player: string, options: Table[string, bool]) =
c12cc641
JN
102 let url =
103 if find(url, PEERTUBE_REGEX) != -1 and isInstalled("webtorrent"):
104 getPeerTubeMagnetLink(url)
105 else: url
d7688e97 106 if url.startswith("magnet:") or url.endswith(".torrent"):
d36e2201 107 if options["musicOnly"]:
8d06ad69 108 # TODO Replace with WebTorrent once it supports media player options
811928a7
JN
109 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
110 else:
8d06ad69
JN
111 # WebTorrent is so much faster!
112 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
fe1a5856 113 else:
d36e2201 114 play(player, options, url)
811928a7 115
b44b6494 116
811928a7
JN
117proc directDownload*(url: string, musicOnly: bool) =
118 let args =
119 if musicOnly: buildMusicDownloadArgs(url)
120 else: buildVideoDownloadArgs(url)
0c2f0385
JN
121 if isInstalled("aria2c"):
122 discard execShellCmd(&"youtube-dl {args.join(\" \")} --external-downloader aria2c --external-downloader-args '-x 16 -s 16 -k 2M'")
123 else:
124 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
13a4017d 125
b44b6494 126
13a4017d
JN
127proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
128 if options["feelingLucky"]: "0"
129 else:
130 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
131 stdout.styledWrite(fgYellow, "Choose video number: ")
132 readLine(stdin)
133
b44b6494 134
13a4017d
JN
135proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
136 if options["download"]:
137 if options["musicOnly"]:
138 download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
139 else:
140 download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
141 else:
d36e2201 142 play(player, options, searchResult.url, searchResult.title)
13a4017d 143
b44b6494 144
13a4017d 145proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
55b0cae7
JN
146 ##[ Continuously present options till the user quits the application
147
148 selectionRange: Currently available range to choose from depending on pagination
149 ]##
13a4017d
JN
150
151 let userInput = offerSelection(searchResults, options, selectionRange)
152
153 case userInput
154 of "all":
155 for selection in selectionRange.begin .. selectionRange.until:
156 handleUserInput(searchResults[selection], options, player)
157 quit(0)
158 of "n":
159 if selectionRange.until + 1 < len(searchResults):
160 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
161 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
162 else:
163 present(searchResults, options, selectionRange, player)
13a4017d
JN
164 of "p":
165 if selectionRange.begin > 0:
166 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
167 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
168 else:
169 present(searchResults, options, selectionRange, player)
13a4017d
JN
170 of "q":
171 quit(0)
172 else:
db34bbff
JN
173 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
174 handleUserInput(searchResult, options, player)
13a4017d
JN
175 if options["feelingLucky"]:
176 quit(0)
177 else:
178 present(searchResults, options, selectionRange, player)