]> njoseph.me Git - nimcoon.git/blob - cli_tube.nim
Implement video search
[nimcoon.git] / cli_tube.nim
1 import htmlparser
2 import httpClient
3 import os
4 import osproc
5 import strtabs
6 import strutils
7 import uri
8 import xmltree
9 import sequtils, sugar
10
11 # TODO Pretty colors in terminal
12 # import terminal
13
14 # Supported video players in order of preference
15 # TODO Should go into a config file
16 let supported_players = @["mpv", "mplayer", "vlc"]
17
18 proc find_supported_player(): string =
19 for player in supported_players:
20 let player_bin = execProcess("which " & player)
21 if player_bin.len != 0:
22 return strip(player_bin)
23
24 proc get_youtube_page(search_query: string): string =
25 let query_param = encodeUrl(search_query)
26 var client = newHttpClient()
27 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & query_param)
28 # TODO Get rid of temp file or make one temp file per user
29 writeFile("/tmp/cli-tube-page.html", response.body)
30 return "/tmp/cli-tube-page.html"
31
32 proc extract_titles_and_urls(html_file: string): seq[tuple[title: string, url: string]] =
33 loadHtml(html_file).findAll("a").
34 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
35 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
36
37 proc present_video_options(titles_and_urls: seq[tuple[title: string, url: string]]) =
38 for number, (title, url) in titles_and_urls:
39 echo number, ". ", title, "\n", url, "\n"
40
41 present_video_options(
42 extract_titles_and_urls(
43 get_youtube_page(
44 paramStr(1))))