aboutsummaryrefslogtreecommitdiffstats
path: root/crates/yt_dlp/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/yt_dlp/src')
-rw-r--r--crates/yt_dlp/src/post_processors/dearrow.rs120
1 files changed, 82 insertions, 38 deletions
diff --git a/crates/yt_dlp/src/post_processors/dearrow.rs b/crates/yt_dlp/src/post_processors/dearrow.rs
index ff4cdfa..94a13db 100644
--- a/crates/yt_dlp/src/post_processors/dearrow.rs
+++ b/crates/yt_dlp/src/post_processors/dearrow.rs
@@ -8,6 +8,9 @@
// 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::{
@@ -16,6 +19,7 @@ use pyo3::{
wrap_pyfunction,
};
use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
use crate::{
pydict_cast, pydict_get,
@@ -63,13 +67,16 @@ inst = DeArrow()
/// # 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: DeArrowApi = {
+ let mut output: HashMap<String, DeArrowApi> = {
loop {
let output_bytes = {
let mut dst = Vec::new();
@@ -77,8 +84,12 @@ pub fn unwrapped_process(info: Bound<'_, PyDict>) -> Result<Bound<'_, PyDict>, E
let mut easy = Easy::new();
easy.url(
format!(
- "https://sponsor.ajay.app/api/branding?videoID={}",
- pydict_get!(info, "id", String)
+ "https://sponsor.ajay.app/api/branding/{}",
+ HexDisplay(&Sha256::digest(pydict_get!(info, "id", String)))
+ .to_string()
+ .chars()
+ .take(4)
+ .collect::<String>()
)
.as_str(),
)?;
@@ -96,51 +107,76 @@ pub fn unwrapped_process(info: Bound<'_, PyDict>) -> Result<Bound<'_, PyDict>, E
match serde_json::from_slice(&output_bytes) {
Ok(ok) => break ok,
- Err(err) => {
+ Err(_) => {
if retry_num > 0 {
trace!(
"DeArrow: Api access failed, trying again ({retry_num} retries left)"
);
retry_num -= 1;
} else {
- let err: serde_json::Error = err;
- return Err(err.into());
+ // 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 });
}
}
}
}
};
- // We pop the titles, so we need this vector reversed.
- output.titles.reverse();
+ 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;
- };
+ 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;
- }
+ 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())?;
+ update_title(&info, &title.value)
+ .wrap_exc(info.py(), "updating title in dearrow pp")?;
- break true;
- };
+ 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())?;
+ 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)
}
@@ -152,11 +188,19 @@ pub enum Error {
#[error("Failed to access the DeArrow api: {0}")]
Get(#[from] curl::Error),
- #[error("Failed to deserialize a api json return object: {0}")]
- Deserialize(#[from] serde_json::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"))?);
@@ -186,7 +230,7 @@ fn update_title(info: &Bound<'_, PyDict>, new_title: &str) -> PyResult<()> {
Ok(())
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, Deserialize, Debug)]
/// See: <https://wiki.sponsor.ajay.app/w/API_Docs/DeArrow>
struct DeArrowApi {
titles: Vec<Title>,
@@ -202,14 +246,14 @@ struct DeArrowApi {
casual_votes: Vec<CasualVote>,
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, Deserialize, Debug)]
struct CasualVote {
id: String,
count: u32,
- title: String,
+ title: Option<String>,
}
-#[derive(Serialize, Deserialize, Clone)]
+#[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.
@@ -218,7 +262,7 @@ struct Title {
value: String,
original: bool,
- votes: u64,
+ votes: i64,
locked: bool,
#[serde(alias = "UUID")]
@@ -229,13 +273,13 @@ struct Title {
user_id: Option<String>,
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, Deserialize, Debug)]
struct Thumbnail {
// null if original is true
timestamp: Option<f64>,
original: bool,
- votes: u64,
+ votes: i64,
locked: bool,
#[serde(alias = "UUID")]