]>
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, | |
11 | uri, | |
12 | xmltree | |
13 | ||
14 | import config | |
15 | ||
16 | type | |
17 | SearchResult* = tuple[title: string, url: string] | |
18 | CommandLineOptions* = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool] | |
19 | ||
20 | proc selectMediaPlayer*(): string = | |
21 | let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) | |
22 | if len(availablePlayers) == 0: | |
23 | stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}" | |
24 | raise newException(OSError, "No supported media player found") | |
25 | else: | |
26 | return availablePlayers[0] | |
27 | ||
28 | proc getYoutubePage*(searchQuery: string): string = | |
29 | let queryParam = encodeUrl(searchQuery) | |
30 | let client = newHttpClient() | |
31 | let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}") | |
32 | return $response.body | |
33 | ||
4a0587e2 JN |
34 | func extractTitlesAndUrls*(html: string): seq[SearchResult] = |
35 | {.noSideEffect.}: | |
36 | parseHtml(html).findAll("a"). | |
37 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
38 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)] | |
d65a1dcf JN |
39 | |
40 | proc presentVideoOptions*(searchResults: seq[SearchResult]) = | |
41 | echo "" | |
42 | for index, (title, url) in searchResults: | |
43 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
44 | ||
45 | proc play*(player: string, args: openArray[string]) = | |
46 | # poEchoCmd can be added to options for debugging | |
47 | discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath}) | |
48 | quit(0) | |
49 | ||
50 | func urlLongen(url: string): string = | |
51 | url.replace("youtu.be/", "www.youtube.com/watch?v=") | |
52 | ||
53 | func stripZshEscaping(url: string): string = | |
54 | url.replace("\\", "") | |
55 | ||
56 | func sanitizeURL*(url: string): string = | |
57 | urlLongen(stripZshEscaping(url)) | |
58 | ||
59 | proc directPlay*(searchQuery: string, player: string) = | |
fe1a5856 JN |
60 | let url = sanitizeURL(searchQuery) |
61 | if searchQuery.startswith("magnet:"): | |
62 | play("peerflix", args=[url, &"--{player}"]) | |
63 | else: | |
64 | play(player, args=[url]) |