aboutsummaryrefslogtreecommitdiffstats
path: root/src/playback.rs
blob: 05196ddc6d0b74c8b49eab446936115b6dc0a660 (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
use crate::errors::*;
use crate::structs::*;
use crate::utils::*;

use std::fs::{DirBuilder, File};
use std::io::{self, BufReader, Read, Write};
use std::process::Command;

use regex::Regex;
use rss::Channel;
use std::path::PathBuf;

fn launch_player(url: &str) -> Result<()> {
    if launch_mpv(url).is_err() {
        return launch_vlc(url);
    }
    Ok(())
}

fn launch_mpv(url: &str) -> Result<()> {
    if let Err(err) = Command::new("mpv")
        .args(&["--audio-display=no", "--ytdl=no", url])
        .status()
    {
        let stderr = io::stderr();
        let mut handle = stderr.lock();
        match err.kind() {
            io::ErrorKind::NotFound => {
                writeln!(&mut handle, "Couldn't open mpv\nTrying vlc...").ok()
            }
            _ => writeln!(&mut handle, "Error: {}", err).ok(),
        };
    }
    Ok(())
}

fn launch_vlc(url: &str) -> Result<()> {
    if let Err(err) = Command::new("vlc").args(&["-I ncurses", url]).status() {
        let stderr = io::stderr();
        let mut handle = stderr.lock();
        match err.kind() {
            io::ErrorKind::NotFound => writeln!(&mut handle, "Couldn't open vlc...aborting").ok(),
            _ => writeln!(&mut handle, "Error: {}", err).ok(),
        };
    }
    Ok(())
}

pub fn play_latest(state: &State, p_search: &str) -> Result<()> {
    let re_pod: Regex = Regex::new(&format!("(?i){}", &p_search))?;
    let mut path: PathBuf = get_xml_dir()?;
    DirBuilder::new().recursive(true).create(&path)?;
    for subscription in &state.subscriptions {
        if re_pod.is_match(&subscription.title) {
            let mut filename: String = subscription.title.clone();
            filename.push_str(".xml");
            path.push(filename);

            let file: File = File::open(&path)?;
            let podcast: Podcast = Podcast::from(Channel::read_from(BufReader::new(file))?);
            let episodes = podcast.episodes();
            let episode = episodes[0].clone();

            filename = episode.title().unwrap();
            filename.push_str(&episode.extension().unwrap());
            path = get_podcast_dir()?;
            path.push(podcast.title());
            path.push(filename);
            if path.exists() {
                launch_player(path.to_str().unwrap())?;
            } else {
                launch_player(episode.url().unwrap())?;
            }
            return Ok(());
        }
    }
    Ok(())
}

pub fn play_episode_by_num(state: &State, p_search: &str, ep_num_string: &str) -> Result<()> {
    let re_pod: Regex = Regex::new(&format!("(?i){}", &p_search))?;
    if let Ok(ep_num) = ep_num_string.parse::<usize>() {
        let mut path: PathBuf = get_xml_dir()?;
        let stderr = io::stderr();
        let mut handle = stderr.lock();
        if let Err(err) = DirBuilder::new().recursive(true).create(&path) {
            writeln!(
                &mut handle,
                "Couldn't create directory: {}\nReason: {}",
                path.to_str().unwrap(),
                err
            )
            .ok();
            return Ok(());
        }
        for subscription in &state.subscriptions {
            if re_pod.is_match(&subscription.title) {
                let mut filename: String = subscription.title.clone();
                filename.push_str(".xml");
                path.push(filename);

                let file: File = File::open(&path).unwrap();
                let podcast = Podcast::from(Channel::read_from(BufReader::new(file)).unwrap());
                let episodes = podcast.episodes();
                let episode = episodes[episodes.len() - ep_num].clone();

                filename = episode.title().unwrap();
                filename.push_str(&episode.extension().unwrap());
                path = get_podcast_dir()?;
                path.push(podcast.title());
                path.push(filename);
                if path.exists() {
                    launch_player(path.to_str().unwrap())?;
                } else {
                    launch_player(episode.url().unwrap())?;
                }
                return Ok(());
            }
        }
    } else {
        {
            let stdout = io::stdout();
            let mut handle = stdout.lock();
            writeln!(&mut handle, "Failed to parse episode index number...").ok();
            writeln!(&mut handle, "Attempting to find episode by name...").ok();
        }
        play_episode_by_name(state, p_search, ep_num_string)?;
    }
    Ok(())
}

pub fn play_episode_by_name(state: &State, p_search: &str, ep_string: &str) -> Result<()> {
    let re_pod: Regex = Regex::new(&format!("(?i){}", &p_search))?;
    let mut path: PathBuf = get_xml_dir()?;
    if let Err(err) = DirBuilder::new().recursive(true).create(&path) {
        let stderr = io::stderr();
        let mut handle = stderr.lock();
        writeln!(
            &mut handle,
            "Couldn't create directory: {:?}\nReason: {}",
            path, err
        )
        .ok();
        return Ok(());
    }
    for subscription in &state.subscriptions {
        if re_pod.is_match(&subscription.title) {
            let mut filename: String = subscription.title.clone();
            filename.push_str(".xml");
            path.push(filename);

            let mut file: File = File::open(&path).unwrap();
            let mut content: Vec<u8> = Vec::new();
            file.read_to_end(&mut content).unwrap();

            let podcast = Podcast::from(Channel::read_from(content.as_slice()).unwrap());
            let episodes = podcast.episodes();
            let filtered_episodes: Vec<&Episode> = episodes
                .iter()
                .filter(|ep| {
                    ep.title()
                        .unwrap_or_else(|| "".to_string())
                        .to_lowercase()
                        .contains(&ep_string.to_lowercase())
                })
                .collect();
            if let Some(episode) = filtered_episodes.first() {
                filename = episode.title().unwrap();
                filename.push_str(&episode.extension().unwrap());
                path = get_podcast_dir()?;
                path.push(podcast.title());
                path.push(filename);
                if path.exists() {
                    launch_player(path.to_str().unwrap())?;
                } else {
                    launch_player(episode.url().unwrap())?;
                }
            }
            return Ok(());
        }
    }
    Ok(())
}