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