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
|
// yt - A fully featured command line YouTube client
//
// 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>.
use std::{
io::{Write, stderr},
sync::atomic::AtomicUsize,
};
use anyhow::{Context, Result};
use blake3::Hash;
use futures::{StreamExt, future::join_all, stream};
use log::{Level, debug, error, log_enabled};
use serde_json::json;
use tokio_util::task::LocalPoolHandle;
use yt_dlp::{InfoJson, YoutubeDLOptions, json_cast, json_get, process_ie_result};
use crate::{
ansi_escape_codes::{clear_whole_line, move_to_col},
app::App,
storage::subscriptions::Subscription,
};
use super::process_subscription;
pub(super) struct Updater {
max_backlog: usize,
hashes: Vec<Hash>,
pool: LocalPoolHandle,
}
static REACHED_NUMBER: AtomicUsize = const { AtomicUsize::new(1) };
impl Updater {
pub(super) fn new(max_backlog: usize, hashes: Vec<Hash>) -> Self {
// TODO(@bpeetz): The number should not be hardcoded. <2025-06-14>
let pool = LocalPoolHandle::new(16);
Self {
max_backlog,
hashes,
pool,
}
}
pub(super) async fn update(self, app: &App, subscriptions: Vec<Subscription>) -> Result<()> {
let total_number = subscriptions.len();
let mut stream = stream::iter(subscriptions)
.map(|sub| self.get_new_entries(sub, total_number))
.buffer_unordered(16 * 4);
while let Some(output) = stream.next().await {
let mut entries = output?;
if let Some(next) = entries.next() {
let (sub, entry) = next;
process_subscription(app, sub, entry).await?;
join_all(entries.map(|(sub, entry)| process_subscription(app, sub, entry)))
.await
.into_iter()
.collect::<Result<(), _>>()?;
}
}
Ok(())
}
async fn get_new_entries(
&self,
sub: Subscription,
total_number: usize,
) -> Result<impl Iterator<Item = (Subscription, InfoJson)>> {
let max_backlog = self.max_backlog;
let hashes = self.hashes.clone();
let yt_dlp = YoutubeDLOptions::new()
.set("playliststart", 1)
.set("playlistend", max_backlog)
.set("noplaylist", false)
.set(
"extractor_args",
json! {{"youtubetab": {"approximate_date": [""]}}},
)
// TODO: This also removes unlisted and other stuff. Find a good way to remove the
// members-only videos from the feed. <2025-04-17>
.set("match-filter", "availability=public")
.build()?;
self.pool
.spawn_pinned(move || {
async move {
if !log_enabled!(Level::Debug) {
clear_whole_line();
move_to_col(1);
eprint!(
"({}/{total_number}) Checking playlist {}...",
REACHED_NUMBER.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
sub.name
);
move_to_col(1);
stderr().flush()?;
}
let info = yt_dlp
.extract_info(&sub.url, false, false)
.with_context(|| format!("Failed to get playlist '{}'.", sub.name))?;
let empty = vec![];
let entries = info
.get("entries")
.map_or(&empty, |val| json_cast!(val, as_array));
let valid_entries: Vec<(Subscription, InfoJson)> = entries
.iter()
.take(max_backlog)
.filter_map(|entry| -> Option<(Subscription, InfoJson)> {
let id = json_get!(entry, "id", as_str);
let extractor_hash = blake3::hash(id.as_bytes());
if hashes.contains(&extractor_hash) {
debug!(
"Skipping entry, as it is already present: '{extractor_hash}'",
);
None
} else {
Some((sub.clone(), json_cast!(entry, as_object).to_owned()))
}
})
.collect();
Ok(valid_entries
.into_iter()
.map(|(sub, entry)| {
let inner_yt_dlp = YoutubeDLOptions::new()
.set("noplaylist", true)
.build()
.expect("Worked before, should work now");
match inner_yt_dlp.process_ie_result(entry, false) {
Ok(output) => Ok((sub, output)),
Err(err) => Err(err),
}
})
// Don't fail the whole update, if one of the entries fails to fetch.
.filter_map(|base| match base {
Ok(ok) => Some(ok),
Err(err) => {
let process_ie_result::Error::Python(err) = &err;
if err.contains(
"Join this channel to get access to members-only content ",
) {
// Hide this error
} else {
// Show the error, but don't fail.
let error = err
.strip_prefix("DownloadError: \u{1b}[0;31mERROR:\u{1b}[0m ")
.unwrap_or(err);
error!("{error}");
}
None
}
}))
}
})
.await?
}
}
|