]> njoseph.me Git - nimcoon.git/blobdiff - clitube.nim
Add dependencies list
[nimcoon.git] / clitube.nim
index a1ba868a8c0d5c45e045a4b6885a153c7770a451..cc354483cdba5a8faab5b59c7bac86f32086799f 100644 (file)
@@ -1,51 +1,82 @@
 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"]
-
-# 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)
-  # TODO Get rid of temp file or make one temp file per user
-  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"]))
+    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
+var feelingLucky = false
+
+for kind, key, value in getopt():
+  case kind
+  of cmdArgument:
+     searchQuery = key
+  of cmdShortOption, cmdLongOption:
+    case key
+    of "m", "music": musicOnly = true
+    of "l", "lucky": feelingLucky = true
+  of cmdEnd:
+    discard
+
+
+if "?watch" in searchQuery or "videos/watch" in searchQuery :
+  discard execProcess(&"{player} {searchQuery}")
+  quit(0)
+
+
+let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
+
+let number =
+  if feelingLucky:
+    0
+  else:
+    presentVideoOptions(searchResults)
+    stdout.styledWrite(fgYellow, "Choose video number: ")
+    parseInt(readLine(stdin))
+
+styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, searchResults[number].title
+
+var command = @[player, searchResults[number].url]
+
+if musicOnly:
+  command.add("--no-video")
 
-presentVideoOptions(
-  extractTitlesAndUrls(
-    getYoutubePage(
-      paramStr(1))))
+# Play the video using the preferred/available media player
+discard execProcess(command.join(" "))