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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use std::error::Error;
use log;
use std::collections::HashMap;
use std::cell::RefCell;
use lazy_static::lazy_static;
use regex::Regex;
use reqwest;
use reqwest::blocking::ClientBuilder;
use reqwest::header::HeaderValue;
use reqwest::header::HeaderMap;
use reqwest::cookie::Cookie;
use reqwest::redirect::Policy;
use scraper;
use scraper::Html;
use scraper::Selector;
use scraper::ElementRef;
use crate::error::HttpError;
use crate::error::HnError;
use crate::parser::HtmlParse;
use crate::parser::ListingsParser;
use crate::parser::CommentsParser;
use crate::parser::extract_fnid;
use crate::parser::comments::create_comment_tree;
use crate::model::Id;
use crate::model::Listing;
use crate::model::Date;
use crate::model::Thread;


const URL_LOGIN: &str = "https://news.ycombinator.com/login";
const URL_SUBMIT_FORM: &str = "https://news.ycombinator.com/submit";
const URL_SUBMIT: &str = "https://news.ycombinator.com/r";

lazy_static! {
    static ref FNID_REGEX: Regex =  Regex::new(r#"<input.*value="(.+?)".*>"#).unwrap();
}

pub struct Client {
    http_client: reqwest::blocking::Client,
    username: String,
    password: String,
    cookie: RefCell<Option<(String, String)>>,
}

impl Client {

    pub fn new(username: &str, password: &str) -> Self {
        Self {
            username: String::from(username),
            password: String::from(password),
            http_client: reqwest::blocking::Client::new(),
            cookie: RefCell::new(None),
        }
    }

    fn cookie(&self) -> Result<String, Box<dyn Error>> {
        // Note: Chaining these causes a compiler error about dropping to early
        let pair = self.cookie.borrow();
        let pair = pair.as_ref().ok_or(HnError::UnauthenticatedError)?;

        Ok(format!("{}={};", pair.0, pair.1))
    }

    pub fn submit(
        &self,
        title: String,
        url: Option<String>,
        text: Option<String>,
    ) -> Result<(), Box<dyn Error>> {

        let cookie_string = self.cookie()?;
        let cookie: HeaderValue = cookie_string.parse()
            .expect("Got a user cookie, but failed to parse it to a header");

        let mut formdata = HashMap::new();
        formdata.insert("fnid", self.get_fnid()?);
        formdata.insert("fnop", "submit-page".to_string());
        formdata.insert("url", url.unwrap_or_else(|| "".to_string()));
        formdata.insert("text", text.unwrap_or_else(|| "".to_string()));
        log::debug!("submit post body = {:?}", formdata);
        formdata.insert("title", title);
        
        let req = self.http_client.post(URL_SUBMIT)
            .header("Cookie", cookie)
            .form(&formdata);
        log::debug!("submit post request = {:?}", req);
        let resp = req.send()?;
        log::debug!("submit post response = {:?}", resp);
        
        Ok(())

    }
    
    fn get_fnid(&self) -> Result<String, Box<dyn Error>> {
        let cookie_string = self.cookie()?;
        let cookie: HeaderValue = cookie_string.parse()
            .expect("Got a user cookie, but failed to parse it to a header");
    
        let req = self.http_client
            .get(URL_SUBMIT_FORM)
            .header("Cookie", cookie);
        log::debug!("submit form request = {:?}", req);
        let resp = req.send()?;
        log::debug!("submit form response = {:?}", resp);
        let body = resp.text()?;
        let dom = Html::parse_document(&body);
        
        // Underlying library doesn't implement std::error::Error on their
        // Error structs, so I can't include it as the src error in my struct
        let selector = match Selector::parse("input[name='fnid']") {
            Err(_src) => {
                return Err(Box::new(HnError::HtmlParsingError));
            },
            Ok(selector) => selector,
        };
    
        let result: Vec<ElementRef> = dom.select(&selector).collect();
        let el = match result.get(0) {
            Some(el) => el,
            None => {
                return Err(Box::new(HnError::HtmlParsingError));
            }
        };
        let fnid = extract_fnid(el)?;
    
        Ok(fnid)
    }

    pub fn login(&self) -> Result<(), Box<dyn Error>> {
        let mut formdata = HashMap::new();
        formdata.insert("acct", &self.username);
        formdata.insert("pw", &self.password);
        let goto = "newest".to_string();
        formdata.insert("goto", &goto);

        let mut headers = HeaderMap::new();
        headers.insert("User-Agent", "hacker-news client/0.0.1".parse().unwrap());

        // Login request requires no redirect on response, therefore we build a 
        // new one rather than referencing self.http_client.
        // TODO: Is there a better way to accomodate this?
        let client = ClientBuilder::new()
            .redirect(Policy::none())
            .build()?;

        // Send login request
        let req = client.post(URL_LOGIN)
            .headers(headers)
            .form(&formdata);
        log::debug!("login request = {:?}", req);
        let resp = req.send()?;
        if resp.status().as_u16() != 302 {
            log::error!("login response = {:?}", resp);
            return Err(Box::new(HnError::AuthenticationError));
        }
        log::debug!("login response = {:?}", resp);

        // Store user session cookie
        let cookies: Vec<Cookie> = resp.cookies().collect();
        let cookie = cookies.get(0)
            // .ok_or("Unable to retrieve user cookie")?;
            .ok_or_else(|| {
                log::error!("Unable to parse user cookie from succesful login response, \
                    response = {:?}, cookies = {:?}", resp, cookies);
                HnError::HtmlParsingError
            })?;
        let cookie = Some((cookie.name().to_string(), cookie.value().to_string()));

        // Store on client instance field
        *self.cookie.borrow_mut() = cookie;
        println!("cookie = {:?}", self.cookie);

        Ok(())
    }
    
    pub fn item(&self, id: Id) -> Result<Listing, Box<dyn Error>> {
        let url = format!("https://news.ycombinator.com/item?id={}", id);
        let req = self.http_client.get(&url);
        log::debug!("Send GET request to {:?}", url);
        let resp = req.send()?;
        let status = resp.status().as_u16();
        if status != 200 {
            let err = HttpError {
                url: resp.url().to_string(),
                code: status,
            };
            log::error!("Received non-200 response: {:?}", err);
            return Err(Box::new(HnError::HttpError(err)));
        }
        log::debug!("Received 200 response from {:?}", url);

        let text = resp.text()?;
        let html = Html::parse_document(&text);

        // Note: There is an assumption here that given an item ID, we should
        // only extract one listing from a page. Therefore, we can simply pop once
        // from the Vec obtained by extract listings.

        let item = ListingsParser::parse(&html)?
            .pop()
            .ok_or(format!("Did not find item {}", id))?;

        Ok(item)
    }

    pub fn thread(&self, id: Id) -> Result<Thread, Box<dyn Error>> {
        log::debug!("HTML client attempting comments for id = {:?}", id);
        let url = format!("https://news.ycombinator.com/item?id={}", id);
        let req = self.http_client.get(&url);
        let resp = req.send()?;
        let text = resp.text()?;
        let html = Html::parse_document(&text);
        let comments = CommentsParser::parse(&html)?;
        let comments = create_comment_tree(comments);
        let listings = ListingsParser::parse(&html)?;
        if listings.len() > 1 {
            log::warn!("Parsed multiple listings for a thread, where only 1 is expected");
        }
        let listing = listings.into_iter()
            .next()
            .ok_or_else(|| {
                log::error!("Succesfully parsed HTML, but found no listings");
                HnError::HtmlParsingError
            })?;
        let thread = Thread { listing, comments };
        
        Ok(thread)
    }

    pub fn news(&self) -> Result<Vec<Listing>, Box<dyn Error>> {
        self.listings("https://news.ycombinator.com/news")
    }

    pub fn past(&self, date: Date) -> Result<Vec<Listing>, Box<dyn Error>> {
        let url = format!("https://news.ycombinator.com/front?day={}-{}-{}",
            date.0, date.1, date.2);

        self.listings(&url)
    }

    /// Retrieve a page of HackerNews Listings, such as that delivered from:
    /// * `https://news.ycombinator.com/`
    /// * `https://news.ycombinator.com/newest`
    /// * `https://news.ycombinator.com/front`
    /// * `https://news.ycombinator.com/newcomments`
    /// * `https://news.ycombinator.com/ask`
    /// * `https://news.ycombinator.com/show`
    /// * `https://news.ycombinator.com/jobs`
    pub fn listings(&self, url: &str) -> Result<Vec<Listing>, Box<dyn Error>> {
        let req = self.http_client.get(url);
        let resp = req.send()?;
        let text = resp.text()?;
        let html = Html::parse_document(&text);
        let listings = ListingsParser::parse(&html)?;

        Ok(listings)
    }
}


#[cfg(test)]
mod tests {

    use super::*;

    use crate::util::setup;

    #[test]
    fn test_news() -> Result<(), Box<dyn Error>> {
        setup();
        let client = Client::new("filler_user", "filler_pwd");
        let listings = client.news()?;
        log::info!("Successfully called Client::news()");
        log::trace!("Listings output from Client::news() = {:?}", listings);

        Ok(())
    }

    #[test]
    fn test_item() -> Result<(), Box<dyn Error>> {
        setup();
        let client = Client::new("filler_user", "filler_pwd");
        let item = client.item(25925926)?;
        log::debug!("test_item item = {:#?}", item);

        Ok(())
    }

    #[test]
    fn test_comments() -> Result<(), Box<dyn Error>> {
        setup();
        let client = Client::new("", "");
        let comments = client.thread(100)?;
        log::debug!("comments = {:?}", comments);

        Ok(())
    }

    #[test]
    fn test_login() -> Result<(), Box<dyn Error>> {
        setup();
        let user: String = match std::env::var("HN_USER") {
            Ok(user) => user,
            Err(_) => {
                log::warn!("login test unable to retrieve Hacker News username from \
                environment variable $HN_USER. Omitting test.");
                return Ok(());
            }
        };

        let pwd: String = match std::env::var("HN_PASS") {
            Ok(pwd) => pwd,
            Err(_) => {
                log::warn!("login test unable to retrieve Hacker News password from \
                environment variable $HN_PASS. Omitting test.");
                return Ok(());
            }
        };
        
        let client = Client::new(&user, &pwd);
        client.login()?;

        Ok(())
    }

}