Make options a dictionary and add validation
[nimcoon.git] / src / nimcoon.nim
1 import
2 parseopt,
3 std/[terminal],
4 strformat,
5 strutils,
6 tables
7
8 import config
9 import lib
10
11
12 proc parseArguments(): CommandLineOptions =
13 var
14 searchQuery = ""
15 options = to_table({"musicOnly": false, "feelingLucky": false, "fullScreen": false, "download": false})
16
17 for kind, key, value in getopt():
18 case kind
19 of cmdArgument:
20 searchQuery = key
21 of cmdShortOption, cmdLongOption:
22 case key
23 of "m", "music": options["musicOnly"] = true
24 of "l", "lucky": options["feelingLucky"] = true
25 of "f", "full-screen": options["fullScreen"] = true
26 of "d", "download": options["download"] = true
27 of cmdEnd: discard
28
29 return (searchQuery, options)
30
31
32 proc isValidOptions*(options: Options): bool =
33 # Check for invalid combinations of options
34 var invalidCombinations = [("musicOnly", "fullScreen")]
35 for combination in invalidCombinations:
36 if options[combination[0]] and options[combination[1]]:
37 stderr.writeLine fmt"Incompatible options provided: {combination[0]} and {combination[1]}"
38 return false
39 return true
40
41
42 proc main() =
43 let
44 player = selectMediaPlayer()
45 (searchQuery, options) = parseArguments()
46
47 if(not isValidOptions(options)):
48 quit(1)
49
50 if searchQuery.startswith("https:") or searchQuery.startswith("magnet:"):
51 directPlay(searchQuery, player)
52 quit(0)
53
54 let searchResults = extractTitlesAndUrls(getYoutubePage(searchQuery))
55
56 proc getUserInput(): string =
57 if options["feelingLucky"]: "0"
58 else:
59 presentVideoOptions(searchResults[..(limit-1)])
60 stdout.styledWrite(fgYellow, "Choose video number: ")
61 readLine(stdin)
62
63 # This is a pure function with no side effects
64 func buildArgs(number: int): seq[string] =
65 var args = @[searchResults[number].url]
66 if options["musicOnly"]: args.add("--no-video")
67 if options["fullScreen"]: args.add("--fullscreen")
68 return args
69
70 while(true):
71 let userInput = getUserInput()
72
73 if userInput == "all":
74 for number in 0..(len(searchResults)):
75 play(player, buildArgs(number), searchResults[number].title)
76
77 if userInput == "q":
78 break
79
80 # Play the video using the preferred/available media player
81 let videoNumber = parseInt(userInput)
82 play(player, buildArgs(videoNumber), searchResults[videoNumber].title)
83 if options["feelingLucky"]:
84 break
85
86
87 when isMainModule:
88 main()