]>
Commit | Line | Data |
---|---|---|
d65a1dcf JN |
1 | import |
2 | htmlparser, | |
3 | httpClient, | |
e9f0c7d0 | 4 | os, |
d65a1dcf JN |
5 | osproc, |
6 | sequtils, | |
7 | sugar, | |
8 | strformat, | |
9 | std/[terminal], | |
e9f0c7d0 | 10 | strformat, |
d65a1dcf JN |
11 | strtabs, |
12 | strutils, | |
6f161e0b | 13 | tables, |
d65a1dcf JN |
14 | uri, |
15 | xmltree | |
16 | ||
17 | import config | |
18 | ||
19 | type | |
6f161e0b | 20 | Options* = Table[string, bool] |
e9f0c7d0 | 21 | SearchResult* = tuple[title: string, url: string] |
13a4017d | 22 | SearchResults* = seq[tuple[title: string, url: string]] |
6f161e0b | 23 | CommandLineOptions* = tuple[searchQuery: string, options: Options] |
e6561dc9 | 24 | SelectionRange* = tuple[begin: int, until: int] |
d65a1dcf | 25 | |
e9f0c7d0 | 26 | # poEchoCmd can be added to options for debugging |
e4a68706 | 27 | let processOptions = {poStdErrToStdOut, poUsePath} |
9e6b8568 | 28 | |
d65a1dcf JN |
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 | ||
13a4017d | 43 | func extractTitlesAndUrls*(html: string): SearchResults = |
4a0587e2 JN |
44 | {.noSideEffect.}: |
45 | parseHtml(html).findAll("a"). | |
46 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
72720bec | 47 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) |
d65a1dcf | 48 | |
13a4017d | 49 | proc presentVideoOptions*(searchResults: SearchResults) = |
17955bba | 50 | eraseScreen() |
d65a1dcf JN |
51 | for index, (title, url) in searchResults: |
52 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
53 | ||
d36e2201 JN |
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 | |
e71f26f3 JN |
72 | if "--no-video" in args: |
73 | discard execShellCmd(&"{player} {args.join(\" \")}") | |
74 | else: | |
75 | discard execProcess(player, args=args, options=processOptions) | |
d65a1dcf | 76 | |
9a8ef4ad JN |
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 | ||
e9f0c7d0 JN |
93 | proc download*(args: openArray[string], title: string) = |
94 | styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title | |
95 | discard execShellCmd(&"youtube-dl {args.join(\" \")}") | |
96 | ||
d65a1dcf JN |
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 | ||
d36e2201 | 106 | proc directPlay*(url: string, player: string, options: Table[string, bool]) = |
9a8ef4ad | 107 | if url.startswith("magnet:"): |
d36e2201 | 108 | if options["musicOnly"]: |
811928a7 JN |
109 | discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video") |
110 | else: | |
111 | discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions) | |
fe1a5856 | 112 | else: |
d36e2201 | 113 | play(player, options, url) |
811928a7 JN |
114 | |
115 | proc directDownload*(url: string, musicOnly: bool) = | |
116 | let args = | |
117 | if musicOnly: buildMusicDownloadArgs(url) | |
118 | else: buildVideoDownloadArgs(url) | |
9a8ef4ad | 119 | discard execShellCmd(&"youtube-dl {args.join(\" \")}") |
13a4017d JN |
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 | ||
13a4017d JN |
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: | |
d36e2201 | 135 | play(player, options, searchResult.url, searchResult.title) |
13a4017d JN |
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) | |
ebae91b4 JN |
153 | else: |
154 | present(searchResults, options, selectionRange, player) | |
13a4017d JN |
155 | of "p": |
156 | if selectionRange.begin > 0: | |
157 | let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit) | |
158 | present(searchResults, options, newSelectionRange, player) | |
ebae91b4 JN |
159 | else: |
160 | present(searchResults, options, selectionRange, player) | |
13a4017d JN |
161 | of "q": |
162 | quit(0) | |
163 | else: | |
db34bbff JN |
164 | let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)] |
165 | handleUserInput(searchResult, options, player) | |
13a4017d JN |
166 | if options["feelingLucky"]: |
167 | quit(0) | |
168 | else: | |
169 | present(searchResults, options, selectionRange, player) |