librespot/src/main.rs

157 lines
4.8 KiB
Rust
Raw Normal View History

2017-01-10 16:31:12 +00:00
#[macro_use] extern crate log;
extern crate getopts;
2015-07-09 19:08:56 +00:00
extern crate librespot;
extern crate ctrlc;
2017-01-10 16:31:12 +00:00
extern crate env_logger;
2015-04-25 20:32:07 +00:00
2017-01-10 16:31:12 +00:00
use env_logger::LogBuilder;
use std::io::{stderr, Write};
use std::process::exit;
use std::thread;
2017-01-10 16:31:12 +00:00
use std::env;
use std::path::PathBuf;
use std::str::FromStr;
use librespot::spirc::SpircManager;
use librespot::authentication::get_credentials;
2017-01-10 16:31:12 +00:00
use librespot::audio_backend::{self, BACKENDS};
use librespot::cache::{Cache, DefaultCache, NoCache};
use librespot::player::Player;
use librespot::session::{Bitrate, Config, Session};
use librespot::version;
2016-03-16 00:05:05 +00:00
fn usage(program: &str, opts: &getopts::Options) -> String {
let brief = format!("Usage: {} [options]", program);
format!("{}", opts.usage(&brief))
}
2017-01-10 16:31:12 +00:00
fn setup_logging(verbose: bool) {
let mut builder = LogBuilder::new();
2016-01-02 02:30:24 +00:00
2017-01-10 16:31:12 +00:00
match env::var("RUST_LOG") {
Ok(config) => {
builder.parse(&config);
builder.init().unwrap();
if verbose {
warn!("`--verbose` flag overidden by `RUST_LOG` environment variable");
}
}
Err(_) => {
if verbose {
builder.parse("mdns=info,librespot=trace");
} else {
builder.parse("mdns=info,librespot=info");
}
builder.init().unwrap();
}
}
}
fn list_backends() {
println!("Available Backends : ");
for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
if idx == 0 {
println!("- {} (default)", name);
} else {
println!("- {}", name);
}
}
}
fn setup(args: &[String]) -> (Session, Player) {
let mut opts = getopts::Options::new();
opts.optopt("c", "cache", "Path to a directory where files will be cached.", "CACHE")
.reqopt("n", "name", "Device name", "NAME")
.optopt("b", "bitrate", "Bitrate (96, 160 or 320). Defaults to 160", "BITRATE")
.optopt("", "onstart", "Run PROGRAM when playback is about to begin.", "PROGRAM")
.optopt("", "onstop", "Run PROGRAM when playback has ended.", "PROGRAM")
.optflag("v", "verbose", "Enable verbose output")
.optopt("u", "username", "Username to sign in with", "USERNAME")
.optopt("p", "password", "Password", "PASSWORD")
.optopt("", "backend", "Audio backend to use. Use '?' to list options", "BACKEND")
.optopt("", "device", "Audio device to use. Use '?' to list options", "DEVICE");
let matches = match opts.parse(&args[1..]) {
2016-01-02 15:19:39 +00:00
Ok(m) => m,
Err(f) => {
writeln!(stderr(), "error: {}\n{}", f.to_string(), usage(&args[0], &opts)).unwrap();
exit(1);
2016-04-24 11:15:53 +00:00
}
};
2017-01-10 16:31:12 +00:00
let verbose = matches.opt_present("verbose");
setup_logging(verbose);
info!("librespot {} ({}). Built on {}.",
version::short_sha(),
version::commit_date(),
version::short_now());
let backend_name = matches.opt_str("backend");
if backend_name == Some("?".into()) {
list_backends();
exit(0);
}
let backend = audio_backend::find(backend_name.as_ref())
.expect("Invalid backend");
let bitrate = matches.opt_str("b").as_ref()
.map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
.unwrap_or(Bitrate::Bitrate160);
2017-01-18 17:07:20 +00:00
let device_name = matches.opt_str("name").unwrap();
let device_id = librespot::session::device_id(&device_name);
let cache = matches.opt_str("c").map(|cache_location| {
Box::new(DefaultCache::new(PathBuf::from(cache_location)).unwrap())
as Box<Cache + Send + Sync>
}).unwrap_or_else(|| Box::new(NoCache));
let cached_credentials = cache.get_credentials();
let credentials = get_credentials(&device_name, &device_id,
matches.opt_str("username"),
matches.opt_str("password"),
cached_credentials);
2017-01-10 16:31:12 +00:00
let config = Config {
user_agent: version::version_string(),
2017-01-18 17:07:20 +00:00
device_name: device_name,
device_id: device_id,
2017-01-10 16:31:12 +00:00
bitrate: bitrate,
onstart: matches.opt_str("onstart"),
onstop: matches.opt_str("onstop"),
};
let session = Session::new(config, cache);
session.login(credentials).unwrap();
2017-01-10 16:31:12 +00:00
let device_name = matches.opt_str("device");
let player = Player::new(session.clone(), move || {
(backend)(device_name.as_ref().map(AsRef::as_ref))
});
(session, player)
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let (session, player) = setup(&args);
let spirc = SpircManager::new(session.clone(), player);
let spirc_signal = spirc.clone();
2016-01-02 15:19:39 +00:00
thread::spawn(move || spirc.run());
ctrlc::set_handler(move || {
spirc_signal.send_goodbye();
exit(0);
});
2016-01-01 23:16:12 +00:00
loop {
session.poll();
}
2015-07-01 17:49:03 +00:00
}