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
|
use anyhow::{bail, Context};
use downloader::Downloadable;
use serde::Deserialize;
use url::Url;
pub mod constants;
pub mod downloader;
#[derive(Deserialize)]
pub struct YtccListData {
pub url: String,
pub title: String,
pub description: String,
pub publish_date: String,
pub watch_date: Option<f64>,
pub duration: String,
pub thumbnail_url: Option<String>,
pub extractor_hash: String,
pub id: u32,
pub playlists: Vec<YtccPlaylistData>,
}
impl std::fmt::Display for YtccListData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
f,
r#"pick {} "{}" "{}" "{}" "{}" "{}"{}"#,
self.id,
self.title.replace(['"', '„', '”'], "'"),
self.publish_date,
self.playlists
.iter()
.map(|p| p.name.replace('"', "'"))
.collect::<Vec<String>>()
.join(", "),
Duration::from(self.duration.trim()),
self.url.replace('"', "'"),
"\n"
)
}
}
#[derive(Deserialize)]
pub struct YtccPlaylistData {
pub name: String,
pub url: String,
pub reverse: bool,
}
pub enum LineCommand {
Pick,
Drop,
Watch,
Url,
}
impl std::str::FromStr for LineCommand {
type Err = anyhow::Error;
fn from_str(v: &str) -> Result<Self, <Self as std::str::FromStr>::Err> {
match v {
"pick" | "p" => Ok(Self::Pick),
"drop" | "d" => Ok(Self::Drop),
"watch" | "w" => Ok(Self::Watch),
"url" | "u" => Ok(Self::Url),
other => bail!("'{}' is not a recognized command!", other),
}
}
}
pub struct Line {
pub cmd: LineCommand,
pub id: u32,
pub url: Url,
}
/// We expect that each line is correctly formatted, and simply use default ones if they are not
impl From<&str> for Line {
fn from(v: &str) -> Self {
let buf: Vec<_> = v.split_whitespace().collect();
let url: Url = Url::parse(
buf.last()
.expect("This should always exists")
.trim_matches('"'),
)
.expect("This parsing should work,as the url is generated");
Line {
cmd: buf
.get(0)
.unwrap_or(&"pick")
.parse()
.unwrap_or(LineCommand::Pick),
id: buf.get(1).unwrap_or(&"0").parse().unwrap_or(0),
url,
}
}
}
pub struct Duration {
time: u32,
}
impl From<&str> for Duration {
fn from(v: &str) -> Self {
let buf: Vec<_> = v.split(':').take(2).collect();
Self {
time: (buf[0].parse::<u32>().expect("Should be a number") * 60)
+ buf[1].parse::<u32>().expect("Should be a number"),
}
}
}
impl std::fmt::Display for Duration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
const SECOND: u32 = 1;
const MINUTE: u32 = 60 * SECOND;
const HOUR: u32 = 60 * MINUTE;
let base_hour = self.time - (self.time % HOUR);
let base_min = (self.time % HOUR) - ((self.time % HOUR) % MINUTE);
let base_sec = (self.time % HOUR) % MINUTE;
let h = base_hour / HOUR;
let m = base_min / MINUTE;
let s = base_sec / SECOND;
if self.time == 0 {
write!(f, "[No Duration]")
} else if h > 0 {
write!(f, "[{h}h {m}m]")
} else {
write!(f, "[{m}m {s}s]")
}
}
}
#[cfg(test)]
mod test {
use crate::Duration;
#[test]
fn test_display_duration_1h() {
let dur = Duration { time: 60 * 60 };
assert_eq!("[1h 0m]".to_owned(), dur.to_string());
}
#[test]
fn test_display_duration_30min() {
let dur = Duration { time: 60 * 30 };
assert_eq!("[30m 0s]".to_owned(), dur.to_string());
}
}
pub fn ytcc_drop(id: u32) -> anyhow::Result<()> {
let mut ytcc = std::process::Command::new("ytcc");
ytcc.args(["mark", &format!("{}", id)]);
if !ytcc.status().context("Failed to run ytcc")?.success() {
bail!("`ytcc mark {}` failed to execute", id)
}
Ok(())
}
pub fn filter_line(line: &str) -> anyhow::Result<Option<Downloadable>> {
// Filter out comments and empty lines
if line.starts_with('#') || line.trim().is_empty() {
return Ok(None);
}
let line = Line::from(line);
match line.cmd {
LineCommand::Pick => Ok(None),
LineCommand::Drop => ytcc_drop(line.id)
.with_context(|| format!("Failed to drop: {}", line.id))
.map(|_| None),
LineCommand::Watch => Ok(Some(Downloadable {
id: Some(line.id),
url: line.url,
})),
LineCommand::Url => {
let mut firefox = std::process::Command::new("firefox");
firefox.args(["-P", "timesinks.youtube"]);
firefox.arg(line.url.as_str());
let _handle = firefox.spawn().context("Failed to run firefox")?;
Ok(None)
}
}
}
|