]>
Commit | Line | Data |
---|---|---|
1 | import | |
2 | htmlparser, | |
3 | httpClient, | |
4 | os, | |
5 | osproc, | |
6 | sequtils, | |
7 | sugar, | |
8 | strformat, | |
9 | std/[terminal], | |
10 | strformat, | |
11 | strtabs, | |
12 | strutils, | |
13 | tables, | |
14 | uri, | |
15 | xmltree | |
16 | ||
17 | import config | |
18 | ||
19 | type | |
20 | Options* = Table[string, bool] | |
21 | SearchResult* = tuple[title: string, url: string] | |
22 | SearchResults* = seq[tuple[title: string, url: string]] | |
23 | CommandLineOptions* = tuple[searchQuery: string, options: Options] | |
24 | SelectionRange* = tuple[begin: int, until: int] | |
25 | ||
26 | # poEchoCmd can be added to options for debugging | |
27 | let processOptions = {poStdErrToStdOut, poUsePath} | |
28 | ||
29 | proc selectMediaPlayer*(): string = | |
30 | let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) | |
31 | if len(availablePlayers) == 0: | |
32 | stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}" | |
33 | raise newException(OSError, "No supported media player found") | |
34 | else: | |
35 | return availablePlayers[0] | |
36 | ||
37 | proc getYoutubePage*(searchQuery: string): string = | |
38 | let queryParam = encodeUrl(searchQuery) | |
39 | let client = newHttpClient() | |
40 | let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}") | |
41 | return $response.body | |
42 | ||
43 | func extractTitlesAndUrls*(html: string): SearchResults = | |
44 | {.noSideEffect.}: | |
45 | parseHtml(html).findAll("a"). | |
46 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
47 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) | |
48 | ||
49 | proc presentVideoOptions*(searchResults: SearchResults) = | |
50 | eraseScreen() | |
51 | for index, (title, url) in searchResults: | |
52 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
53 | ||
54 | func isPlaylist(url: string): bool = | |
55 | # Only YouTube playlists are supported for now | |
56 | "www.youtube.com" in url and "&list=" in url | |
57 | ||
58 | # This is a pure function with no side effects | |
59 | func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] = | |
60 | var args = @[url] | |
61 | if options["musicOnly"]: args.add("--no-video") | |
62 | if options["fullScreen"]: args.add("--fullscreen") | |
63 | # Playlists are only supported for MPV player | |
64 | if isPlaylist(url) and player == "mpv": | |
65 | args.add("--ytdl-raw-options=\"yes-playlist=\"") | |
66 | return args | |
67 | ||
68 | proc play*(player: string, options: Table[string, bool], url: string, title: string = "") = | |
69 | let args = buildPlayerArgs(url, options, player) | |
70 | if title != "": | |
71 | styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title | |
72 | if "--no-video" in args: | |
73 | discard execShellCmd(&"{player} {args.join(\" \")}") | |
74 | else: | |
75 | discard execProcess(player, args=args, options=processOptions) | |
76 | ||
77 | func buildMusicDownloadArgs*(url: string): seq[string] = | |
78 | {.noSideEffect.}: | |
79 | var args = @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o"] | |
80 | let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'" | |
81 | args.add(downloadLocation) | |
82 | args.add(url) | |
83 | return args | |
84 | ||
85 | func buildVideoDownloadArgs*(url: string): seq[string] = | |
86 | {.noSideEffect.}: | |
87 | var args = @["-f", "best", "-o"] | |
88 | let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'" | |
89 | args.add(downloadLocation) | |
90 | args.add(url) | |
91 | return args | |
92 | ||
93 | proc download*(args: openArray[string], title: string) = | |
94 | styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title | |
95 | discard execShellCmd(&"youtube-dl {args.join(\" \")}") | |
96 | ||
97 | func urlLongen(url: string): string = | |
98 | url.replace("youtu.be/", "www.youtube.com/watch?v=") | |
99 | ||
100 | func stripZshEscaping(url: string): string = | |
101 | url.replace("\\", "") | |
102 | ||
103 | func sanitizeURL*(url: string): string = | |
104 | urlLongen(stripZshEscaping(url)) | |
105 | ||
106 | proc directPlay*(url: string, player: string, options: Table[string, bool]) = | |
107 | if url.startswith("magnet:"): | |
108 | if options["musicOnly"]: | |
109 | discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video") | |
110 | else: | |
111 | discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions) | |
112 | else: | |
113 | play(player, options, url) | |
114 | ||
115 | proc directDownload*(url: string, musicOnly: bool) = | |
116 | let args = | |
117 | if musicOnly: buildMusicDownloadArgs(url) | |
118 | else: buildVideoDownloadArgs(url) | |
119 | discard execShellCmd(&"youtube-dl {args.join(\" \")}") | |
120 | ||
121 | proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string = | |
122 | if options["feelingLucky"]: "0" | |
123 | else: | |
124 | presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until]) | |
125 | stdout.styledWrite(fgYellow, "Choose video number: ") | |
126 | readLine(stdin) | |
127 | ||
128 | proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) = | |
129 | if options["download"]: | |
130 | if options["musicOnly"]: | |
131 | download(buildMusicDownloadArgs(searchResult.url), searchResult.title) | |
132 | else: | |
133 | download(buildVideoDownloadArgs(searchResult.url), searchResult.title) | |
134 | else: | |
135 | play(player, options, searchResult.url, searchResult.title) | |
136 | ||
137 | proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) = | |
138 | #[ Continuously present options till the user quits the application | |
139 | selectionRange: Currently available range to choose from depending on pagination | |
140 | ]# | |
141 | ||
142 | let userInput = offerSelection(searchResults, options, selectionRange) | |
143 | ||
144 | case userInput | |
145 | of "all": | |
146 | for selection in selectionRange.begin .. selectionRange.until: | |
147 | handleUserInput(searchResults[selection], options, player) | |
148 | quit(0) | |
149 | of "n": | |
150 | if selectionRange.until + 1 < len(searchResults): | |
151 | let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit)) | |
152 | present(searchResults, options, newSelectionRange, player) | |
153 | else: | |
154 | present(searchResults, options, selectionRange, player) | |
155 | of "p": | |
156 | if selectionRange.begin > 0: | |
157 | let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit) | |
158 | present(searchResults, options, newSelectionRange, player) | |
159 | else: | |
160 | present(searchResults, options, selectionRange, player) | |
161 | of "q": | |
162 | quit(0) | |
163 | else: | |
164 | let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)] | |
165 | handleUserInput(searchResult, options, player) | |
166 | if options["feelingLucky"]: | |
167 | quit(0) | |
168 | else: | |
169 | present(searchResults, options, selectionRange, player) |