]> njoseph.me Git - nimcoon.git/blame - src/lib.nim
Make all sequences immutable
[nimcoon.git] / src / lib.nim
CommitLineData
d65a1dcf
JN
1import
2 htmlparser,
3 httpClient,
e9f0c7d0 4 os,
d65a1dcf
JN
5 osproc,
6 sequtils,
7 sugar,
8 strformat,
9 std/[terminal],
e9f0c7d0 10 strformat,
d65a1dcf
JN
11 strtabs,
12 strutils,
6f161e0b 13 tables,
d65a1dcf
JN
14 uri,
15 xmltree
16
17import config
18
19type
6f161e0b 20 Options* = Table[string, bool]
e9f0c7d0 21 SearchResult* = tuple[title: string, url: string]
13a4017d 22 SearchResults* = seq[tuple[title: string, url: string]]
6f161e0b 23 CommandLineOptions* = tuple[searchQuery: string, options: Options]
e6561dc9 24 SelectionRange* = tuple[begin: int, until: int]
d65a1dcf 25
e9f0c7d0 26# poEchoCmd can be added to options for debugging
e4a68706 27let processOptions = {poStdErrToStdOut, poUsePath}
9e6b8568 28
d65a1dcf
JN
29proc selectMediaPlayer*(): string =
30 let availablePlayers = filterIt(supportedPlayers, execProcess("which " & it).len != 0)
31 if len(availablePlayers) == 0:
32 stderr.writeLine &"Please install one of the supported media players: {supportedPlayers}"
33 raise newException(OSError, "No supported media player found")
34 else:
35 return availablePlayers[0]
36
37proc getYoutubePage*(searchQuery: string): string =
38 let queryParam = encodeUrl(searchQuery)
39 let client = newHttpClient()
40 let response = get(client, &"https://www.youtube.com/results?hl=en&search_query={queryParam}")
41 return $response.body
42
13a4017d 43func extractTitlesAndUrls*(html: string): SearchResults =
4a0587e2
JN
44 {.noSideEffect.}:
45 parseHtml(html).findAll("a").
46 filter(a => "watch" in a.attrs["href"] and a.attrs.hasKey "title").
72720bec 47 map(a => (a.attrs["title"], "https://www.youtube.com" & a.attrs["href"]))
d65a1dcf 48
13a4017d 49proc presentVideoOptions*(searchResults: SearchResults) =
17955bba 50 eraseScreen()
d65a1dcf
JN
51 for index, (title, url) in searchResults:
52 styledEcho $index, ". ", styleBright, fgMagenta, title, "\n", resetStyle, fgCyan, url, "\n"
53
d36e2201 54func isPlaylist(url: string): bool =
28d7042e 55 # Identifies if video is part of a playlist
d36e2201
JN
56 # Only YouTube playlists are supported for now
57 "www.youtube.com" in url and "&list=" in url
58
59# This is a pure function with no side effects
60func buildPlayerArgs(url: string, options: Table[string, bool], player: string): seq[string] =
046c2cc3
JN
61 let url =
62 # Playlists are only supported for MPV player
63 if isPlaylist(url) and player == "mpv":
64 "https://www.youtube.com/playlist?" & url.split('&')[1]
65 else: url
66 let musicOnly = if options["musicOnly"]: "--no-video" else: ""
67 let fullScreen = if options["fullScreen"]: "--fullscreen" else: ""
68 return filterIt([url, musicOnly, fullScreen], it != "")
d36e2201
JN
69
70proc play*(player: string, options: Table[string, bool], url: string, title: string = "") =
71 let args = buildPlayerArgs(url, options, player)
72 if title != "":
73 styledEcho "\n", fgGreen, "Playing ", styleBright, fgMagenta, title
e71f26f3
JN
74 if "--no-video" in args:
75 discard execShellCmd(&"{player} {args.join(\" \")}")
76 else:
77 discard execProcess(player, args=args, options=processOptions)
d65a1dcf 78
9a8ef4ad
JN
79func buildMusicDownloadArgs*(url: string): seq[string] =
80 {.noSideEffect.}:
9a8ef4ad 81 let downloadLocation = &"'{expandTilde(musicDownloadDirectory)}/%(title)s.%(ext)s'"
046c2cc3 82 return @["--ignore-errors", "-f", "bestaudio", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "-o", downloadLocation, url]
9a8ef4ad
JN
83
84func buildVideoDownloadArgs*(url: string): seq[string] =
85 {.noSideEffect.}:
9a8ef4ad 86 let downloadLocation = &"'{expandTilde(videoDownloadDirectory)}/%(title)s.%(ext)s'"
046c2cc3 87 return @["-f", "best", "-o", downloadLocation, url]
9a8ef4ad 88
e9f0c7d0
JN
89proc download*(args: openArray[string], title: string) =
90 styledEcho "\n", fgGreen, "Downloading ", styleBright, fgMagenta, title
91 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
92
d65a1dcf
JN
93func urlLongen(url: string): string =
94 url.replace("youtu.be/", "www.youtube.com/watch?v=")
95
96func stripZshEscaping(url: string): string =
97 url.replace("\\", "")
98
99func sanitizeURL*(url: string): string =
100 urlLongen(stripZshEscaping(url))
101
d36e2201 102proc directPlay*(url: string, player: string, options: Table[string, bool]) =
d7688e97 103 if url.startswith("magnet:") or url.endswith(".torrent"):
d36e2201 104 if options["musicOnly"]:
8d06ad69 105 # TODO Replace with WebTorrent once it supports media player options
811928a7
JN
106 discard execShellCmd(&"peerflix '{url}' -a --{player} -- --no-video")
107 else:
8d06ad69
JN
108 # WebTorrent is so much faster!
109 discard execProcess("webtorrent", args=[url, &"--{player}"], options=processOptions)
fe1a5856 110 else:
d36e2201 111 play(player, options, url)
811928a7
JN
112
113proc directDownload*(url: string, musicOnly: bool) =
114 let args =
115 if musicOnly: buildMusicDownloadArgs(url)
116 else: buildVideoDownloadArgs(url)
9a8ef4ad 117 discard execShellCmd(&"youtube-dl {args.join(\" \")}")
13a4017d
JN
118
119proc offerSelection(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange): string =
120 if options["feelingLucky"]: "0"
121 else:
122 presentVideoOptions(searchResults[selectionRange.begin .. selectionRange.until])
123 stdout.styledWrite(fgYellow, "Choose video number: ")
124 readLine(stdin)
125
13a4017d
JN
126proc handleUserInput(searchResult: SearchResult, options: Table[string, bool], player: string) =
127 if options["download"]:
128 if options["musicOnly"]:
129 download(buildMusicDownloadArgs(searchResult.url), searchResult.title)
130 else:
131 download(buildVideoDownloadArgs(searchResult.url), searchResult.title)
132 else:
d36e2201 133 play(player, options, searchResult.url, searchResult.title)
13a4017d
JN
134
135proc present*(searchResults: SearchResults, options: Table[string, bool], selectionRange: SelectionRange, player: string) =
136 #[ Continuously present options till the user quits the application
137 selectionRange: Currently available range to choose from depending on pagination
138 ]#
139
140 let userInput = offerSelection(searchResults, options, selectionRange)
141
142 case userInput
143 of "all":
144 for selection in selectionRange.begin .. selectionRange.until:
145 handleUserInput(searchResults[selection], options, player)
146 quit(0)
147 of "n":
148 if selectionRange.until + 1 < len(searchResults):
149 let newSelectionRange = (selectionRange.until + 1, min(len(searchResults) - 1, selectionRange.until + limit))
150 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
151 else:
152 present(searchResults, options, selectionRange, player)
13a4017d
JN
153 of "p":
154 if selectionRange.begin > 0:
155 let newSelectionRange = (selectionRange.begin - limit, selectionRange.until - limit)
156 present(searchResults, options, newSelectionRange, player)
ebae91b4
JN
157 else:
158 present(searchResults, options, selectionRange, player)
13a4017d
JN
159 of "q":
160 quit(0)
161 else:
db34bbff
JN
162 let searchResult = searchResults[selectionRange.begin .. selectionRange.until][parseInt(userInput)]
163 handleUserInput(searchResult, options, player)
13a4017d
JN
164 if options["feelingLucky"]:
165 quit(0)
166 else:
167 present(searchResults, options, selectionRange, player)