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
extern crate serde_derive;
extern crate uuid;

use std::fmt;
use std::fs::File;
use std::io;
use std::io::Write;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer};
use serde::de::{Error, Unexpected};

use category::Category;
use episode_info::EpisodeInfo;

use self::serde_derive::{Deserialize, Serialize};
use self::uuid::Uuid;

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Torrent {
    title: Option<String>,
    filename: Option<String>,
    category: Category,
    download: String,
    seeders: Option<u32>,
    leechers: Option<u32>,
    size: Option<u128>,
    pubdate: Option<DateTime<Utc>>,
    episode_info: Option<EpisodeInfo>,
    #[serde(default, deserialize_with = "bool_from_int")]
    ranked: Option<bool>,
    info_page: Option<String>,
}

impl Torrent {
    /// Return the title.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn title(&self) -> &Option<String> { &self.title }

    /// Return the filename
    ///
    /// Only available when `format` is set to `Format::Json`.
    pub fn filename(&self) -> &Option<String> { &self.filename }

    /// Return the category that the torrent belongs to.
    pub fn category(&self) -> &Category {
        &self.category
    }

    /// Return a magnet link.
    pub fn download(&self) -> &String { &self.download }

    /// Return the number of seeders available.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn seeders(&self) -> &Option<u32> {
        &self.seeders
    }

    /// Return the number of leechers.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn leechers(&self) -> &Option<u32> {
        &self.leechers
    }

    /// Return the size in bytes.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn size(&self) -> &Option<u128> {
        &self.size
    }

    /// Return the publication date.
    ///
    /// DateTime is always synchronize with UTC.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn pub_date(&self) -> &Option<DateTime<Utc>> {
        &self.pubdate
    }

    /// Return the episode info.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn episode_info(&self) -> &Option<EpisodeInfo> {
        &self.episode_info
    }

    /// Return true if it's a scene, rarbg or rartv releases, otherwise false.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn ranked(&self) -> &Option<bool> {
        &self.ranked
    }

    /// Return an HTTP link that redirect to the torrent page.
    ///
    /// Only available when `format` is set to `Format::JsonExtended`.
    pub fn info_page(&self) -> &Option<String> {
        &self.info_page
    }

    /// Export the torrent to a magnet file using its title, filename or UUID as filename.
    ///
    /// # Arguments
    ///
    /// * `path` - A string slice that holds a path to a **folder**
    ///
    pub fn export(&self, path: &str) -> Result<String, io::Error> {
        let filename = match self.title() {
            Some(title) => title.clone(),
            None => match self.filename() {
                Some(filename) => filename.clone(),
                None => Uuid::new_v4().to_string()
            },
        };
        let filepath = format!("{}/{}.magnet", path, filename);
        let file = File::create(&filepath);
        if file.is_err() {
            return Err(file.unwrap_err());
        }
        match file.unwrap().write_all(self.download.as_bytes()) {
            Ok(_) => Ok(filepath),
            Err(reason) => Err(reason),
        }
    }
}

impl fmt::Display for Torrent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

// https://github.com/serde-rs/serde/issues/1344#issuecomment-410309140
fn bool_from_int<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error> where D: Deserializer<'de>, {
    match u8::deserialize(deserializer)? {
        0 => Ok(Some(false)),
        1 => Ok(Some(true)),
        other => Err(Error::invalid_value(
            Unexpected::Unsigned(other as u64),
            &"zero or one",
        )),
    }
}