aboutsummaryrefslogtreecommitdiffstats
path: root/src/structs.rs
blob: 07cb901b82a959aff5070465f63efc2d8ce35ec4 (plain)
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
use actions::*;
use chrono::prelude::*;
use rayon::prelude::*;
use reqwest;
use rss::{self, Channel, Item};
use serde_json;
use std::collections::BTreeSet;
use std::fs::{self, DirBuilder, File};
use std::io::{self, Read, Write};
use utils::*;

#[derive(Serialize, Deserialize, Clone)]
pub struct Subscription {
    title: String,
    url: String,
}

impl Subscription {
    pub fn title(&self) -> String {
        self.title.clone()
    }

    pub fn url(&self) -> String {
        self.url.clone()
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub struct State {
    last_run_time: DateTime<Utc>,
    subs: Vec<Subscription>,
}

impl State {
    pub fn new() -> State {
        let mut path = get_podcast_dir();
        path.push(".subscriptions");
        if path.exists() {
            let mut s = String::new();
            File::open(&path).unwrap().read_to_string(&mut s).unwrap();
            let mut state: State = serde_json::from_str(&s).unwrap();
            // Check if a day has passed (86400 seconds)
            if state
                .last_run_time
                .signed_duration_since(Utc::now())
                .num_seconds() < -86400
            {
                update_rss(&state.clone());
            }
            state.last_run_time = Utc::now();
            state
        } else {
            State {
                last_run_time: Utc::now(),
                subs: Vec::new(),
            }
        }
    }

    pub fn subscribe(&mut self, url: &str) {
        let mut set = BTreeSet::new();
        for sub in self.subscriptions() {
            set.insert(sub.title());
        }
        let channel = Channel::from_url(url).unwrap();
        if !set.contains(channel.title()) {
            self.subs.push(Subscription {
                title: String::from(channel.title()),
                url: String::from(url),
            });
        }
        if let Err(err) = self.save() {
            eprintln!("{}", err);
        }
        download_rss(url);
    }

    pub fn subscriptions(&self) -> Vec<Subscription> {
        self.subs.clone()
    }

    pub fn save(&self) -> Result<(), io::Error> {
        let mut path = get_podcast_dir();
        DirBuilder::new().recursive(true).create(&path).unwrap();
        path.push(".subscriptions.tmp");
        let serialized = serde_json::to_string(self)?;
        let mut file = File::create(&path)?;
        file.write_all(serialized.as_bytes())?;
        fs::rename(&path, get_sub_file())?;
        Ok(())
    }
}

#[derive(Clone)]
pub struct Podcast(Channel);

#[derive(Clone)]
pub struct Episode(Item);

impl From<Channel> for Podcast {
    fn from(channel: Channel) -> Podcast {
        Podcast(channel)
    }
}

impl From<Item> for Episode {
    fn from(item: Item) -> Episode {
        Episode(item)
    }
}

impl Podcast {
    pub fn title(&self) -> &str {
        self.0.title()
    }

    #[allow(dead_code)]
    pub fn url(&self) -> &str {
        self.0.link()
    }

    pub fn from_url(url: &str) -> Result<Podcast, rss::Error> {
        match Channel::from_url(url) {
            Ok(val) => Ok(Podcast::from(val)),
            Err(err) => Err(err),
        }
    }

    pub fn episodes(&self) -> Vec<Episode> {
        let mut result = Vec::new();

        let items = self.0.items().to_vec();
        for item in items {
            result.push(Episode::from(item));
        }
        result
    }

    pub fn download(&self) {
        let mut path = get_podcast_dir();
        path.push(self.title());

        let downloaded = already_downloaded(self.title());

        self.episodes().par_iter().for_each(
            |ref i| if let Some(ep_title) =
                i.title()
            {
                if !downloaded.contains(ep_title) {
                    if let Err(err) = i.download(self.title()) {
                        println!("{}", err);
                    }
                }
            },
        );
    }

    pub fn download_specific(&self, episode_numbers: Vec<usize>) {
        let mut path = get_podcast_dir();
        path.push(self.title());

        let downloaded = already_downloaded(self.title());
        let episodes = self.episodes();

        episode_numbers.par_iter().for_each(
            |ep_num| if let Some(ep_title) =
                episodes[episodes.len() - ep_num].title()
            {
                if !downloaded.contains(ep_title) {
                    if let Err(err) = episodes[episodes.len() - ep_num].download(self.title()) {
                        println!("{}", err);
                    }
                }
            },
        );
    }
}

impl Episode {
    pub fn title(&self) -> Option<&str> {
        self.0.title()
    }

    pub fn url(&self) -> Option<&str> {
        match self.0.enclosure() {
            Some(val) => Some(val.url()),
            None => None,
        }
    }

    pub fn extension(&self) -> Option<&str> {
        match self.0.enclosure() {
            Some(enclosure) => {
                match enclosure.mime_type() {
                    "audio/mpeg" => Some(".mp3"),
                    "audio/mp4" => Some(".m4a"),
                    "audio/ogg" => Some(".ogg"),
                    _ => None,
                }
            }
            None => None,
        }
    }

    pub fn download(&self, podcast_name: &str) -> Result<(), io::Error> {
        let mut path = get_podcast_dir();
        path.push(podcast_name);
        DirBuilder::new().recursive(true).create(&path).unwrap();

        if let Some(url) = self.url() {
            if let Some(title) = self.title() {
                println!("Downloading: {}", title);
                let mut filename = String::from(title);
                filename.push_str(self.extension().unwrap());
                path.push(filename);
                let mut file = File::create(&path)?;
                let mut resp = reqwest::get(url).unwrap();
                let mut content: Vec<u8> = Vec::new();
                resp.read_to_end(&mut content)?;
                file.write_all(&content)?;
                return Ok(());
            }
        }
        Ok(())
    }
}