Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First implementation of automatic recognition of redirect url #98

Merged
merged 1 commit into from
Oct 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use clap::App as ClapApp;
use rspotify::spotify::client::Spotify;
use rspotify::spotify::oauth2::{SpotifyClientCredentials, SpotifyOAuth, TokenInfo};
use rspotify::spotify::util::get_token;
use rspotify::spotify::util::request_token;
use rspotify::spotify::util::process_token;
use std::cmp::min;
use std::io::{self, Write};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use termion::cursor::Goto;
use termion::event::Key;
Expand Down Expand Up @@ -57,7 +57,29 @@ fn get_spotify(token_info: TokenInfo) -> (Spotify, Instant) {

(spotify, token_expiry)
}

/// get token automatically with local webserver
pub fn get_token_auto(spotify_oauth: &mut SpotifyOAuth) -> Option<TokenInfo> {
match spotify_oauth.get_cached_token() {
Some(token_info) => Some(token_info),
None => {
match redirect_uri_web_server(spotify_oauth) {
Ok(url) => {
process_token(spotify_oauth, &mut url.to_string())
},
Err(()) => {
println!("Starting webserver failed. Continuing with manual authentication");
request_token(spotify_oauth);
println!("Enter the URL you were redirected to: ");
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => process_token(spotify_oauth, &mut input),
Err(_) => None,
}
}
}
}
}
}
fn main() -> Result<(), failure::Error> {
ClapApp::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
Expand All @@ -68,13 +90,6 @@ fn main() -> Result<(), failure::Error> {
.after_help("Your spotify Client ID and Client Secret are stored in $HOME/.config/spotify-tui/client.yml")
.get_matches();

let (tx, rx) = mpsc::channel();

// Start the web server in case we need to use the redirect uri, this will get closed below
// after auth is successful
thread::spawn(|| {
redirect_uri_web_server(rx);
});

let mut client_config = ClientConfig::new();
client_config.load_config()?;
Expand All @@ -90,11 +105,8 @@ fn main() -> Result<(), failure::Error> {
.scope(&SCOPES.join(" "))
.build();

match get_token(&mut oauth) {
match get_token_auto(&mut oauth) {
Some(token_info) => {
// Terminate the web server running for the Redirect URI (fire and forget)
if tx.send(()).is_ok() {};

// Terminal initialization
let stdout = io::stdout().into_raw_mode()?;
let stdout = MouseTerminal::from(stdout);
Expand Down
2 changes: 1 addition & 1 deletion src/redirect_uri.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
<div class="container">
<div class="header">
<h1>spotify-tui</h1>
<p class="lead">Copy the URL of this page into the terminal</p>
<p class="lead">Client authorized. You can return to your terminal and close this window.</p>
</div>
</div>
</body>
Expand Down
54 changes: 41 additions & 13 deletions src/redirect_uri.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,75 @@
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::sync::mpsc::{Receiver, TryRecvError};
use rspotify::spotify::util::request_token;
use rspotify::spotify::oauth2::SpotifyOAuth;

pub fn redirect_uri_web_server(thread_reciever: Receiver<()>) {
pub fn redirect_uri_web_server(spotify_oauth: &mut SpotifyOAuth) -> Result<String, ()> {
let listener = TcpListener::bind("127.0.0.1:8888");

match listener {
Ok(listener) => {
request_token(spotify_oauth);

for stream in listener.incoming() {
match stream {
Ok(stream) => {
handle_connection(stream);

// Listen for any signal to break out of this loop and close the server
match thread_reciever.try_recv() {
Ok(_) | Err(TryRecvError::Disconnected) => {
break;
}
Err(TryRecvError::Empty) => {}
if let Some(url) = handle_connection(stream) {
return Ok(url);
}
}
Err(e) => {
println!("Error running redirect uri webserver {}", e);
println!("Error: {}", e);
}
};
}
}
Err(e) => {
println!("Error running redirect uri webserver {}", e);
println!("Error: {}", e);
}
}

Err(())
}

fn handle_connection(mut stream: TcpStream) {
fn handle_connection(mut stream: TcpStream) -> Option<String> {
// The request will be quite large (> 512) so just assign plenty just in case
let mut buffer = [0; 1000];
let _ = stream.read(&mut buffer).unwrap();

// convert buffer into string and 'parse' the URL
match String::from_utf8(buffer.to_vec()) {
Ok(request) => {
let split: Vec<&str> = request.split_whitespace().collect();

if split.len() > 1 {
respond_with_success(stream);
return Some(split[1].to_string());
}

respond_with_error("Malformed request".to_string(), stream);
},
Err(e) => {
respond_with_error(format!("Invalid UTF-8 sequence: {}", e), stream);
},
};

None
}

fn respond_with_success(mut stream: TcpStream) {
let contents = include_str!("redirect_uri.html");

let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);

stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}

fn respond_with_error(error_message: String, mut stream: TcpStream) {
println!("Error: {}", error_message);
let response = format!("HTTP/1.1 400 Bad Request\r\n\r\n400 - Bad Request - {}", error_message);

stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}