forked from Rigellute/spotify-tui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirect_uri.rs
78 lines (64 loc) · 1.96 KB
/
redirect_uri.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
use rspotify::{oauth2::SpotifyOAuth, util::request_token};
use std::{
io::prelude::*,
net::{TcpListener, TcpStream},
};
pub fn redirect_uri_web_server(spotify_oauth: &mut SpotifyOAuth, port: u16) -> Result<String, ()> {
let listener = TcpListener::bind(format!("127.0.0.1:{}", port));
match listener {
Ok(listener) => {
request_token(spotify_oauth);
for stream in listener.incoming() {
match stream {
Ok(stream) => {
if let Some(url) = handle_connection(stream) {
return Ok(url);
}
}
Err(e) => {
println!("Error: {}", e);
}
};
}
}
Err(e) => {
println!("Error: {}", e);
}
}
Err(())
}
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();
}