forked from akiirui/mpv-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.rs
258 lines (221 loc) · 8.01 KB
/
handler.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use thiserror::Error;
use crate::config::{Config, PlayMode};
use crate::protocol::Protocol;
#[derive(Error, Debug)]
pub enum HandlerError {
#[error(transparent)]
Config(#[from] crate::config::ConfigError),
#[error(transparent)]
Protocol(#[from] crate::protocol::ProtocolError),
#[error(transparent)]
IoError(#[from] std::io::Error),
#[error("Error: No argument is given")]
NoArg,
#[error("Error: Too many arguments are given")]
TooManyArgs,
#[cfg(unix)]
#[error("Error: Failed to get config directory")]
FailedGetConfigDir,
#[error("Error: The downloader \"{0}\" requires a quality LEVEL")]
DownloaderRequireQuality(String),
#[error("Error: Downloader or player exited with error or termination signal")]
DownloaderExited,
#[error("Error: Failed to run downloader \"{0}\": {1}")]
FailedRunDownloader(String, std::io::Error),
#[error("Error: Failed to run player: {0}")]
FailedRunPlayer(std::io::Error),
}
#[derive(Debug)]
pub struct Handler {
protocol: Protocol,
config: Config,
}
impl Handler {
/// Generate a Handler
pub fn new() -> Result<Self, HandlerError> {
let mut args: Vec<String> = std::env::args().collect();
let arg: &mut String = match args.len() {
2 => &mut args[1],
1 => return Err(HandlerError::NoArg),
_ => return Err(HandlerError::TooManyArgs),
};
match arg.as_str() {
"version" | "-v" | "-V" => version(),
_ => {}
};
let protocol: Protocol;
let config: Config;
protocol = Protocol::parse(arg)?;
config = Config::load()?;
Ok(Handler { protocol, config })
}
/// Prepare arguments and run downloader & player
pub fn run(&self) -> Result<(), HandlerError> {
let mut downloader_options: Vec<&String> = Vec::new();
let downloader = self.config.downloader(&self.protocol.downloader)?;
// Append cookies option and cookies file path to arguments
let mut cookies_path: String;
if self.protocol.cookies.len() != 0 {
let mut path: std::path::PathBuf;
let cookies = downloader.cookies(&self.protocol.downloader)?;
#[cfg(unix)]
{
path = match dirs::config_dir() {
Some(path) => path,
None => return Err(HandlerError::FailedGetConfigDir),
};
path.push("mpv-handler");
path.push("cookies");
path.push(&self.protocol.cookies);
}
#[cfg(windows)]
{
path = std::env::current_exe()?;
path.pop();
path.push("cookies");
path.push(&self.protocol.cookies);
}
cookies_path = path.as_path().display().to_string();
if downloader.cookies_prefix {
cookies_path.insert_str(0, &cookies);
downloader_options.push(&cookies_path);
} else {
downloader_options.push(&cookies);
downloader_options.push(&cookies_path);
}
}
// Append quality option
if self.protocol.quality.len() != 0 {
let quality = downloader.quality(&self.protocol.downloader, &self.protocol.quality)?;
downloader_options.push(quality)
} else if downloader.require_quality {
return Err(HandlerError::DownloaderRequireQuality(
self.protocol.downloader.clone(),
));
}
// Append output or player options
for option in &downloader.options {
downloader_options.push(option);
}
// Choose downloader play mode
let play_mode = downloader.play_mode()?;
let bin = downloader.bin(&self.protocol.downloader)?;
let player = self.config.player()?;
let player_options = &downloader.player_options;
#[cfg(unix)]
{
self.set_environment()?;
}
println!("Playing: {}", self.protocol.url);
match play_mode {
PlayMode::Direct => self.play_direct(&bin, downloader_options),
PlayMode::Normal => self.play(&bin, &player, downloader_options, player_options),
PlayMode::Pipe => self.play_pipe(&bin, &player, downloader_options, player_options),
}
}
/// Set environment variables for player and downloader if needed (Unix only)
#[cfg(unix)]
fn set_environment(&self) -> Result<(), HandlerError> {
// Fix google-chrome overwrite "LD_LIBRARY_PATH" on Linux
// It will be let mpv exit with error:
// mpv: symbol lookup error: mpv: undefined symbol: vkCreateWaylandSurfaceKHR
std::env::remove_var("LD_LIBRARY_PATH");
// Set "LD_LIBRARY_PATH" if needed
// When "ld_path" option is given in "config.toml" or "custom.toml"
if let Some(ld_path) = self.config.ld_path()? {
std::env::set_var("LD_LIBRARY_PATH", ld_path)
}
Ok(())
}
/// Run downloader directly (mpv has ytdl-hooks)
fn play_direct(
&self,
bin: &String,
downloader_options: Vec<&String>,
) -> Result<(), HandlerError> {
let downloader = std::process::Command::new(bin)
.args(downloader_options)
.arg(&self.protocol.url)
.status();
match downloader {
Ok(status) => match status.success() {
true => Ok(()),
false => Err(HandlerError::DownloaderExited),
},
Err(error) => Err(HandlerError::FailedRunDownloader(
self.protocol.downloader.clone(),
error,
)),
}
}
/// Run downloader and set player
fn play(
&self,
bin: &String,
player: &String,
downloader_options: Vec<&String>,
player_options: &Vec<String>,
) -> Result<(), HandlerError> {
let mut player = player.clone();
for option in player_options {
player.push(' ');
player.push_str(option);
}
let downloader = std::process::Command::new(bin)
.args(downloader_options)
.arg(player)
.arg(&self.protocol.url)
.status();
match downloader {
Ok(status) => match status.success() {
true => Ok(()),
false => Err(HandlerError::DownloaderExited),
},
Err(error) => Err(HandlerError::FailedRunDownloader(
self.protocol.downloader.clone(),
error,
)),
}
}
/// Run downloader and transfer video data through pipeline
fn play_pipe(
&self,
downloader_bin: &String,
player_bin: &String,
downloader_options: Vec<&String>,
player_options: &Vec<String>,
) -> Result<(), HandlerError> {
let downloader = match std::process::Command::new(downloader_bin)
.args(downloader_options)
.arg(&self.protocol.url)
.stdout(std::process::Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(error) => {
return Err(HandlerError::FailedRunDownloader(
self.protocol.downloader.clone(),
error,
))
}
};
let player = std::process::Command::new(player_bin)
.args(player_options)
.arg("-")
.stdin(downloader.stdout.unwrap())
.status();
match player {
Ok(status) => match status.success() {
true => Ok(()),
false => Err(HandlerError::DownloaderExited),
},
Err(error) => Err(HandlerError::FailedRunPlayer(error)),
}
}
}
/// Print `mpv-handler` version infomation
fn version() {
let version: &str = option_env!("MPV_HANDLER_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
println!("mpv-handler {}", version);
std::process::exit(0)
}