]> njoseph.me Git - nimcoon.git/blobdiff - src/lib.nim
PeerTube: Pick magnet link of the best resolution
[nimcoon.git] / src / lib.nim
index c737f0242ef157c4d6560865f2979a1a201e24a1..26df76293947f83968d4e318d2b8883246357d80 100644 (file)
@@ -1,26 +1,39 @@
 import
   htmlparser,
   httpClient,
+  json,
+  os,
   osproc,
+  re,
   sequtils,
-  sugar,
-  strformat,
   std/[terminal],
+  strformat,
+  strformat,
   strtabs,
   strutils,
+  sugar,
+  tables,
   uri,
   xmltree
 
 import config
 
 type
+  Options* = Table[string, bool]
   SearchResult* = tuple[title: string, url: string]
-  CommandLineOptions* = tuple[searchQuery: string, musicOnly: bool, feelingLucky: bool, fullScreen: bool]
+  SearchResults* = seq[tuple[title: string, url: string]]
+  CommandLineOptions* = tuple[searchQuery: string, options: Options]
+  SelectionRange* = tuple[begin: int, until: int]
 
+# poEchoCmd can be added to options for debugging
 let processOptions = {poStdErrToStdOut, poUsePath}
+let PEERTUBE_REGEX = re"videos\/watch\/[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}"
+
+proc isInstalled(program: string): bool =
+  execProcess("which " & program).len != 0
 
 proc selectMediaPlayer*(): string =
-  let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
+  let availablePlayers = supportedPlayers.filter(isInstalled)
   if len(availablePlayers) == 0:
     stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
     raise newException(OSError, "No supported media player found")
@@ -33,21 +46,65 @@ proc getYoutubePage*(searchQuery: string): string =
   let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
   return $response.body
 
-func extractTitlesAndUrls*(html: string): seq[SearchResult] =
+proc getPeerTubeMagnetLink(url: string): string =
+  # Gets the magnet link of the best possible resolutino from PeerTube
+  let uuid = url.substr(find(url, PEERTUBE_REGEX) + "videos/watch/".len)
+  let domainName = url.substr(8, find(url, '/', start=8) - 1)
+  let apiURL = &"https://{domainName}/api/v1/videos/{uuid}"
+  let client = newHttpClient()
+  let response = get(client, apiURL)
+  let jsonNode = parseJson($response.body)
+  jsonNode["files"][0]["magnetUri"].getStr()
+
+func extractTitlesAndUrls*(html: string): SearchResults =
   {.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]) =
+proc presentVideoOptions*(searchResults: SearchResults) =
   eraseScreen()
   for index, (title, url) in searchResults:
     styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
 
-proc play*(player: string, args: openArray[string], title: string) =
-  # poEchoCmd can be added to options for debugging
-  styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
-  discard execProcess(player, args=args, options=processOptions)
+func isPlaylist(url: string): bool =
+  # Identifies if video is part of a playlist
+  # Only YouTube playlists are supported for now
+  "www.youtube.com" in url and "&list=" in url
+
+# This is a pure function with no side effects
+func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
+  let url =
+    # Playlists are only supported for MPV player
+    if isPlaylist(url) and player == "mpv":
+      "https://www.youtube.com/playlist?" & url.split('&')[1]
+    else: url
+  let musicOnly = if options["musicOnly"]: "--no-video" else: ""
+  let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
+  return filterIt([url, musicOnly, fullScreen], it != "")
+
+proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
+  let args = buildPlayerArgs(url, options, player)
+  if title != "":
+    styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
+  if "--no-video" in args:
+    discard execShellCmd(&"{player} {args.join(\" \")}")
+  else:
+    discard execProcess(player, args=args, options=processOptions)
+
+func buildMusicDownloadArgs*(url: string): seq[string] =
+  {.noSideEffect.}:
+    let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
+    return @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o", downloadLocation, url]
+
+func buildVideoDownloadArgs*(url: string): seq[string] =
+  {.noSideEffect.}:
+    let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
+    return @["-f", "best", "-o", downloadLocation, url]
+
+proc download*(args: openArray[string], title: string) =
+  styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
+  discard execShellCmd(&"youtube-dl {args.join(\" \")}")
 
 func urlLongen(url: string): string =
   url.replace("youtu.be/", "www.youtube.com/watch?v=")
@@ -58,9 +115,73 @@ func stripZshEscaping(url: string): string =
 func sanitizeURL*(url: string): string =
   urlLongen(stripZshEscaping(url))
 
-proc directPlay*(searchQuery: string, player: string) =
-  let url = sanitizeURL(searchQuery)
-  if searchQuery.startswith("magnet:"):
-    discard execProcess("peerflix", args=[url, &"--{player}"], options=processOptions)
+proc directPlay*(url: string, player: string, options: Table[string, bool]) =
+  let url =
+    if find(url, PEERTUBE_REGEX) != -1 and isInstalled("webtorrent"):
+      getPeerTubeMagnetLink(url)
+    else: url
+  if url.startswith("magnet:") or url.endswith(".torrent"):
+    if options["musicOnly"]:
+      # TODO Replace with WebTorrent once it supports media player options
+      discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
+    else:
+      # WebTorrent is so much faster!
+      discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
+  else:
+    play(player, options, url)
+
+proc directDownload*(url: string, musicOnly: bool) =
+  let args =
+    if musicOnly: buildMusicDownloadArgs(url)
+    else: buildVideoDownloadArgs(url)
+  discard execShellCmd(&"youtube-dl {args.join(\" \")}")
+
+proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
+  if options["feelingLucky"]: "0"
+  else:
+    presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
+    stdout.styledWrite(fgYellow, "Choose video number: ")
+    readLine(stdin)
+
+proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
+  if options["download"]:
+    if options["musicOnly"]:
+      download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
+    else:
+      download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
+  else:
+    play(player, options, searchResult.url, searchResult.title)
+
+proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
+  #[ Continuously present options till the user quits the application
+       selectionRange: Currently available range to choose from depending on pagination
+  ]#
+
+  let userInput = offerSelection(searchResults, options, selectionRange)
+
+  case userInput
+  of "all":
+    for selection in selectionRange.begin .. selectionRange.until:
+      handleUserInput(searchResults[selection], options, player)
+    quit(0)
+  of "n":
+    if selectionRange.until + 1 < len(searchResults):
+      let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
+      present(searchResults, options, newSelectionRange, player)
+    else:
+      present(searchResults, options, selectionRange, player)
+  of "p":
+    if selectionRange.begin > 0:
+      let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
+      present(searchResults, options, newSelectionRange, player)
+    else:
+      present(searchResults, options, selectionRange, player)
+  of "q":
+    quit(0)
   else:
-    discard execProcess(player, args=[url], options=processOptions)
+    let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
+    handleUserInput(searchResult, options, player)
+    if options["feelingLucky"]:
+      quit(0)
+    else:
+      present(searchResults, options, selectionRange, player)