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
|
// 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::collections::HashMap;
use base16ct::HexDisplay;
use curl::easy::Easy;
use log::{info, trace, warn};
use pyo3::{
Bound, PyAny, PyErr, PyResult, Python, exceptions, intern, pyfunction,
types::{PyAnyMethods, PyDict, PyModule},
wrap_pyfunction,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::{
pydict_cast, pydict_get,
python_error::{IntoPythonError, PythonError},
};
/// # Errors
/// - If the underlying function returns an error.
/// - If python operations fail.
pub fn process(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
#[pyfunction]
fn actual_processor(info_json: Bound<'_, PyDict>) -> PyResult<Bound<'_, PyDict>> {
let output = match unwrapped_process(info_json) {
Ok(ok) => ok,
Err(err) => {
return Err(PyErr::new::<exceptions::PyRuntimeError, _>(err.to_string()));
}
};
Ok(output)
}
let module = PyModule::new(py, "rust_post_processors")?;
let scope = PyDict::new(py);
scope.set_item(
intern!(py, "actual_processor"),
wrap_pyfunction!(actual_processor, module)?,
)?;
py.run(
c"
import yt_dlp
class DeArrow(yt_dlp.postprocessor.PostProcessor):
def run(self, info):
info = actual_processor(info)
return [], info
inst = DeArrow()
",
Some(&scope),
None,
)?;
Ok(scope.get_item(intern!(py, "inst"))?.cast_into()?)
}
/// # Errors
/// If the API access fails.
///
/// # Panics
/// If the API functions failed.
pub fn unwrapped_process(info: Bound<'_, PyDict>) -> Result<Bound<'_, PyDict>, Error> {
if pydict_get!(info, "extractor_key", String).as_str() != "Youtube" {
return Ok(info);
}
let mut retry_num = 3;
let mut output: HashMap<String, DeArrowApi> = {
loop {
let output_bytes = {
let mut dst = Vec::new();
let mut easy = Easy::new();
easy.url(
format!(
"https://sponsor.ajay.app/api/branding/{}",
HexDisplay(&Sha256::digest(pydict_get!(info, "id", String)))
.to_string()
.chars()
.take(4)
.collect::<String>()
)
.as_str(),
)?;
let mut transfer = easy.transfer();
transfer.write_function(|data| {
dst.extend_from_slice(data);
Ok(data.len())
})?;
transfer.perform()?;
drop(transfer);
dst
};
match serde_json::from_slice(&output_bytes) {
Ok(ok) => break ok,
Err(_) => {
if retry_num > 0 {
trace!(
"DeArrow: Api access failed, trying again ({retry_num} retries left)"
);
retry_num -= 1;
} else {
// Try to get a better error message, by re-parsing with some formatting
// applied.
let json = String::from_utf8_lossy(&output_bytes).to_string();
let json = match serde_json::from_str::<serde_json::Value>(&json) {
Ok(ok) => {
serde_json::to_string_pretty(&ok).expect("should be formattable")
}
Err(_) => json
.replace(',', ",\n ")
.replace('{', "{\n ")
.replace('}', "\n}")
.replace('[', "[\n ")
.replace(']', "\n]"),
};
let err: serde_json::Error =
serde_json::from_str::<HashMap<String, DeArrowApi>>(&json)
.expect_err("It failed before");
return Err(Error::Deserialize { json, err });
}
}
}
}
};
if let Some(mut output) = output.remove(&pydict_get!(info, "id", String)) {
// We pop the titles, so we need this vector reversed.
output.titles.reverse();
let title_len = output.titles.len();
let mut iterator = output.titles.clone();
let selected = loop {
let Some(title) = iterator.pop() else {
break false;
};
if (title.locked || title.votes < 1) && title_len > 1 {
info!(
"DeArrow: Skipping title {:#?}, as it is not good enough",
title.value
);
// Skip titles that are not “good” enough.
continue;
}
update_title(&info, &title.value)
.wrap_exc(info.py(), "updating title in dearrow pp")?;
break true;
};
if !selected && title_len != 0 {
// No title was selected, even though we had some titles.
// Just pick the first one in this case.
update_title(&info, &output.titles[0].value)
.wrap_exc(info.py(), "updating title in dearrow pp")?;
}
}
// TODO(@bpeetz): We should try to remove CAPITAL stuff, if we don't get a title from dearrow. But we should still keep Capitalisation in tact. <2026-09-23>
Ok(info)
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Python(#[from] PythonError),
#[error("Failed to access the DeArrow api: {0}")]
Get(#[from] curl::Error),
#[error("Failed to deserialized a dearrow api json response: `{json}`, err: `{err}`")]
Deserialize {
json: String,
err: serde_json::Error,
},
}
fn update_title(info: &Bound<'_, PyDict>, new_title: &str) -> PyResult<()> {
// Replace the `>` char, which is used by DeArrow to mark words that should not be
// auto-formatted.
// We don't do auto-formatting, so we can just remove it.
let new_title = new_title.replace('>', "");
let py = info.py();
assert!(!info.contains(intern!(py, "original_title"))?);
if let Ok(old_title) = info.get_item(intern!(py, "title")) {
warn!(
"DeArrow: Updating title from {:#?} to {:#?}",
pydict_cast!(old_title, &str),
new_title
);
info.set_item(intern!(py, "original_title"), old_title)
.expect("We checked, it is a new key");
} else {
warn!("DeArrow: Setting title to {new_title:#?}");
}
let cleaned_title = {
// NOTE(@bpeetz): DeArrow uses `>` as a “Don't format the next word” mark.
// They should be removed, if one does not use a auto-formatter. <2025-06-16>
new_title.replace('>', "")
};
info.set_item(intern!(py, "title"), cleaned_title)
.expect("This should work?");
Ok(())
}
#[derive(Serialize, Deserialize, Debug)]
/// See: <https://wiki.sponsor.ajay.app/w/API_Docs/DeArrow>
struct DeArrowApi {
titles: Vec<Title>,
thumbnails: Vec<Thumbnail>,
#[serde(alias = "randomTime")]
random_time: Option<f64>,
#[serde(alias = "videoDuration")]
video_duration: Option<f64>,
#[serde(alias = "casualVotes")]
casual_votes: Vec<CasualVote>,
}
#[derive(Serialize, Deserialize, Debug)]
struct CasualVote {
id: String,
count: u32,
title: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Title {
/// Note: Titles will sometimes contain > before a word.
/// This tells the auto-formatter to not format a word.
/// If you have no auto-formatter, you can ignore this and replace it with an empty string
#[serde(alias = "title")]
value: String,
original: bool,
votes: i64,
locked: bool,
#[serde(alias = "UUID")]
uuid: String,
/// only present if requested
#[serde(alias = "userID")]
user_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Thumbnail {
// null if original is true
timestamp: Option<f64>,
original: bool,
votes: i64,
locked: bool,
#[serde(alias = "UUID")]
uuid: String,
/// only present if requested
#[serde(alias = "userID")]
user_id: Option<String>,
}
|