Fix .gitlab-ci.yml
[nimcoon.git] / clitube.nim
CommitLineData
44978125
JN
1import htmlparser
2import httpClient
3import os
4import osproc
2f3c8875 5import sequtils, sugar
44978125
JN
6import strtabs
7import strutils
8import uri
9import xmltree
44978125 10
44978125 11# Supported video players in order of preference
39a495a9 12let supportedPlayers = @["mpv", "mplayer", "vlc"]
44978125 13
2d9a92ad
JN
14# Hard-coded terminal colors
15proc reset(): string {.procvar.} = "\e[0m"
16proc bold*(s: string): string {.procvar.} = "\e[1m" & s & reset()
17
18proc fgMagenta*(s: string): string {.procvar.} = "\e[35m" & s & reset()
19proc fgCyan*(s: string): string {.procvar.} = "\e[36m" & s & reset()
20
2f3c8875
JN
21type SearchResult = tuple[title: string, url: string]
22
933e339b
JN
23proc selectMediaPlayer(): string =
24 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
25 if len(availablePlayers) == 0:
26 echo "Please install one of the supported media players: ", supportedPlayers
27 raise newException(OSError, "No supported media player found")
28 else:
29 return availablePlayers[0]
44978125 30
39a495a9
JN
31proc getYoutubePage(searchQuery: string): string =
32 let queryParam = encodeUrl(searchQuery)
44978125 33 var client = newHttpClient()
39a495a9 34 let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
44978125
JN
35 # TODO Get rid of temp file or make one temp file per user
36 writeFile("/tmp/cli-tube-page.html", response.body)
37 return "/tmp/cli-tube-page.html"
38
2f3c8875 39proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
39a495a9 40 loadHtml(htmlFile).findAll("a").
44978125
JN
41 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
42 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
43
2f3c8875
JN
44proc presentVideoOptions(searchResults: seq[SearchResult]) =
45 for index, (title, url) in searchResults:
2d9a92ad 46 echo index, ". ", title.bold.fgMagenta, "\n", url.fgCyan, "\n"
44978125 47
39a495a9
JN
48presentVideoOptions(
49 extractTitlesAndUrls(
50 getYoutubePage(
44978125 51 paramStr(1))))