Add option to download video
[nimcoon.git] / src / nimcoon.nim
index 8b1ba591f166a0545053cc420ecf12149c5847ab..2ddafc94d4384968048b25f2665ea83eb7d413bd 100644 (file)
@@ -1,17 +1,19 @@
 import
+  os,
   parseopt,
   std/[terminal],
-  strutils
+  strformat,
+  strutils,
+  tables
 
 import config
 import lib
 
-proc parseOptions(): CommandLineOptions =
+
+proc parseArguments(): CommandLineOptions =
   var
     searchQuery = ""
-    musicOnly = false
-    feelingLucky = false
-    fullScreen = false
+    options = to_table({"musicOnly": false, "feelingLucky": false, "fullScreen": false, "download": false})
 
   for kind, key, value in getopt():
     case kind
@@ -19,19 +21,32 @@ proc parseOptions(): CommandLineOptions =
       searchQuery = key
     of cmdShortOption, cmdLongOption:
       case key
-      of "m", "music": musicOnly = true
-      of "l", "lucky": feelingLucky = true
-      of "f", "full-screen": fullScreen = true
-    of cmdEnd:
-      discard
+      of "m", "music": options["musicOnly"] = true
+      of "l", "lucky": options["feelingLucky"] = true
+      of "f", "full-screen": options["fullScreen"] = true
+      of "d", "download": options["download"] = true
+    of cmdEnd: discard
+
+  return (searchQuery, options)
 
-  return (searchQuery, musicOnly, feelingLucky, fullScreen)
+
+proc isValidOptions*(options: Options): bool =
+  # Check for invalid combinations of options
+  var invalidCombinations = [("musicOnly", "fullScreen")]
+  for combination in invalidCombinations:
+    if options[combination[0]] and options[combination[1]]:
+     stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}"
+     return false
+  return true
 
 
 proc main() =
   let
     player = selectMediaPlayer()
-    (searchQuery, musicOnly, feelingLucky, fullScreen) = parseOptions()
+    (searchQuery, options) = parseArguments()
+
+  if(not isValidOptions(options)):
+    quit(1)
 
   if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
     directPlay(searchQuery, player)
@@ -40,33 +55,60 @@ proc main() =
   let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
 
   proc getUserInput(): string =
-    if feelingLucky: "0"
+    if options["feelingLucky"]: "0"
     else:
       presentVideoOptions(searchResults[..(limit-1)])
       stdout.styledWrite(fgYellow, "Choose video number: ")
       readLine(stdin)
 
   # This is a pure function with no side effects
-  func buildArgs(number: int): seq[string] =
+  func buildPlayerArgs(number: int): seq[string] =
     var args = @[searchResults[number].url]
-    if musicOnly: args.add("--no-video")
-    if fullScreen: args.add("--fullscreen")
+    if options["musicOnly"]: args.add("--no-video")
+    if options["fullScreen"]: args.add("--fullscreen")
     return args
 
+  func buildMusicDownloadArgs(number: int): seq[string] =
+    {.noSideEffect.}:
+      var args = @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o"]
+      let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/{searchResults[number].title}.mp3'"
+      args.add(downloadLocation)
+      args.add(searchResults[number].url)
+      return args
+
+  func buildVideoDownloadArgs(number: int): seq[string] =
+    {.noSideEffect.}:
+      var args = @["-f", "best", "-o"]
+      let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
+      args.add(downloadLocation)
+      args.add(searchResults[number].url)
+      return args
+
+  proc handleUserInput(number: int) =
+    if options["download"]:
+      if options["musicOnly"]:
+        download(buildMusicDownloadArgs(number), searchResults[number].title)
+      else:
+        download(buildVideoDownloadArgs(number), searchResults[number].title)
+    else:
+      play(player, buildPlayerArgs(number), searchResults[number].title)
+
+
   while(true):
     let userInput = getUserInput()
 
     if userInput == "all":
       for number in 0..(len(searchResults)):
-        play(player, buildArgs(number), searchResults[number].title)
+        # TODO `spawn` this?
+        handleUserInput(number)
 
     if userInput == "q":
       break
 
     # Play the video using the preferred/available media player
     let videoNumber = parseInt(userInput)
-    play(player, buildArgs(videoNumber), searchResults[videoNumber].title)
-    if feelingLucky:
+    handleUserInput(videoNumber)
+    if options["feelingLucky"]:
       break