From bd7c31233de96d96e16f9c15e22d014514f7a173 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Thu, 8 Nov 2018 01:52:31 -0500 Subject: stop passing the api key on the command line --- src/lastfm/mod.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) (limited to 'src/lastfm') diff --git a/src/lastfm/mod.rs b/src/lastfm/mod.rs index fc2eb5b..b5888cc 100644 --- a/src/lastfm/mod.rs +++ b/src/lastfm/mod.rs @@ -1,3 +1,8 @@ +use paths; + +use failure::Fail; +use std::io::{Read, Write}; + mod api_types; const API_ROOT: &'static str = "https://ws.audioscrobbler.com/2.0/"; @@ -98,12 +103,12 @@ impl<'a> Iterator for Tracks<'a> { } impl LastFMClient { - pub fn new(api_key: &str, user: &str) -> LastFMClient { - LastFMClient { + pub fn new(user: &str) -> failure::Fallible { + Ok(LastFMClient { client: reqwest::Client::new(), - api_key: api_key.to_string(), + api_key: find_api_key()?, user: user.to_string(), - } + }) } pub fn track_count(&self, from: Option) -> failure::Fallible { @@ -151,3 +156,39 @@ impl LastFMClient { } } } + +fn find_api_key() -> failure::Fallible { + let api_key_path = paths::api_key_path() + .map_err(|e| e.context("failed to determine api key path"))?; + let api_key = if api_key_path.exists() { + let mut api_key = String::new(); + let mut f = std::fs::File::open(&api_key_path) + .map_err(|e| { + e.context(format!("failed to open {}", api_key_path.display())) + })?; + f.read_to_string(&mut api_key) + .map_err(|e| { + e.context(format!("failed to read from {}", api_key_path.display())) + })?; + api_key + } + else { + let api_key = rpassword::prompt_password_stderr( + &format!( + "last.fm api key (will be stored in {}): ", + api_key_path.display() + ) + )?; + std::fs::create_dir_all(api_key_path.parent().unwrap())?; + let mut f = std::fs::File::create(&api_key_path) + .map_err(|e| { + e.context(format!("failed to open {}", api_key_path.display())) + })?; + f.write_all(api_key.as_bytes()) + .map_err(|e| { + e.context(format!("failed to write to {}", api_key_path.display())) + })?; + api_key + }; + Ok(api_key.trim_end().to_string()) +} -- cgit v1.2.3-54-g00ecf