use std::sync::{Arc, Mutex, MutexGuard};
use std::io::Read;
use hyper::client::{Client, RequestBuilder};
use hyper::header::UserAgent;
use hyper::net::DefaultConnector;
use hyper::status::StatusCode::Unauthorized;
use serde_json::from_str;
use serde::Deserialize;
use structures::subreddit::Subreddit;
use structures::user::User;
use structures::submission::LazySubmission;
use structures::messages::MessageInterface;
use auth::Authenticator;
use errors::APIError;
pub struct RedditClient {
pub client: Client,
user_agent: String,
authenticator: Arc<Mutex<Box<Authenticator + Send>>>,
auto_logout: bool
}
impl RedditClient {
pub fn new(user_agent: &str, authenticator: Arc<Mutex<Box<Authenticator + Send>>>) -> RedditClient {
let client = Client::with_connector(DefaultConnector::default());
let this = RedditClient {
client: client,
user_agent: user_agent.to_owned(),
authenticator: authenticator,
auto_logout: true
};
this.get_authenticator().login(&this.client, &this.user_agent).expect("Authentication failed. Did you use the correct username/password?");
this
}
pub fn set_auto_logout(&mut self, val: bool) {
self.auto_logout = val;
}
pub fn ensure_authenticated<F, T>(&self, lambda: F) -> Result<T, APIError> where F: Fn() -> Result<T, APIError> {
let res = lambda();
match res {
Err(APIError::HTTPError(Unauthorized)) => {
try!(self.get_authenticator().refresh_token(&self.client, &self.user_agent));
lambda()
},
_ => res
}
}
pub fn get_authenticator(&self) -> MutexGuard<Box<Authenticator + Send + 'static>> {
self.authenticator.lock().unwrap()
}
pub fn subreddit(&self, name: &str) -> Subreddit {
Subreddit::create_new(self, name)
}
pub fn user(&self, name: &str) -> User {
User::new(self, name)
}
pub fn build_url(&self, dest: &str, oauth_required: bool, authenticator: &mut MutexGuard<Box<Authenticator + Send + 'static>>) -> String {
let oauth_supported = authenticator.oauth();
let stem = if oauth_required || oauth_supported {
assert!(oauth_supported, "OAuth is required to use this endpoint, but your authenticator does not support it.");
"https://oauth.reddit.com"
} else {
"https://api.reddit.com"
};
format!("{}{}", stem, dest)
}
pub fn get(&self, dest: &str, oauth_required: bool) -> RequestBuilder {
let mut authenticator = self.get_authenticator();
let url = self.build_url(dest, oauth_required, &mut authenticator);
let req = self.client.get(&url);
let mut headers = authenticator.headers();
headers.set(UserAgent(self.user_agent.to_owned()));
req.headers(headers)
}
pub fn get_json<T>(&self, dest: &str, oauth_required: bool) -> Result<T, APIError>
where T: Deserialize {
self.ensure_authenticated(|| {
let mut response = try!(self.get(dest, oauth_required).send());
if response.status.is_success() {
let mut buf = String::new();
response.read_to_string(&mut buf).expect("Buffer read failed");
let json: T = try!(from_str(&buf));
Ok(json)
} else {
Err(APIError::HTTPError(response.status))
}
})
}
pub fn post(&self, dest: &str, oauth_required: bool) -> RequestBuilder {
let mut authenticator = self.get_authenticator();
let url = self.build_url(dest, oauth_required, &mut authenticator);
let req = self.client.post(&url);
let mut headers = authenticator.headers();
headers.set(UserAgent(self.user_agent.to_owned()));
req.headers(headers)
}
pub fn post_json<T>(&self, dest: &str, body: &str, oauth_required: bool) -> Result<T, APIError>
where T: Deserialize {
self.ensure_authenticated(|| {
let mut response = try!(self.post(dest, oauth_required).body(body).send());
if response.status.is_success() {
let mut buf = String::new();
response.read_to_string(&mut buf).expect("Buffer read failed");
let json: T = try!(from_str(&buf));
Ok(json)
} else {
Err(APIError::HTTPError(response.status))
}
})
}
pub fn post_success(&self, dest: &str, body: &str, oauth_required: bool) -> Result<(), APIError> {
self.ensure_authenticated(|| {
let response = try!(self.post(dest, oauth_required).body(body).send());
if response.status.is_success() {
Ok(())
} else {
Err(APIError::HTTPError(response.status))
}
})
}
pub fn url_escape(&self, item: String) -> String {
let mut res = String::new();
for character in item.chars() {
match character {
' ' => res.push('+'),
'*' | '-' | '.' | '0'...'9' | 'A'...'Z' | '_' | 'a'...'z' => res.push(character),
_ => {
for val in character.to_string().as_bytes() {
res = res + &format!("%{:X}", val);
}
}
}
}
res
}
pub fn get_by_id(&self, id: &str) -> LazySubmission {
LazySubmission::new(self, id)
}
pub fn messages(&self) -> MessageInterface {
MessageInterface::new(self)
}
}
impl Drop for RedditClient {
fn drop(&mut self) {
if self.auto_logout {
self.get_authenticator().logout(&self.client, &self.user_agent).unwrap();
}
}
}