13 proc parseArguments(): CommandLineOptions =
16 options = to_table({"musicOnly": false, "feelingLucky": false, "fullScreen": false, "download": false})
18 for kind, key, value in getopt():
22 of cmdShortOption, cmdLongOption:
24 of "m", "music": options["musicOnly"] = true
25 of "l", "lucky": options["feelingLucky"] = true
26 of "f", "full-screen": options["fullScreen"] = true
27 of "d", "download": options["download"] = true
30 return (searchQuery, options)
33 proc isValidOptions*(options: Options): bool =
34 # Check for invalid combinations of options
35 var invalidCombinations = [("musicOnly", "fullScreen"), ("download", "fullScreen")]
36 for combination in invalidCombinations:
37 if options[combination[0]] and options[combination[1]]:
38 stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}"
45 player = selectMediaPlayer()
46 (searchQuery, options) = parseArguments()
48 if(not isValidOptions(options)):
51 if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
52 if options["download"]:
53 directDownload(sanitizeURL(searchQuery), options["musicOnly"])
55 directPlay(sanitizeURL(searchQuery), player, options["musicOnly"])
58 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
60 # Currently available range to choose from depending on pagination
61 var selectionRange: SelectionRange = (0, limit-1) # Nim decided to deviate from Python ranges here
63 proc offerSelection(): string =
64 if options["feelingLucky"]: "0"
66 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
67 stdout.styledWrite(fgYellow, "Choose video number: ")
70 # This is a pure function with no side effects
71 func buildPlayerArgs(number: int): seq[string] =
72 var args = @[searchResults[number].url]
73 if options["musicOnly"]: args.add("--no-video")
74 if options["fullScreen"]: args.add("--fullscreen")
77 proc handleUserInput(selection: int) =
78 if options["download"]:
79 if options["musicOnly"]:
80 download(buildMusicDownloadArgs(searchResults[selection].url), searchResults[selection].title)
82 download(buildVideoDownloadArgs(searchResults[selection].url), searchResults[selection].title)
84 play(player, buildPlayerArgs(selection), searchResults[selection].title)
88 let userInput = offerSelection()
92 for selection in selectionRange.begin .. selectionRange.until:
94 handleUserInput(selection)
96 if selectionRange.until + 1 < len(searchResults):
97 selectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
103 # Play the video using the preferred/available media player
104 let videoNumber = parseInt(userInput)
105 handleUserInput(videoNumber)
106 if options["feelingLucky"]: