]>
Commit | Line | Data |
---|---|---|
d65a1dcf JN |
1 | import |
2 | htmlparser, | |
3 | httpClient, | |
4 | osproc, | |
5 | sequtils, | |
6 | sugar, | |
7 | strformat, | |
8 | std/[terminal], | |
9 | strtabs, | |
10 | strutils, | |
6f161e0b | 11 | tables, |
d65a1dcf JN |
12 | uri, |
13 | xmltree | |
14 | ||
15 | import config | |
16 | ||
17 | type | |
18 | SearchResult* = tuple[title: string, url: string] | |
6f161e0b JN |
19 | Options* = Table[string, bool] |
20 | CommandLineOptions* = tuple[searchQuery: string, options: Options] | |
d65a1dcf | 21 | |
9e6b8568 JN |
22 | let processOptions = {poStdErrToStdOut, poUsePath} |
23 | ||
d65a1dcf JN |
24 | proc selectMediaPlayer*(): string = |
25 | let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) | |
26 | if len(availablePlayers) == 0: | |
27 | stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}" | |
28 | raise newException(OSError, "No supported media player found") | |
29 | else: | |
30 | return availablePlayers[0] | |
31 | ||
32 | proc getYoutubePage*(searchQuery: string): string = | |
33 | let queryParam = encodeUrl(searchQuery) | |
34 | let client = newHttpClient() | |
35 | let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}") | |
36 | return $response.body | |
37 | ||
4a0587e2 JN |
38 | func extractTitlesAndUrls*(html: string): seq[SearchResult] = |
39 | {.noSideEffect.}: | |
40 | parseHtml(html).findAll("a"). | |
41 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
72720bec | 42 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"])) |
d65a1dcf JN |
43 | |
44 | proc presentVideoOptions*(searchResults: seq[SearchResult]) = | |
17955bba | 45 | eraseScreen() |
d65a1dcf JN |
46 | for index, (title, url) in searchResults: |
47 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
48 | ||
9e6b8568 | 49 | proc play*(player: string, args: openArray[string], title: string) = |
d65a1dcf | 50 | # poEchoCmd can be added to options for debugging |
9e6b8568 JN |
51 | styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title |
52 | discard execProcess(player, args=args, options=processOptions) | |
d65a1dcf JN |
53 | |
54 | func urlLongen(url: string): string = | |
55 | url.replace("youtu.be/", "www.youtube.com/watch?v=") | |
56 | ||
57 | func stripZshEscaping(url: string): string = | |
58 | url.replace("\\", "") | |
59 | ||
60 | func sanitizeURL*(url: string): string = | |
61 | urlLongen(stripZshEscaping(url)) | |
62 | ||
63 | proc directPlay*(searchQuery: string, player: string) = | |
fe1a5856 JN |
64 | let url = sanitizeURL(searchQuery) |
65 | if searchQuery.startswith("magnet:"): | |
9e6b8568 | 66 | discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions) |
fe1a5856 | 67 | else: |
3ba7018e | 68 | discard execProcess(player, args=[url], options=processOptions) |