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