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
use clap::{self, App, Arg};
use csv;
use reqwest;
use std::{fmt, io, num, path::PathBuf};

mod consts;
mod episodes;
mod file_system;
mod podcasts;
mod web;

#[derive(Debug)]
pub enum Errors {
    RSS,
    WrongID(String),
    Parse(num::ParseIntError),
    IO(io::Error),
    CSV(csv::Error),
    Timeout(String),
    NotFound(String),
    Network(reqwest::Error),
}

impl fmt::Display for Errors {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Errors::RSS => write!(f, "Couldn't parse RSS feed"),
            Errors::WrongID(ref id) => write!(f, "Invalid ID: {}", id),
            Errors::Parse(ref e) => write!(f, "Couldn't parse string as number: {}", e),
            Errors::IO(ref e) => write!(f, "IO error: {}", e),
            Errors::CSV(ref e) => write!(f, "CSV error: {}", e),
            Errors::Timeout(ref url) => write!(f, "Network timeout for {}", url),
            Errors::NotFound(ref url) => write!(f, "Resource not found {}", url),
            Errors::Network(ref e) => write!(f, "Network error {}", e),
        }
    }
}

impl From<csv::Error> for Errors {
    fn from(err: csv::Error) -> Errors {
        Errors::CSV(err)
    }
}

impl From<file_system::FileSystemErrors> for Errors {
    fn from(err: file_system::FileSystemErrors) -> Errors {
        match err {
            file_system::FileSystemErrors::CreateFile(e) => Errors::IO(e),
            file_system::FileSystemErrors::CreateDirectory(e) => Errors::IO(e),
            file_system::FileSystemErrors::Rename(e) => Errors::IO(e),
            file_system::FileSystemErrors::Remove(e) => Errors::IO(e),
        }
    }
}

impl From<io::Error> for Errors {
    fn from(err: io::Error) -> Errors {
        Errors::IO(err)
    }
}

impl From<std::num::ParseIntError> for Errors {
    fn from(err: std::num::ParseIntError) -> Errors {
        Errors::Parse(err)
    }
}

#[derive(Debug)]
pub struct Config {
    app_directory: PathBuf,
    download_directory: PathBuf,
}

impl Config {
    pub fn new(app_directory: PathBuf, download_directory: PathBuf) -> Self {
        Self {
            app_directory,
            download_directory,
        }
    }
}

pub struct ApplicationBuilder {
    config: Config,
    app: App<'static>,
    subcommands: Vec<App<'static>>,
}

impl ApplicationBuilder {
    pub fn new(config: Config) -> Self {
        let app = App::new("pcasts")
            .version("1.0.0")
            .author("Dmitry S. <dimashur@gmail.com>")
            .about("CLI util for downloading podcasts");

        Self {
            config,
            app,
            subcommands: vec![],
        }
    }

    pub fn podcasts_subcommand(mut self) -> Self {
        self.subcommands.push(
            App::new("podcasts")
                .arg(
                    // Lists all the previously added podcasts with the add command
                    Arg::with_name("list")
                        .about("Show a list of previously added RSS feeds")
                        .short('l')
                        .long("--list")
                        .conflicts_with_all(&["add", "remove"]),
                )
                .arg(
                    // Adds a new podcasts with the provided RSS feed. doesn't do anything if the
                    // podcast already exists in the list
                    Arg::with_name("add")
                        .about("Add new RSS feed")
                        .short('a')
                        .long("--add")
                        .takes_value(true)
                        .multiple(true)
                        .conflicts_with_all(&["list", "remove"]),
                )
                .arg(
                    // Removes a previously added podcast from the list of saved podcasts
                    Arg::with_name("remove")
                        .about("Remove an existing RSS feed")
                        .short('r')
                        .long("--remove")
                        .takes_value(true)
                        .multiple(true)
                        .conflicts_with_all(&["list", "add"]),
                ),
        );

        self
    }

    pub fn episodes_subcommand(mut self) -> Self {
        self.subcommands.push(
            App::new("episodes")
                .subcommand(
                    // Lists the saved episodes which were previously saved with the update command
                    App::new("list")
                        .about("List episodes. By default lists the episodes of all the podcasts")
                        .arg(
                            // The id of the podcast for which we want to list the episodes. if not
                            // provided, lists the episodes of all the podcasts
                            Arg::with_name("id")
                                .about("Id of the podcast to list")
                                .long("--id")
                                .takes_value(true)
                                .multiple(true),
                        ),
                )
                .subcommand(
                    // Updates the list of episodes for the podcast
                    App::new("update").arg(
                        // The id of the podcast for which we wish to update the list of existing
                        // episodes
                        Arg::with_name("id")
                            .about("ID of the podcast to update")
                            .long("--id")
                            .multiple(true)
                            .takes_value(true),
                    ),
                )
                .subcommand(
                    // Download episodes for a particular podcast
                    App::new("download")
                        .arg(
                            // The id of the podcast for which we wish to download a new episode.
                            Arg::with_name("id")
                                .about("ID of the podcast")
                                .long("--id")
                                .required(true)
                                .takes_value(true),
                        )
                        .arg(
                            // The ids of the episodes we wish to download. if not provided, downloads
                            // all the existing episodes for the podcast
                            Arg::with_name("episode-id")
                                .about("IDs of the episodes to download")
                                .long("--episode-id")
                                .multiple(true)
                                .takes_value(true),
                        )
                        .arg(
                            // The number of episodes to download if no episode id's were provided
                            Arg::with_name("count")
                                .about("Number of episodes to download starting from the most recent one")
                                .long("--count")
                                .conflicts_with("episode-id")
                                .takes_value(true),
                        )
                        .arg(
                            // The list of downloaded episodes for a particular podcast
                            Arg::with_name("list")
                                .about("List the downloaded episodes of the provided podcast")
                                .short('l')
                                .long("--list")
                                .conflicts_with("episode-id"),
                        ),
                ),
        );

        self
    }

    pub fn build(self) -> Application {
        let app = self.app.clone().subcommands(self.subcommands);

        Application::new(self.config, app)
    }
}

#[derive(Debug)]
pub struct Application {
    app: App<'static>,
    config: Config,
}

impl Application {
    pub fn new(config: Config, app: App<'static>) -> Self {
        Self { config, app }
    }

    pub fn run(&mut self) -> Result<(), Errors> {
        let matches = self.app.get_matches_mut();

        if let Some(matches) = matches.subcommand_matches("podcasts") {
            return podcasts::Podcasts::new(matches, &self.config).run();
        }

        if let Some(matches) = matches.subcommand_matches("episodes") {
            return episodes::Episodes::new(matches, &self.config).run();
        }

        Ok(())
    }
}