Advertisement
Guest User

Untitled

a guest
Dec 29th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.03 KB | None | 0 0
  1. use std::error::Error;
  2. use std::fs::File;
  3. use std::io::{BufReader, Read, Write};
  4. use std::path::{MAIN_SEPARATOR, PathBuf};
  5.  
  6. extern crate hyper;
  7. use hyper::client::Client;
  8. use hyper::client::response::Response;
  9. use hyper::header::UserAgent;
  10.  
  11. extern crate rss;
  12. use rss::Channel;
  13.  
  14. const EXTENSION: &'static str = "torrent";
  15. const USER_AGENT: &'static str = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.53 Safari/525.19";
  16.  
  17. const PATH: &'static str = "/tmp";
  18. const URLS: [&'static str; 1] = [
  19.     "https://www.nyaa.se/?page=rss&term=horriblesubs+hibike+euphonium+s2+1080",
  20. ];
  21.  
  22. fn get(client: &Client, url: &str) -> Result<Response, hyper::Error> {
  23.     client.get(url).header(UserAgent(USER_AGENT.to_string())).send()
  24. }
  25.  
  26. fn save(data: &[u8], name: &str) -> Result<(), Box<Error>> {
  27.     let name = name.replace(MAIN_SEPARATOR, "-");
  28.     let mut buf = PathBuf::from(PATH);
  29.     buf.push(&name);
  30.     buf.set_extension(EXTENSION);
  31.     let path = buf.as_path();
  32.     if !path.exists() {
  33.         let mut file = File::create(path)?;
  34.         file.write(data)?;
  35.     }
  36.     Ok(())
  37. }
  38.  
  39. fn torrent(client: &Client, url: Option<String>, name: Option<String>) -> Result<(), Box<Error>> {
  40.     let url = url.ok_or("no url")?;
  41.     let name = name.ok_or("no name")?;
  42.     let mut response = get(client, &url)?;
  43.     let mut body = vec![];
  44.     response.read_to_end(&mut body)?;
  45.     save(&body, &name)
  46. }
  47.  
  48. fn feed(client: &Client, url: &str) -> Result<(), Box<Error>> {
  49.     let response = get(client, url)?;
  50.     let reader = BufReader::new(response);
  51.     let channel = Channel::read_from(reader)?;
  52.     for item in channel.items {
  53.         if let Err(e) = torrent(client, item.link.clone(), item.title.clone()) {
  54.             println!("{} {}", item.link.unwrap_or("item".to_string()), e);
  55.         }
  56.     }
  57.     Ok(())
  58. }
  59.  
  60. fn main() {
  61.     let client = Client::new();
  62.     for url in URLS.iter() {
  63.         if let Err(e) = feed(&client, url) {
  64.             println!("{} {}", url, e);
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement