]>
Commit | Line | Data |
---|---|---|
1 | import htmlparser | |
2 | import httpClient | |
3 | import os | |
4 | import osproc | |
5 | import sequtils, sugar | |
6 | import strformat | |
7 | import std/[terminal] | |
8 | import strtabs | |
9 | import strutils | |
10 | import uri | |
11 | import xmltree | |
12 | ||
13 | import preferences | |
14 | ||
15 | type SearchResult = tuple[title: string, url: string] | |
16 | ||
17 | proc selectMediaPlayer(): string = | |
18 | let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0) | |
19 | if len(availablePlayers) == 0: | |
20 | stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}" | |
21 | raise newException(OSError, "No supported media player found") | |
22 | else: | |
23 | return availablePlayers[0] | |
24 | ||
25 | proc getYoutubePage(searchQuery: string): string = | |
26 | let queryParam = encodeUrl(searchQuery) | |
27 | let client = newHttpClient() | |
28 | let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}") | |
29 | return $response.body | |
30 | ||
31 | proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] = | |
32 | parseHtml(htmlFile).findAll("a"). | |
33 | filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title"). | |
34 | map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)] | |
35 | ||
36 | proc presentVideoOptions(searchResults: seq[SearchResult]) = | |
37 | echo "" | |
38 | for index, (title, url) in searchResults: | |
39 | styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n" | |
40 | ||
41 | let input = paramStr(1) | |
42 | let player = selectMediaPlayer() | |
43 | ||
44 | if "https://www.youtube.com" in input: | |
45 | discard execProcess(&"{player} {input}") | |
46 | quit(0) | |
47 | ||
48 | let searchResults = extractTitlesAndUrls(getYoutubePage(input)) | |
49 | ||
50 | presentVideoOptions(searchResults) | |
51 | ||
52 | stdout.styledWrite(fgYellow, "Choose video number: ") | |
53 | let number = parseInt(readLine(stdin)) | |
54 | ||
55 | styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title | |
56 | ||
57 | # Play the video using the preferred/available media player | |
58 | discard execProcess(&"{player} {searchResults[number].url}") |