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
//! hn-rs: Bindings for Hacker News (YCombinator) news feed API
//!
//! hn-rs is a simple binding around the firebase APIs for fetching the news
//! feed from Hacker News.  It spawns a thread that regularly updates the top
//! 60 items on Hacker News.
//!
//! The main class, `HackerNews`, exposes this list in the most recently sorted
//! order as a standard Rust iterator.  The iterator returns copies of the items
//! so the application can keep ownership if it wishes.
//!
//! Currently it only exposes methods to request the title and URL of news items.
//!
//! News items can be marked as 'hidden' so they are not returned in future
//! passes through the iterator.
//!
//! See the `examples/` dir for usage.
//!
extern crate time;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate futures;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;

use futures::future::Future;
use futures::future::Either;
use futures::stream::Stream;

use std::str::FromStr;
use std::time::Duration;
use std::thread;
use std::sync::Arc;
use std::sync::RwLock;
use std::collections::BTreeMap;

use hyper::Uri;
use hyper::client::Client;
use hyper::client::HttpConnector;
use hyper_tls::HttpsConnector;

use tokio_core::reactor::Core;
use tokio_core::reactor::Handle;

const HN_URL_TOP_STORIES: &'static str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const HN_URL_ITEM: &'static str = "https://hacker-news.firebaseio.com/v0/item/";
const HN_URL_DISCUSSION: &'static str = "https://news.ycombinator.com/item?id=";

/// Stores the metadata about a single news item
#[derive(Deserialize, Debug, Clone)]
pub struct Item {
    by: String,
    descendants: Option<u64>,
    id: u64,
    kids: Option<Vec<u64>>,
    score: Option<u32>,
    time: u64,
    title: Option<String>,
    text: Option<String>,
    #[serde(rename(deserialize = "type"))]
    item_type: String,
    url: Option<String>,

    //
    // INTERNAL.  Not deserialized from HN JSON
    //
    #[serde(default)]
    seen: bool,
    #[serde(default)]
    hidden: bool,
}

impl Item {
    /// Return the title of the news item
    pub fn title(&self) -> String {
        self.title.clone().unwrap_or("".to_string())
    }
    /// Return the URL of the news item.
    ///
    /// This is the link to the external (non-HN) website if it has one, or a
    /// link to the HN comment section for stories without external links.
    pub fn url(&self) -> String {
        match self.url {
            Some(ref url) => url.clone(),
            None => format!("{}{}", HN_URL_DISCUSSION, self.id),
        }
    }
}

#[doc(hidden)]
#[derive(Clone,Default)]
pub struct Cache {
    x: Arc<RwLock<BTreeMap<u64, Item>>>,
}
impl std::ops::Deref for Cache {
    type Target = RwLock<BTreeMap<u64, Item>>;
    fn deref(&self) -> &Self::Target { &*self.x }
}

#[doc(hidden)]
#[derive(Clone,Default)]
pub struct TopList {
    x: Arc<RwLock<Vec<u64>>>,
}
impl std::ops::Deref for TopList {
    type Target = RwLock<Vec<u64>>;
    fn deref(&self) -> &Self::Target { &*self.x }
}

#[doc(hidden)]
#[derive(Default)]
pub struct IHackerNews {
    pub top: TopList,
    pub cache: Cache,
}

/// Main interface to the Hacker News API
///
/// # Examples
///
/// ```rust
/// extern crate hn;
/// use std::time::Duration;
/// use std::thread;
///
/// fn main() {
///   let hn = hn::HackerNews::new();
///   while hn.into_iter().count() == 0 {
///       thread::sleep(Duration::from_millis(1000));
///   }
///   for item in hn.into_iter() {
///       println!("item: {}", item.title());
///   }
/// }
/// ```
///
#[derive(Clone,Default)]
pub struct HackerNews {
    x: Arc<IHackerNews>,
}
impl std::ops::Deref for HackerNews {
    type Target = IHackerNews;
    fn deref(&self) -> &Self::Target { &*self.x }
}
impl<'a> IntoIterator for &'a HackerNews {
    type Item = Item;
    type IntoIter = HackerNewsIterator<'a>;
    fn into_iter(self) -> Self::IntoIter {
        HackerNewsIterator {
            hn: self,
            idx: 0,
        }
    }
}

/// Iterator for iterating over HN news stories
///
/// Items are returned in the same order that they were prioritized on HN at
/// the time of the last update.
pub struct HackerNewsIterator<'a> {
    hn: &'a HackerNews,
    idx: usize,
}
impl<'a> Iterator for HackerNewsIterator<'a> {
    type Item = Item;
    fn next(&mut self) -> Option<Item> {
        let reader = self.hn.top.read().unwrap();
        while self.idx < reader.len() {
            let item: Option<&u64> = (*reader).get(self.idx);
            self.idx += 1;
            if let Some(item) = item {
                if let Some(item) = self.hn.cache.write().unwrap().get_mut(item) {
                    if !item.hidden {
                        item.seen = true;
                        return Some((*item).clone());
                    }
                }
            }
        }
        self.idx = 0;
        None
    }
}

impl HackerNews {
    /// Return a newly allocated HN wrapper, and spawn background thread
    pub fn new() -> HackerNews {
        let hn: HackerNews = Default::default();
        let thread_hn = hn.clone();
        let _ = thread::spawn(move || {
            HackerNews::hn_thread(thread_hn);
        });
        hn
    }
    /// Return number of items currently in the 'top list'
    pub fn len(&self) -> usize {
        self.top.read().unwrap().len()
    }
    /// Hide an item so it isn't returned in future iterator passes
    pub fn hide(&self, item: &Item) {
        let id = item.id;
        if let Some(item) = self.cache.write().unwrap().get_mut(&id) {
            item.hidden = true;
        }
    }
    fn hn_thread(hn: HackerNews) {
        let mut core = Core::new().unwrap();
        let handle = core.handle();
        let https = HttpsConnector::new(4, &handle).unwrap();
        let client = Client::configure()
            .keep_alive(true)
            .connector(https)
            .build(&handle);
        let mut last_update_time = 0;
        loop {
            let now = time::now_utc().to_timespec().sec as i64;
            if now > last_update_time + 10 {
                if HackerNews::update_top_stories(&mut core, &client, &hn.top).is_ok() {
                    HackerNews::update_item_cache(&client, &handle, &hn.top, &hn.cache);
                }
                last_update_time = now;
            }
            core.turn(Some(Duration::from_millis(100)));
        }
    }
    fn update_top_stories(core: &mut Core,
                          client: &Client<HttpsConnector<HttpConnector>>,
                          top: &RwLock<Vec<u64>>) -> Result<(), hyper::error::Error> {
        let handle = core.handle();
        let uri = Uri::from_str(HN_URL_TOP_STORIES).ok().unwrap();
        let request = client.get(uri).and_then(|res| {
            res.body().concat2()
        });

        let timeout = tokio_core::reactor::Timeout::new(Duration::from_millis(5000), &handle).unwrap();
        let timed_request = request.select2(timeout).then(|res| match res {
            Ok(Either::A((data, _timeout))) => Ok(data),
            Ok(Either::B((_timeout_error, _get))) => {
                Err(hyper::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "Timed out requesting top list",
                )))
            }
            Err(Either::A((error, _timeout))) => Err(error),
            Err(Either::B((timeout_error, _get))) => Err(From::from(timeout_error)),
        });

        let got = core.run(timed_request)?;
        let top_stories_str = std::str::from_utf8(&got).unwrap();
        {
            let mut writer = top.write().unwrap();
            let top_stories: Result<Vec<u64>,_> = serde_json::from_str(top_stories_str);
            if let Ok(mut top_stories) = top_stories {
                top_stories.truncate(60);
                *writer = top_stories;
            }
        }
        Ok(())
    }
    fn update_item_cache(client: &Client<HttpsConnector<HttpConnector>>,
                         handle: &Handle,
                         top: &RwLock<Vec<u64>>,
                         cache: &Cache) {
        let stories = top.read().unwrap();
        let stories: Vec<&u64>  = stories.iter().filter(|s| {
            let reader = cache.read().unwrap();
            !(*reader).contains_key(*s)
        }).collect();
        let mut req_count = 0;
        for story in stories {
            if req_count >= 60 {
                // Max 60 per batch
                break;
            }
            let uri = format!("{}{}.json", HN_URL_ITEM, story);
            let id = story.clone();
            let uri = Uri::from_str(&uri).ok().unwrap();
            let future_cache = cache.clone();
            let req = client.get(uri).and_then(|res| {
                res.body().concat2()
            }).then(move |body| {
                if body.is_err() {
                    return Err(());
                }
                let body = body.unwrap();
                let item_str = std::str::from_utf8(&body).unwrap();
                let item: Result<Item,_> = serde_json::from_str(item_str);
                if let Ok(item) = item {
                    let mut writer = future_cache.write().unwrap();
                    (*writer).insert(id, item);
                }
                Ok(())
            });

            let timeout = tokio_core::reactor::Timeout::new(Duration::from_millis(5000), &handle).unwrap();
            let timed_request = req.select2(timeout).then(|_| { Ok(()) });
            handle.spawn(timed_request);
            req_count += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn init() {
        use super::HackerNews;
        use std::time::Duration;
        use std::thread;
        let _ = HackerNews::new();
        thread::sleep(Duration::from_millis(300));
    }
}