]> njoseph.me Git - nimcoon.git/blobdiff - lib.nim
Better UX for playing all search results
[nimcoon.git] / lib.nim
diff --git a/lib.nim b/lib.nim
index 25669a3666b3c21539a9f10d6d363951c971f276..fe9d5c02cf3070da046176f742b1293b7505a74e 100644 (file)
--- a/lib.nim
+++ b/lib.nim
@@ -17,6 +17,8 @@ type
   SearchResult* = tuple[title: string, url: string]
   CommandLineOptions* = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
 
+let processOptions = {poStdErrToStdOut, poUsePath}
+
 proc selectMediaPlayer*(): string =
   let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
   if len(availablePlayers) == 0:
@@ -31,20 +33,21 @@ proc getYoutubePage*(searchQuery: string): string =
   let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
   return $response.body
 
-proc extractTitlesAndUrls*(html: string): seq[SearchResult] =
-  parseHtml(html).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)]
+func extractTitlesAndUrls*(html: string): seq[SearchResult] =
+  {.noSideEffect.}:
+    parseHtml(html).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"]))
 
 proc presentVideoOptions*(searchResults: seq[SearchResult]) =
   echo ""
   for index, (title, url) in searchResults:
     styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
 
-proc play*(player: string, args: openArray[string]) =
+proc play*(player: string, args: openArray[string], title: string) =
   # poEchoCmd can be added to options for debugging
-  discard execProcess(player, args=args, options={poStdErrToStdOut, poUsePath})
-  quit(0)
+  styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
+  discard execProcess(player, args=args, options=processOptions)
 
 func urlLongen(url: string): string =
   url.replace("youtu.be/", "www.youtube.com/watch?v=")
@@ -56,7 +59,8 @@ func sanitizeURL*(url: string): string =
   urlLongen(stripZshEscaping(url))
 
 proc directPlay*(searchQuery: string, player: string) =
-  if "watch?" in searchQuery or "videos/watch" in searchQuery or "soundcloud.com" in searchQuery:
-    play(player, args=[sanitizeURL(searchQuery)])
-  elif searchQuery.startswith("magnet:"):
-    play("peerflix", args=[searchQuery, &"--{player}"])
+  let url = sanitizeURL(searchQuery)
+  if searchQuery.startswith("magnet:"):
+    discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
+  else:
+    discard execProcess("peerflix", args=[url], options=processOptions)