]>
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 | ||
34 | proc extractTitlesAndUrls*(html: string): seq[SearchResult] = | |
35 | parseHtml(html).findAll("a"). | |
36 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
37 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)] | |
38 | ||
39 | proc presentVideoOptions*(searchResults: seq[SearchResult]) = | |
40 | echo "" | |
41 | for index, (title, url) in searchResults: | |
42 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
43 | ||
44 | proc play*(player: string, args: openArray[string]) = | |
45 | # poEchoCmd can be added to options for debugging | |
46 | discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath}) | |
47 | quit(0) | |
48 | ||
49 | func urlLongen(url: string): string = | |
50 | url.replace("youtu.be/", "www.youtube.com/watch?v=") | |
51 | ||
52 | func stripZshEscaping(url: string): string = | |
53 | url.replace("\\", "") | |
54 | ||
55 | func sanitizeURL*(url: string): string = | |
56 | urlLongen(stripZshEscaping(url)) | |
57 | ||
58 | proc directPlay*(searchQuery: string, player: string) = | |
59 | if "watch?" in searchQuery or "videos/watch" in searchQuery or "soundcloud.com" in searchQuery: | |
60 | play(player, args=[sanitizeURL(searchQuery)]) | |
61 | elif searchQuery.startswith("magnet:"): | |
62 | play("peerflix", args=[searchQuery, &"--{player}"]) |