Add option to play music only
[nimcoon.git] / clitube.nim
index 9c14735f1791dab183f824209f9b2c92fd057e4d..3714c13612433ed295690aec1a41063ecfde2110 100644 (file)
@@ -1,62 +1,73 @@
 import htmlparser
 import httpClient
-import os
+import parseopt
 import osproc
 import sequtils, sugar
+import strformat
+import std/[terminal]
 import strtabs
 import strutils
 import uri
 import xmltree
 
-# Supported video players in order of preference
-let supportedPlayers = @["mpv", "mplayer", "vlc"]
-
-# Only show these many results
-let limit = 10
-
-# Hard-coded terminal colors
-proc reset(): string {.procvar.} = "\e[0m"
-proc bold*(s: string): string {.procvar.} = "\e[1m" & s & reset()
-
-proc fgMagenta*(s: string): string {.procvar.} = "\e[35m" & s & reset()
-proc fgCyan*(s: string): string {.procvar.} = "\e[36m" & s & reset()
+import preferences
 
 type SearchResult = tuple[title: string, url: string]
 
 proc selectMediaPlayer(): string =
   let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
   if len(availablePlayers) == 0:
-    echo "Please install one of the supported media players: ", supportedPlayers
+    stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
     raise newException(OSError, "No supported media player found")
   else:
     return availablePlayers[0]
 
 proc getYoutubePage(searchQuery: string): string =
   let queryParam = encodeUrl(searchQuery)
-  var client = newHttpClient()
-  let response = get(client, "https://www.youtube.com/results?hl=en&search_query=" & queryParam)
-  writeFile("/tmp/cli-tube-page.html", response.body)
-  return "/tmp/cli-tube-page.html"
+  let client = newHttpClient()
+  let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
+  return $response.body
 
 proc extractTitlesAndUrls(htmlFile: string): seq[SearchResult] =
-  loadHtml(htmlFile).findAll("a").
+  parseHtml(htmlFile).findAll("a").
     filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
     map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))[..(limit-1)]
 
 proc presentVideoOptions(searchResults: seq[SearchResult]) =
   echo ""
   for index, (title, url) in searchResults:
-    echo index, ". ", title.bold.fgMagenta, "\n", url.fgCyan, "\n"
+    styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
+
+let player = selectMediaPlayer()
+
+var searchQuery = ""
+var musicOnly = false
+
+for kind, key, value in getopt():
+  case kind
+  of cmdArgument:
+     searchQuery = key
+  of cmdShortOption, cmdLongOption:
+    case key
+    of "m", "music": musicOnly = true
+  of cmdEnd:
+    discard
+
+let noVideo = if musicOnly: "--no-video" else: ""
+
+if "https://www.youtube.com" in searchQuery:
+  discard execProcess(&"{player} {searchQuery}")
+  quit(0)
+
 
-let searchResults = extractTitlesAndUrls(getYoutubePage(paramStr(1)))
+let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
 
 presentVideoOptions(searchResults)
 
-stdout.write "Choose video number: "
-var number: int = parseInt(readLine(stdin))
+stdout.styledWrite(fgYellow, "Choose video number: ")
+let number = parseInt(readLine(stdin))
 
-var player = selectMediaPlayer()
-echo "\n", "Playing ", searchResults[number].title.bold.fgMagenta
+styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
 
-# Play the video in the media player
-discard execProcess(player & " " & searchResults[number].url)
+# Play the video using the preferred/available media player
+discard execProcess(&"{player} {noVideo} {searchResults[number].url}")