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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
|
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
//! These functions interact with the storage db in a read-only way. They are added on-demand (as
//! you could theoretically just could do everything with the `get_videos` function), as
//! performance or convince requires.
use std::{fs::File, path::PathBuf};
use anyhow::{Context, Result, bail};
use blake3::Hash;
use log::{debug, trace};
use sqlx::query;
use yt_dlp::wrapper::info_json::InfoJson;
use crate::{
app::App,
storage::{
subscriptions::Subscription,
video_database::{Video, extractor_hash::ExtractorHash},
},
unreachable::Unreachable,
};
use super::{MpvOptions, VideoOptions, VideoStatus, VideoStatusMarker, YtDlpOptions};
mod playlist;
pub use playlist::*;
#[macro_export]
macro_rules! video_from_record {
($record:expr) => {
Video {
description: $record.description.clone(),
duration: $crate::storage::video_database::MaybeDuration::from_maybe_secs_f64(
$record.duration,
),
extractor_hash:
$crate::storage::video_database::extractor_hash::ExtractorHash::from_hash(
$record
.extractor_hash
.parse()
.expect("The db hash should be a valid blake3 hash"),
),
last_status_change: $crate::storage::video_database::TimeStamp::from_secs(
$record.last_status_change,
),
parent_subscription_name: $record.parent_subscription_name.clone(),
publish_date: $record
.publish_date
.map(|pd| $crate::storage::video_database::TimeStamp::from_secs(pd)),
status: {
let marker = $crate::storage::video_database::VideoStatusMarker::from_db_integer(
$record.status,
);
let optional = if let Some(cache_path) = &$record.cache_path {
Some((
PathBuf::from(cache_path),
if $record.is_focused == 1 { true } else { false },
))
} else {
None
};
$crate::storage::video_database::VideoStatus::from_marker(marker, optional)
},
thumbnail_url: if let Some(url) = &$record.thumbnail_url {
Some(url::Url::parse(&url).expect("Parsing this as url should always work"))
} else {
None
},
title: $record.title.clone(),
url: url::Url::parse(&$record.url).expect("Parsing this as url should always work"),
priority: $crate::storage::video_database::Priority::from($record.priority),
watch_progress: std::time::Duration::from_secs(
u64::try_from($record.watch_progress).expect("The record is positive i64"),
),
}
};
}
/// Returns the videos that are in the `allowed_states`.
///
/// # Panics
/// Only, if assertions fail.
pub async fn videos(app: &App, allowed_states: &[VideoStatusMarker]) -> Result<Vec<Video>> {
fn test(all_states: &[VideoStatusMarker], check: VideoStatusMarker) -> Option<i64> {
if all_states.contains(&check) {
trace!("State '{check:?}' marked as active");
Some(check.as_db_integer())
} else {
trace!("State '{check:?}' marked as inactive");
None
}
}
fn states_to_string(allowed_states: &[VideoStatusMarker]) -> String {
let mut states = allowed_states
.iter()
.fold(String::from("&["), |mut acc, state| {
acc.push_str(state.as_str());
acc.push_str(", ");
acc
});
states = states.trim().to_owned();
states = states.trim_end_matches(',').to_owned();
states.push(']');
states
}
debug!(
"Fetching videos in the states: '{}'",
states_to_string(allowed_states)
);
let active_pick: Option<i64> = test(allowed_states, VideoStatusMarker::Pick);
let active_watch: Option<i64> = test(allowed_states, VideoStatusMarker::Watch);
let active_cached: Option<i64> = test(allowed_states, VideoStatusMarker::Cached);
let active_watched: Option<i64> = test(allowed_states, VideoStatusMarker::Watched);
let active_drop: Option<i64> = test(allowed_states, VideoStatusMarker::Drop);
let active_dropped: Option<i64> = test(allowed_states, VideoStatusMarker::Dropped);
let videos = query!(
r"
SELECT *
FROM videos
WHERE status IN (?,?,?,?,?,?)
ORDER BY priority DESC, publish_date DESC;
",
active_pick,
active_watch,
active_cached,
active_watched,
active_drop,
active_dropped,
)
.fetch_all(&app.database)
.await
.with_context(|| {
format!(
"Failed to query videos with states: '{}'",
states_to_string(allowed_states)
)
})?;
let real_videos: Vec<Video> = videos
.iter()
.map(|base| -> Video {
video_from_record! {base}
})
.collect();
Ok(real_videos)
}
pub fn video_info_json(video: &Video) -> Result<Option<InfoJson>> {
if let VideoStatus::Cached { mut cache_path, .. } = video.status.clone() {
if !cache_path.set_extension("info.json") {
bail!(
"Failed to change path extension to 'info.json': {}",
cache_path.display()
);
}
let info_json_string = File::open(cache_path)?;
let info_json: InfoJson = serde_json::from_reader(&info_json_string)?;
Ok(Some(info_json))
} else {
Ok(None)
}
}
pub async fn video_by_hash(app: &App, hash: &ExtractorHash) -> Result<Video> {
let ehash = hash.hash().to_string();
let raw_video = query!(
"
SELECT * FROM videos WHERE extractor_hash = ?;
",
ehash
)
.fetch_one(&app.database)
.await?;
Ok(video_from_record! {raw_video})
}
pub async fn get_all_hashes(app: &App) -> Result<Vec<Hash>> {
let hashes_hex = query!(
r#"
SELECT extractor_hash
FROM videos;
"#
)
.fetch_all(&app.database)
.await?;
Ok(hashes_hex
.iter()
.map(|hash| {
Hash::from_hex(&hash.extractor_hash).unreachable(
"These values started as blake3 hashes, they should stay blake3 hashes",
)
})
.collect())
}
pub async fn get_video_hashes(app: &App, subs: &Subscription) -> Result<Vec<Hash>> {
let hashes_hex = query!(
r#"
SELECT extractor_hash
FROM videos
WHERE parent_subscription_name = ?;
"#,
subs.name
)
.fetch_all(&app.database)
.await?;
Ok(hashes_hex
.iter()
.map(|hash| {
Hash::from_hex(&hash.extractor_hash).unreachable(
"These values started as blake3 hashes, they should stay blake3 hashes",
)
})
.collect())
}
pub async fn get_video_yt_dlp_opts(app: &App, hash: &ExtractorHash) -> Result<YtDlpOptions> {
let ehash = hash.hash().to_string();
let yt_dlp_options = query!(
r#"
SELECT subtitle_langs
FROM video_options
WHERE extractor_hash = ?;
"#,
ehash
)
.fetch_one(&app.database)
.await
.with_context(|| {
format!("Failed to fetch the `yt_dlp_video_opts` for video with hash: '{hash}'",)
})?;
Ok(YtDlpOptions {
subtitle_langs: yt_dlp_options.subtitle_langs,
})
}
pub async fn video_mpv_opts(app: &App, hash: &ExtractorHash) -> Result<MpvOptions> {
let ehash = hash.hash().to_string();
let mpv_options = query!(
r#"
SELECT playback_speed
FROM video_options
WHERE extractor_hash = ?;
"#,
ehash
)
.fetch_one(&app.database)
.await
.with_context(|| {
format!("Failed to fetch the `mpv_video_opts` for video with hash: '{hash}'")
})?;
Ok(MpvOptions {
playback_speed: mpv_options.playback_speed,
})
}
pub async fn get_video_opts(app: &App, hash: &ExtractorHash) -> Result<VideoOptions> {
let ehash = hash.hash().to_string();
let opts = query!(
r#"
SELECT playback_speed, subtitle_langs
FROM video_options
WHERE extractor_hash = ?;
"#,
ehash
)
.fetch_one(&app.database)
.await
.with_context(|| format!("Failed to fetch the `video_opts` for video with hash: '{hash}'"))?;
let mpv = MpvOptions {
playback_speed: opts.playback_speed,
};
let yt_dlp = YtDlpOptions {
subtitle_langs: opts.subtitle_langs,
};
Ok(VideoOptions { yt_dlp, mpv })
}
|