Spaces:
Build error
Build error
Download src/video_discovery/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 56.6 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/video_discovery/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/video_discovery/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/video_discovery/mod.rs
56.6 kB
#![allow(dead_code)]
//! Video discovery module for IntentForge v2
//!
//! Provides multi-source video discovery from:
//! - Piped API (YouTube frontend)
//! - Invidious API (YouTube fallback)
//! - Internet Archive (public domain)
//! - Vimeo (professional content)
//! - Dailymotion
//! - yt-dlp (CLI-based batch crawling)
//!
//! Includes intent-first scoring for videos.
mod scoring;
use anyhow::{Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::future::join_all;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{Duration, Instant};
use crate::trending::FeedItem;
use scoring::VideoIntentScorer;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoDocument {
pub id: String,
pub title: String,
pub description: Option<String>,
pub thumbnail: String,
pub url: String,
pub source: String,
pub duration_secs: Option<u32>,
pub uploader: Option<String>,
pub view_count: Option<u64>,
pub published_at: Option<DateTime<Utc>>,
pub category: String,
pub priority: i32,
/// Intent-first scoring
pub intent_score: f32,
pub relevance_score: f32,
pub commercial_score: f32,
pub spam_score: f32,
pub intent_category: String,
pub quality_gate: bool,
}
impl VideoDocument {
/// Create a new VideoDocument with default intent scores
/// Scores will be computed later by VideoIntentScorer
#[allow(clippy::too_many_arguments)]
fn new(
id: String,
title: String,
description: Option<String>,
thumbnail: String,
url: String,
source: String,
duration_secs: Option<u32>,
uploader: Option<String>,
view_count: Option<u64>,
published_at: Option<DateTime<Utc>>,
category: String,
priority: i32,
) -> Self {
Self {
id,
title,
description,
thumbnail,
url,
source,
duration_secs,
uploader,
view_count,
published_at,
category,
priority,
intent_score: 0.5,
relevance_score: 0.5,
commercial_score: 0.5,
spam_score: 0.5,
intent_category: "Unknown".to_string(),
quality_gate: true,
}
}
}
impl From<VideoDocument> for FeedItem {
fn from(doc: VideoDocument) -> Self {
FeedItem {
id: doc.id,
title: doc.title,
link: doc.url,
description: doc.description,
published_at: doc.published_at,
source: doc.source,
category: doc.category,
priority: doc.priority as u32,
}
}
}
#[async_trait]
pub trait VideoSource: Send + Sync {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>>;
async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>>;
fn source_name(&self) -> &str;
}
pub struct VideoDiscoveryService {
client: reqwest::Client,
sources: HashMap<String, Arc<dyn VideoSource>>,
cache: Arc<Mutex<VideoCache>>,
config: VideoDiscoveryConfig,
}
#[derive(Debug, Clone)]
pub struct VideoDiscoveryConfig {
pub ytdlp_path: String,
pub ytdlp_update_interval_hours: u64,
pub piped_instances: Vec<String>,
pub invidious_instances: Vec<String>,
pub youtube_api_key: String,
pub rapidapi_key: String,
pub enabled_sources: Vec<String>,
pub search_limit: usize,
pub cache_ttl_secs: u64,
}
impl VideoDiscoveryConfig {
pub fn from_app_config(config: &crate::config::VideoDiscoveryConfig) -> Self {
// Prefer environment variable if set, fallback to config file
let api_key = std::env::var("YOUTUBE_API_KEY")
.ok()
.or_else(|| config.youtube_api_key.clone())
.unwrap_or_default();
let rapid_key = std::env::var("RAPIDAPI_KEY")
.ok()
.or_else(|| config.rapidapi_key.clone())
.unwrap_or_default();
Self {
ytdlp_path: config.ytdlp_path.clone(),
ytdlp_update_interval_hours: config.ytdlp_update_interval_hours,
piped_instances: config.piped_instances.clone(),
invidious_instances: config.invidious_instances.clone(),
youtube_api_key: api_key,
rapidapi_key: rapid_key,
enabled_sources: config.enabled_sources.clone(),
search_limit: config.search_limit,
cache_ttl_secs: config.cache_ttl_secs,
}
}
}
#[derive(Debug)]
struct Entry {
documents: Vec<VideoDocument>,
expires: Instant,
}
#[derive(Debug, Default)]
struct VideoCache {
entries: HashMap<String, Entry>,
}
impl VideoDiscoveryService {
pub fn new(client: reqwest::Client, config: VideoDiscoveryConfig) -> Self {
let mut sources: HashMap<String, Arc<dyn VideoSource>> = HashMap::new();
// YouTube Unified - primary source (uses local youtube-unified service)
let youtube_unified = Arc::new(YouTubeUnifiedClient::new(
client.clone(),
"http://youtube-unified:8085".to_string(),
));
sources.insert("youtube_unified".to_string(), youtube_unified);
// Fallback: Direct YouTube API (requires API key)
let youtube = Arc::new(YouTubeClient::new(
client.clone(),
config.youtube_api_key.clone(),
));
sources.insert("youtube".to_string(), youtube);
// Fallback: RapidAPI YouTube (requires RapidAPI key)
let rapid_youtube = Arc::new(RapidYouTubeClient::new(
client.clone(),
config.rapidapi_key.clone(),
));
sources.insert("rapid_youtube".to_string(), rapid_youtube);
// Piped (privacy-friendly YouTube frontend)
let piped = Arc::new(PipedClient::new(
client.clone(),
config.piped_instances.clone(),
));
sources.insert("piped".to_string(), piped);
// Invidious (another privacy-friendly frontend)
let invidious = Arc::new(InvidiousClient::new(
client.clone(),
config.invidious_instances.clone(),
));
sources.insert("invidious".to_string(), invidious);
// Internet Archive (public domain videos)
let archive = Arc::new(InternetArchiveClient::new(client.clone()));
sources.insert("archive_org".to_string(), archive);
// Dailymotion
let dailymotion = Arc::new(DailymotionClient::new(client.clone()));
sources.insert("dailymotion".to_string(), dailymotion);
// Odysee (LBRY-based)
let odysee = Arc::new(OdyseeClient::new(client.clone()));
sources.insert("odysee".to_string(), odysee);
// Vimeo (professional content)
let vimeo = Arc::new(VimeoClient::new(client.clone()));
sources.insert("vimeo".to_string(), vimeo);
Self {
client,
sources,
cache: Arc::new(Mutex::new(VideoCache::default())),
config,
}
}
pub async fn search(&self, query: &str) -> Result<Vec<VideoDocument>> {
let cache_key = format!("search:{}", query);
if let Some(cached) = self.get_cached(&cache_key).await {
return Ok(cached);
}
// Create intent scorer for this query
let scorer = VideoIntentScorer::new(query);
let mut search_tasks = Vec::new();
for (name, source) in &self.sources {
if !self.config.enabled_sources.contains(name) {
continue;
}
// Skip yt-dlp for real-time search
if name == "yt-dlp" {
continue;
}
let source = source.clone();
let query = query.to_string();
let limit = self.config.search_limit;
let name = name.clone();
search_tasks.push(tokio::spawn(async move {
// OPTIMIZED: Reduced timeouts for faster video search
// YouTube Unified: 2s (was 12s) - Mobile API + Piped should be fast
// Other sources: 1s (was 5s) - Fail fast, don't wait for slow sources
let timeout_duration = if name == "youtube_unified" {
Duration::from_secs(5)
} else {
Duration::from_secs(2)
};
match tokio::time::timeout(timeout_duration, source.search(&query, limit)).await {
Ok(Ok(items)) => {
tracing::info!(
"Source '{}' returned {} videos in <{}s",
name,
items.len(),
timeout_duration.as_secs()
);
items
}
Ok(Err(e)) => {
tracing::warn!("Source '{}' failed: {}", name, e);
vec![]
}
Err(_) => {
tracing::warn!(
"Source '{}' timed out after {}s",
name,
timeout_duration.as_secs()
);
vec![]
}
}
}));
}
let mut results = Vec::new();
let task_results = join_all(search_tasks).await;
for mut items in task_results.into_iter().flatten() {
// Apply intent-first scoring to each video
for item in &mut items {
let scores = scorer.score(
&item.title,
item.description.as_deref(),
item.uploader.as_deref(),
item.duration_secs,
item.view_count,
);
item.intent_score = scores.intent_score;
item.relevance_score = scores.relevance_score;
item.commercial_score = scores.commercial_score;
item.spam_score = scores.spam_score;
item.intent_category = format!("{:?}", scores.intent_category);
item.quality_gate = scores.quality_gate;
}
results.extend(items);
}
// Sort by intent score (highest first), then relevance
results.sort_by(|a, b| {
b.intent_score
.partial_cmp(&a.intent_score)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| {
b.relevance_score
.partial_cmp(&a.relevance_score)
.unwrap_or(std::cmp::Ordering::Equal)
})
});
// Filter out videos that don't pass quality gate (unless we have too few results)
if results.len() > 5 {
results.retain(|v| v.quality_gate || v.intent_score > 0.7);
}
if results.len() > self.config.search_limit {
results.truncate(self.config.search_limit);
}
self.set_cached(cache_key, results.clone()).await;
Ok(results)
}
pub async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>> {
let cache_key = format!("trending:{:?}", region);
if let Some(cached) = self.get_cached(&cache_key).await {
return Ok(cached);
}
let mut results = Vec::new();
for (name, source) in &self.sources {
if !self.config.enabled_sources.contains(name) {
continue;
}
match source.trending(region).await {
Ok(items) => {
tracing::debug!("{} trending returned {} videos", name, items.len());
results.extend(items);
}
Err(e) => tracing::warn!("{} trending failed: {}", name, e),
}
}
self.set_cached(cache_key, results.clone()).await;
Ok(results)
}
pub async fn get_sources(&self) -> Vec<String> {
self.sources.keys().cloned().collect()
}
async fn get_cached(&self, key: &str) -> Option<Vec<VideoDocument>> {
let cache = self.cache.lock().await;
cache.entries.get(key).and_then(|entry| {
if entry.expires > Instant::now() {
Some(entry.documents.clone())
} else {
None
}
})
}
async fn set_cached(&self, key: String, documents: Vec<VideoDocument>) {
let mut cache = self.cache.lock().await;
cache.entries.insert(
key,
Entry {
documents,
expires: Instant::now() + Duration::from_secs(self.config.cache_ttl_secs),
},
);
}
}
pub struct RapidYouTubeClient {
client: reqwest::Client,
api_key: String,
}
#[derive(Debug, Deserialize)]
struct RapidYouTubeResult {
#[serde(default)]
results: Vec<RapidYouTubeVideo>,
}
#[derive(Debug, Deserialize)]
struct RapidYouTubeVideo {
#[serde(default)]
id: String,
#[serde(default)]
title: String,
#[serde(default)]
url: String,
#[serde(default)]
thumbnail: RapidYouTubeThumbnail,
#[serde(default)]
channel: RapidYouTubeChannel,
#[serde(rename = "duration_formatted", default)]
duration_formatted: Option<String>,
#[serde(default)]
views: Option<u64>,
#[serde(rename = "uploadedAt", default)]
uploaded_at: Option<String>,
}
#[derive(Debug, Deserialize, Default)]
struct RapidYouTubeThumbnail {
#[serde(default)]
url: String,
}
#[derive(Debug, Deserialize, Default)]
struct RapidYouTubeChannel {
#[serde(default)]
name: String,
}
#[async_trait]
impl VideoSource for RapidYouTubeClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
if self.api_key.is_empty() {
tracing::warn!("RapidAPI key is empty, skipping search");
return Ok(vec![]);
}
if self.api_key == "SET_VIA_ENV" {
tracing::error!(
"RapidAPI key is still 'SET_VIA_ENV'! Environment variable override failed."
);
return Ok(vec![]);
}
let key_len = self.api_key.len();
let key_prefix = if key_len >= 5 {
&self.api_key[0..5]
} else {
"..."
};
tracing::info!(
"RapidYouTube search starting for: {} (key: {}..., len: {})",
query,
key_prefix,
key_len
);
let url = "https://simple-youtube-search.p.rapidapi.com/search";
let response = self
.client
.get(url)
.header("x-rapidapi-key", &self.api_key)
.header("x-rapidapi-host", "simple-youtube-search.p.rapidapi.com")
.query(&[("query", query), ("type", "video"), ("safesearch", "false")])
.send()
.await
.with_context(|| format!("RapidYouTube search failed: {}", query))?;
if !response.status().is_success() {
tracing::warn!("RapidYouTube API returned error: {}", response.status());
return Ok(vec![]);
}
let result: RapidYouTubeResult = response
.json()
.await
.with_context(|| "Failed to parse RapidYouTube response")?;
Ok(result
.results
.into_iter()
.take(limit)
.map(|v| {
let mut doc = VideoDocument::new(
format!("rapid-yt-{}", v.id),
v.title,
None,
v.thumbnail.url,
v.url,
"YouTube (Fallback)".to_string(),
None,
Some(v.channel.name),
v.views,
None,
"video".to_string(),
9,
);
// This source doesn't provide descriptions, mark as lower quality
doc.quality_gate = false;
doc
})
.collect())
}
async fn trending(&self, _region: Option<&str>) -> Result<Vec<VideoDocument>> {
self.search("trending", 25).await
}
fn source_name(&self) -> &str {
"rapid_youtube"
}
}
impl RapidYouTubeClient {
pub fn new(client: reqwest::Client, api_key: String) -> Self {
Self { client, api_key }
}
}
pub struct YouTubeClient {
client: reqwest::Client,
api_key: String,
}
#[derive(Debug, Deserialize)]
struct YouTubeSearchResponse {
items: Vec<YouTubeItem>,
}
#[derive(Debug, Deserialize)]
struct YouTubeItem {
id: YouTubeId,
snippet: YouTubeSnippet,
}
#[derive(Debug, Deserialize)]
struct YouTubeId {
#[serde(rename = "videoId")]
video_id: Option<String>,
}
#[derive(Debug, Deserialize)]
struct YouTubeSnippet {
title: String,
description: String,
thumbnails: YouTubeThumbnails,
#[serde(rename = "channelTitle")]
channel_title: String,
#[serde(rename = "publishedAt")]
published_at: String,
}
#[derive(Debug, Deserialize)]
struct YouTubeThumbnails {
medium: Option<YouTubeThumbnail>,
default: Option<YouTubeThumbnail>,
}
#[derive(Debug, Deserialize)]
struct YouTubeThumbnail {
url: String,
}
#[async_trait]
impl VideoSource for YouTubeClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
if self.api_key.is_empty() {
tracing::warn!("YouTube API key is empty, skipping search");
return Ok(vec![]);
}
if self.api_key == "SET_VIA_ENV" {
tracing::error!(
"YouTube API key is still 'SET_VIA_ENV'! Environment variable override failed."
);
return Ok(vec![]);
}
let key_len = self.api_key.len();
let key_prefix = if key_len >= 5 {
&self.api_key[0..5]
} else {
"..."
};
tracing::info!(
"YouTube API search starting for: {} (key: {}..., len: {})",
query,
key_prefix,
key_len
);
let url = format!(
"https://www.googleapis.com/youtube/v3/search?part=snippet&q={}&type=video&maxResults={}&key={}",
urlencoding::encode(query),
limit,
self.api_key
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("YouTube API search failed: {}", query))?;
if !response.status().is_success() {
let err_text = response.text().await.unwrap_or_default();
tracing::warn!("YouTube API returned error: {}", err_text);
return Err(anyhow::anyhow!("YouTube API error"));
}
let data: YouTubeSearchResponse = response
.json()
.await
.with_context(|| "Failed to parse YouTube API response")?;
tracing::info!("YouTube API returned {} results", data.items.len());
Ok(data
.items
.into_iter()
.filter_map(|item| {
let video_id = item.id.video_id?;
let published_at = DateTime::parse_from_rfc3339(&item.snippet.published_at)
.map(|dt| dt.with_timezone(&Utc))
.ok();
let thumbnail = item
.snippet
.thumbnails
.medium
.as_ref()
.or(item.snippet.thumbnails.default.as_ref())
.map(|t| t.url.clone())
.unwrap_or_default();
Some(VideoDocument::new(
format!("youtube-{}", video_id),
item.snippet.title,
Some(item.snippet.description),
thumbnail,
format!("https://www.youtube.com/watch?v={}", video_id),
"YouTube".to_string(),
None,
Some(item.snippet.channel_title),
None,
published_at,
"video".to_string(),
10,
))
})
.collect())
}
async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>> {
let region_code = region.unwrap_or("US");
let url = format!(
"https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular®ionCode={}&maxResults=25&key={}",
region_code,
self.api_key
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "YouTube trending API failed")?;
let data: YouTubeSearchResponse = response
.json()
.await
.with_context(|| "Failed to parse YouTube trending response")?;
Ok(data
.items
.into_iter()
.filter_map(|item| {
// trending returns 'id' as a string, search returns 'id' as object
// handled by deserialize logic or filter_map if id structure differs
let video_id = item.id.video_id.unwrap_or_default(); // Fallback
if video_id.is_empty() {
return None;
}
let published_at = DateTime::parse_from_rfc3339(&item.snippet.published_at)
.map(|dt| dt.with_timezone(&Utc))
.ok();
Some(VideoDocument::new(
format!("youtube-{}", video_id),
item.snippet.title,
Some(item.snippet.description),
item.snippet
.thumbnails
.medium
.as_ref()
.map(|t| t.url.clone())
.unwrap_or_default(),
format!("https://www.youtube.com/watch?v={}", video_id),
"YouTube Trending".to_string(),
None,
Some(item.snippet.channel_title),
None,
published_at,
"video".to_string(),
10,
))
})
.collect())
}
fn source_name(&self) -> &str {
"youtube"
}
}
impl YouTubeClient {
pub fn new(client: reqwest::Client, api_key: String) -> Self {
Self { client, api_key }
}
}
pub struct PipedClient {
client: reqwest::Client,
instances: Vec<String>,
current: AtomicUsize,
}
#[derive(Debug, Deserialize)]
struct PipedSearchResponse {
#[serde(default)]
items: Vec<PipedVideo>,
}
#[derive(Debug, Deserialize)]
struct PipedVideo {
#[serde(rename = "videoId", default)]
video_id: String,
#[serde(default)]
title: String,
#[serde(default)]
description: Option<String>,
#[serde(rename = "thumbnailUrl", default)]
thumbnail_url: Option<String>,
#[serde(rename = "shortDescription", default)]
short_description: Option<String>,
#[serde(default)]
author: Option<String>,
#[serde(rename = "lengthSeconds", default)]
length_seconds: Option<u32>,
#[serde(rename = "viewCount", default)]
view_count: Option<u64>,
#[serde(default)]
published: Option<String>,
}
impl PipedClient {
pub fn new(client: reqwest::Client, instances: Vec<String>) -> Self {
Self {
client,
instances,
current: AtomicUsize::new(0),
}
}
fn current_url(&self) -> &str {
let idx = self.current.load(Ordering::Relaxed) % self.instances.len();
&self.instances[idx]
}
fn rotate(&self) {
self.current.fetch_add(1, Ordering::Relaxed);
}
async fn request(&self, path: &str) -> Result<reqwest::Response> {
let url = format!("{}{}", self.current_url(), path);
match self.client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => Ok(resp),
Ok(_) => {
self.rotate();
let url = format!("{}{}", self.current_url(), path);
self.client
.get(&url)
.send()
.await
.with_context(|| format!("All Piped instances failed for {}", path))
}
Err(e) => {
tracing::warn!("Piped {} failed: {}", self.current_url(), e);
self.rotate();
let url = format!("{}{}", self.current_url(), path);
self.client
.get(&url)
.send()
.await
.with_context(|| format!("All Piped instances failed for {}", path))
}
}
}
}
#[async_trait]
impl VideoSource for PipedClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let path = format!("/search?q={}&filter=all", urlencoding::encode(query));
let response = self.request(&path).await?;
let text = response
.text()
.await
.with_context(|| "Failed to get Piped search response text")?;
let data: PipedSearchResponse = match serde_json::from_str(&text) {
Ok(d) => d,
Err(e) => {
tracing::warn!(
"Failed to parse Piped response: {}. Body start: {}",
e,
&text[..200.min(text.len())]
);
return Err(anyhow::anyhow!("Failed to parse Piped response"));
}
};
Ok(data
.items
.into_iter()
.take(limit)
.map(|v| {
let published_at = v
.published
.and_then(|p| chrono::NaiveDate::parse_from_str(&p, "%Y-%m-%d").ok())
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
VideoDocument::new(
format!("piped-{}", v.video_id),
v.title,
v.description.or(v.short_description),
v.thumbnail_url.unwrap_or_default(),
format!("https://piped.video/watch?v={}", v.video_id),
"Piped".to_string(),
v.length_seconds,
v.author,
v.view_count,
published_at,
"video".to_string(),
8,
)
})
.collect())
}
async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>> {
let region_code = region.unwrap_or("US");
let path = format!("/trending?region={}", region_code);
let response = self.request(&path).await?;
let text = response
.text()
.await
.with_context(|| "Failed to get Piped trending response text")?;
let data: PipedSearchResponse = match serde_json::from_str(&text) {
Ok(d) => d,
Err(e) => {
tracing::warn!(
"Failed to parse Piped trending response: {}. Body start: {}",
e,
&text[..200.min(text.len())]
);
return Err(anyhow::anyhow!("Failed to parse Piped trending response"));
}
};
Ok(data
.items
.into_iter()
.take(25)
.map(|v| {
let published_at = v
.published
.and_then(|p| chrono::NaiveDate::parse_from_str(&p, "%Y-%m-%d").ok())
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
VideoDocument::new(
format!("piped-trending-{}", v.video_id),
v.title,
v.description.or(v.short_description),
v.thumbnail_url.unwrap_or_default(),
format!("https://piped.video/watch?v={}", v.video_id),
"Piped Trending".to_string(),
v.length_seconds,
v.author,
v.view_count,
published_at,
"video".to_string(),
9,
)
})
.collect())
}
fn source_name(&self) -> &str {
"piped"
}
}
pub struct InvidiousClient {
client: reqwest::Client,
instances: Vec<String>,
current: AtomicUsize,
}
#[derive(Debug, Deserialize)]
struct InvidiousVideo {
#[serde(rename = "videoId", default)]
video_id: String,
#[serde(default)]
title: String,
#[serde(default)]
description: Option<String>,
#[serde(default)]
published: Option<i64>,
#[serde(rename = "viewCount", default)]
view_count: Option<u64>,
#[serde(default)]
author: Option<String>,
#[serde(rename = "lengthSeconds", default)]
length_seconds: Option<u32>,
}
#[async_trait]
impl VideoSource for InvidiousClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let path = format!("/api/v1/search?q={}&type=video", urlencoding::encode(query));
let response = self.request(&path).await?;
let text = response
.text()
.await
.with_context(|| "Failed to get Invidious search response text")?;
let videos: Vec<InvidiousVideo> = match serde_json::from_str(&text) {
Ok(v) => v,
Err(e) => {
tracing::warn!(
"Failed to parse Invidious response: {}. Body start: {}",
e,
&text[..200.min(text.len())]
);
return Err(anyhow::anyhow!("Failed to parse Invidious response"));
}
};
Ok(videos
.into_iter()
.take(limit)
.map(|v| {
let published_at = v
.published
.and_then(|ts| DateTime::from_timestamp(ts, 0))
.map(|dt| dt.with_timezone(&Utc));
VideoDocument::new(
format!("invidious-{}", v.video_id),
v.title,
v.description,
format!("https://img.youtube.com/vi/{}/mqdefault.jpg", v.video_id),
format!("https://www.youtube.com/watch?v={}", v.video_id),
"Invidious".to_string(),
v.length_seconds,
v.author,
v.view_count,
published_at,
"video".to_string(),
7,
)
})
.collect())
}
async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>> {
let region_code = region.unwrap_or("US");
let path = format!("/api/v1/trending?type=default®ion={}", region_code);
let response = self.request(&path).await?;
let text = response
.text()
.await
.with_context(|| "Failed to get Invidious trending response text")?;
let videos: Vec<InvidiousVideo> = match serde_json::from_str(&text) {
Ok(v) => v,
Err(e) => {
tracing::warn!(
"Failed to parse Invidious trending response: {}. Body start: {}",
e,
&text[..200.min(text.len())]
);
return Err(anyhow::anyhow!(
"Failed to parse Invidious trending response"
));
}
};
Ok(videos
.into_iter()
.take(25)
.map(|v| {
let published_at = v
.published
.and_then(|ts| DateTime::from_timestamp(ts, 0))
.map(|dt| dt.with_timezone(&Utc));
VideoDocument::new(
format!("invidious-trending-{}", v.video_id),
v.title,
v.description,
format!("https://img.youtube.com/vi/{}/mqdefault.jpg", v.video_id),
format!("https://www.youtube.com/watch?v={}", v.video_id),
"Invidious Trending".to_string(),
v.length_seconds,
v.author,
v.view_count,
published_at,
"video".to_string(),
8,
)
})
.collect())
}
fn source_name(&self) -> &str {
"invidious"
}
}
impl InvidiousClient {
pub fn new(client: reqwest::Client, instances: Vec<String>) -> Self {
Self {
client,
instances,
current: AtomicUsize::new(0),
}
}
fn current_url(&self) -> &str {
let idx = self.current.load(Ordering::Relaxed) % self.instances.len();
&self.instances[idx]
}
fn rotate(&self) {
self.current.fetch_add(1, Ordering::Relaxed);
}
async fn request(&self, path: &str) -> Result<reqwest::Response> {
let url = format!("{}{}", self.current_url(), path);
match self.client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => Ok(resp),
_ => {
self.rotate();
let url = format!("{}{}", self.current_url(), path);
self.client
.get(&url)
.send()
.await
.with_context(|| format!("All Invidious instances failed for {}", path))
}
}
}
}
pub struct OdyseeClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct OdyseeResponse {
result: Option<OdyseeResult>,
}
#[derive(Debug, Deserialize)]
struct OdyseeResult {
items: Vec<OdyseeVideo>,
}
#[derive(Debug, Deserialize)]
struct OdyseeVideo {
name: String,
claim_id: String,
value: Option<OdyseeValue>,
meta: Option<OdyseeMeta>,
}
#[derive(Debug, Deserialize)]
struct OdyseeValue {
title: Option<String>,
description: Option<String>,
thumbnail: Option<OdyseeThumbnail>,
video: Option<OdyseeVideoInfo>,
}
#[derive(Debug, Deserialize)]
struct OdyseeThumbnail {
url: Option<String>,
}
#[derive(Debug, Deserialize)]
struct OdyseeVideoInfo {
duration: Option<u32>,
}
#[derive(Debug, Deserialize)]
struct OdyseeMeta {
creation_timestamp: Option<i64>,
}
#[async_trait]
impl VideoSource for OdyseeClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let payload = serde_json::json!({
"method": "claim_search",
"params": {
"text": query,
"stream_types": ["video"],
"page_size": limit,
"order_by": ["relevance"]
}
});
let response = self
.client
.post("https://api.na-backend.odysee.com/api/v1/proxy")
.json(&payload)
.send()
.await
.with_context(|| format!("Odysee search failed: {}", query))?;
let data: OdyseeResponse = response
.json()
.await
.with_context(|| "Failed to parse Odysee response")?;
let items = data.result.map(|r| r.items).unwrap_or_default();
Ok(items
.into_iter()
.map(|v| {
let val = v.value.as_ref();
let published_at = v
.meta
.as_ref()
.and_then(|m| m.creation_timestamp)
.and_then(|ts| DateTime::from_timestamp(ts, 0))
.map(|dt| dt.with_timezone(&Utc));
VideoDocument::new(
format!("odysee-{}", v.claim_id),
val.and_then(|val| val.title.clone()).unwrap_or(v.name),
val.and_then(|val| val.description.clone()),
val.and_then(|val| val.thumbnail.as_ref())
.and_then(|t| t.url.clone())
.unwrap_or_default(),
format!("https://odysee.com/$/discover?claim_id={}", v.claim_id),
"Odysee".to_string(),
val.and_then(|val| val.video.as_ref())
.and_then(|v| v.duration),
None,
None,
published_at,
"video".to_string(),
7,
)
})
.collect())
}
async fn trending(&self, _region: Option<&str>) -> Result<Vec<VideoDocument>> {
self.search("trending", 25).await
}
fn source_name(&self) -> &str {
"odysee"
}
}
impl OdyseeClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
}
pub struct InternetArchiveClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct ArchiveSearchResponse {
response: ArchiveResponse,
}
#[derive(Debug, Deserialize)]
struct ArchiveResponse {
docs: Vec<ArchiveDoc>,
}
#[derive(Debug, Deserialize)]
struct ArchiveDoc {
identifier: String,
title: Option<String>,
creator: Option<String>,
#[serde(rename = "downloads")]
download_count: Option<u64>,
#[serde(rename = "date")]
pub_date: Option<String>,
}
#[async_trait]
impl VideoSource for InternetArchiveClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let url = format!(
"https://archive.org/advancedsearch.php?q=title:({})mediatype:movies&fl[]=identifier,title,creator,downloads,date&output=json&rows={}",
urlencoding::encode(query),
limit
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Archive.org search failed: {}", query))?;
let data: ArchiveSearchResponse = response
.json()
.await
.with_context(|| "Failed to parse Archive.org response")?;
Ok(data
.response
.docs
.into_iter()
.map(|doc| {
let published_at = doc
.pub_date
.and_then(|d| chrono::NaiveDate::parse_from_str(&d, "%Y-%m-%d").ok())
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
VideoDocument::new(
format!("archive-{}", doc.identifier),
doc.title.unwrap_or_default(),
doc.creator.as_ref().map(|c| format!("By {}", c)),
format!("https://archive.org/services/img/{}", doc.identifier),
format!("https://archive.org/details/{}", doc.identifier),
"Internet Archive".to_string(),
None,
doc.creator,
doc.download_count,
published_at,
"video".to_string(),
5,
)
})
.collect())
}
async fn trending(&self, _region: Option<&str>) -> Result<Vec<VideoDocument>> {
self.search("lecture documentary", 25).await
}
fn source_name(&self) -> &str {
"archive_org"
}
}
impl InternetArchiveClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
}
pub struct VimeoClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct VimeoSearchResponse {
data: Vec<VimeoVideo>,
}
#[derive(Debug, Deserialize)]
struct VimeoVideo {
uri: String,
name: String,
description: Option<String>,
link: String,
duration: u32,
pictures: VimeoPictures,
user: VimeoUser,
#[serde(rename = "release_time")]
release_time: String,
}
#[derive(Debug, Deserialize)]
struct VimeoPictures {
base_link: String,
}
#[derive(Debug, Deserialize)]
struct VimeoUser {
name: String,
}
#[async_trait]
impl VideoSource for VimeoClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let url = format!(
"https://api.vimeo.com/videos?query={}&per_page={}",
urlencoding::encode(query),
limit
);
// Vimeo requires an auth token for their API, but they have a public search page.
// For a real implementation, we'd need a token. Using a placeholder for now
// or a scrape-based approach. Since we want "Real-time", we'll use their public oembed/search.
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Vimeo search failed: {}", query))?;
if response.status() == StatusCode::UNAUTHORIZED {
tracing::debug!("Vimeo API requires authentication, skipping direct API search");
return Ok(vec![]);
}
let data: VimeoSearchResponse = response
.json()
.await
.with_context(|| "Failed to parse Vimeo response")?;
Ok(data
.data
.into_iter()
.map(|v| {
let published_at = DateTime::parse_from_rfc3339(&v.release_time)
.map(|dt| dt.with_timezone(&Utc))
.ok();
VideoDocument::new(
format!("vimeo-{}", v.uri.split('/').next_back().unwrap_or(&v.name)),
v.name,
v.description,
v.pictures.base_link,
v.link,
"Vimeo".to_string(),
Some(v.duration),
Some(v.user.name),
None,
published_at,
"video".to_string(),
7,
)
})
.collect())
}
async fn trending(&self, _region: Option<&str>) -> Result<Vec<VideoDocument>> {
self.search("staff picks", 25).await
}
fn source_name(&self) -> &str {
"vimeo"
}
}
impl VimeoClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
}
/// YouTube Unified Client - uses local youtube-unified service
/// This service combines Piped, Invidious, and yt-dlp for comprehensive YouTube access
pub struct YouTubeUnifiedClient {
client: reqwest::Client,
base_url: String,
}
#[derive(Debug, Deserialize)]
struct YouTubeUnifiedResponse {
items: Vec<YouTubeUnifiedItem>,
}
#[derive(Debug, Deserialize, Clone)]
struct YouTubeUnifiedItem {
#[serde(rename = "videoId")]
video_id: String,
title: String,
thumbnail: String,
channel: Option<String>,
#[serde(rename = "lengthSeconds")]
length_seconds: Option<u32>,
#[serde(rename = "viewCount")]
view_count: Option<u64>,
#[serde(rename = "publishedAt")]
published_at: Option<String>,
#[serde(rename = "author")]
author: Option<String>,
}
#[async_trait]
impl VideoSource for YouTubeUnifiedClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
// Use /search endpoint which uses yt-dlp (more reliable)
let url = format!(
"{}/search?q={}&limit={}",
self.base_url,
urlencoding::encode(query),
limit
);
tracing::debug!("YouTube Unified search: {}", url);
let response = self
.client
.get(&url)
.timeout(Duration::from_secs(10))
.send()
.await
.with_context(|| format!("YouTube Unified search failed: {}", query))?;
if !response.status().is_success() {
tracing::warn!("YouTube Unified returned status: {}", response.status());
return Ok(vec![]);
}
let data: YouTubeUnifiedResponse = response
.json()
.await
.with_context(|| "Failed to parse YouTube Unified response")?;
tracing::info!("YouTube Unified returned {} results", data.items.len());
// Parse published text (e.g., "2 days ago" -> DateTime)
let parse_published = |pub_str: &str| -> Option<DateTime<Utc>> {
let lower = pub_str.to_lowercase();
let num = lower.split_whitespace().next()?.parse::<i64>().ok()?;
let duration = if lower.contains("minute") {
chrono::Duration::minutes(num)
} else if lower.contains("hour") {
chrono::Duration::hours(num)
} else if lower.contains("day") {
chrono::Duration::days(num)
} else if lower.contains("week") {
chrono::Duration::weeks(num)
} else if lower.contains("month") {
chrono::Duration::days(num * 30)
} else if lower.contains("year") {
chrono::Duration::days(num * 365)
} else {
return None;
};
Utc::now().checked_sub_signed(duration)
};
Ok(data
.items
.into_iter()
.take(limit)
.map(|v| {
let published_at = v
.published_at
.as_deref()
.or(v.published_at.as_deref())
.and_then(parse_published);
let channel = v.channel.or(v.author);
VideoDocument::new(
format!("yt-unified-{}", v.video_id),
v.title,
None,
v.thumbnail,
format!("https://www.youtube.com/watch?v={}", v.video_id),
"YouTube (Unified)".to_string(),
v.length_seconds,
channel,
v.view_count,
published_at,
"video".to_string(),
10, // Highest priority
)
})
.collect())
}
async fn trending(&self, region: Option<&str>) -> Result<Vec<VideoDocument>> {
let _region_code = region.unwrap_or("US");
let url = format!("{}/search?q=trending&limit=20", self.base_url);
let response = self
.client
.get(&url)
.timeout(Duration::from_secs(10))
.send()
.await
.with_context(|| "YouTube Unified trending failed")?;
if !response.status().is_success() {
return Ok(vec![]);
}
let data: YouTubeUnifiedResponse = response
.json()
.await
.with_context(|| "Failed to parse YouTube Unified trending response")?;
Ok(data
.items
.into_iter()
.map(|v| {
let channel = v.channel.or(v.author);
VideoDocument::new(
format!("yt-unified-{}", v.video_id),
v.title,
None,
v.thumbnail,
format!("https://www.youtube.com/watch?v={}", v.video_id),
"YouTube Trending".to_string(),
v.length_seconds,
channel,
v.view_count,
None,
"video".to_string(),
10,
)
})
.collect())
}
fn source_name(&self) -> &str {
"youtube_unified"
}
}
impl YouTubeUnifiedClient {
pub fn new(client: reqwest::Client, base_url: String) -> Self {
Self { client, base_url }
}
}
pub struct DailymotionClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct DailymotionResponse {
list: Vec<DailymotionVideo>,
}
#[derive(Debug, Deserialize)]
struct DailymotionVideo {
id: String,
title: String,
description: Option<String>,
thumbnail_url: Option<String>,
created_time: Option<i64>,
owner: Option<String>,
view_count: Option<u64>,
duration: Option<u32>,
}
#[async_trait]
impl VideoSource for DailymotionClient {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
let url = format!(
"https://api.dailymotion.com/videos?search={}&limit={}&fields=id,title,description,thumbnail_url,created_time,owner,view_count,duration",
urlencoding::encode(query),
limit
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Dailymotion search failed: {}", query))?;
let data: DailymotionResponse = response
.json()
.await
.with_context(|| "Failed to parse Dailymotion response")?;
Ok(data
.list
.into_iter()
.map(|v| {
let published_at = v
.created_time
.and_then(|ts| DateTime::from_timestamp(ts, 0))
.map(|dt| dt.with_timezone(&Utc));
VideoDocument::new(
format!("dailymotion-{}", v.id),
v.title,
v.description,
v.thumbnail_url.unwrap_or_default(),
format!("https://www.dailymotion.com/video/{}", v.id),
"Dailymotion".to_string(),
v.duration,
v.owner,
v.view_count,
published_at,
"video".to_string(),
6,
)
})
.collect())
}
async fn trending(&self, _region: Option<&str>) -> Result<Vec<VideoDocument>> {
let url = "https://api.dailymotion.com/videos?sort=trending&limit=25&fields=id,title,description,thumbnail_url,created_time,owner,view_count,duration";
let response = self
.client
.get(url)
.send()
.await
.with_context(|| "Dailymotion trending failed")?;
let data: DailymotionResponse = response
.json()
.await
.with_context(|| "Failed to parse Dailymotion trending response")?;
Ok(data
.list
.into_iter()
.map(|v| {
let published_at = v
.created_time
.and_then(|ts| DateTime::from_timestamp(ts, 0))
.map(|dt| dt.with_timezone(&Utc));
VideoDocument::new(
format!("dailymotion-trending-{}", v.id),
v.title,
v.description,
v.thumbnail_url.unwrap_or_default(),
format!("https://www.dailymotion.com/video/{}", v.id),
"Dailymotion Trending".to_string(),
v.duration,
v.owner,
v.view_count,
published_at,
"video".to_string(),
7,
)
})
.collect())
}
fn source_name(&self) -> &str {
"dailymotion"
}
}
impl DailymotionClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
}
pub struct YtdlpService {
client: reqwest::Client,
ytdlp_path: String,
update_check: Arc<Mutex<Option<Instant>>>,
update_interval_hours: u64,
}
impl YtdlpService {
pub fn new(ytdlp_path: String, update_interval_hours: u64) -> Self {
Self {
client: reqwest::Client::new(),
ytdlp_path,
update_check: Arc::new(Mutex::new(None)),
update_interval_hours,
}
}
pub async fn ensure_updated(&self) -> Result<()> {
let mut last_check = self.update_check.lock().await;
let should_check = match *last_check {
Some(instant) => {
instant.elapsed() > Duration::from_secs(self.update_interval_hours * 3600)
}
None => true,
};
if should_check {
tracing::info!("Checking for yt-dlp updates...");
let output = tokio::process::Command::new(&self.ytdlp_path)
.args(["-U"])
.output()
.await
.with_context(|| "Failed to run yt-dlp update check")?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
tracing::info!("yt-dlp update check: {}", stdout.trim());
} else {
tracing::warn!("yt-dlp update check failed");
}
*last_check = Some(Instant::now());
}
Ok(())
}
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<VideoDocument>> {
self.ensure_updated().await?;
let output = tokio::process::Command::new(&self.ytdlp_path)
.args(["--dump-json", &format!("ytsearch{}:", limit), query])
.output()
.await
.with_context(|| format!("yt-dlp search failed for: {}", query))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let mut results = Vec::new();
for line in stdout.lines() {
if let Ok(video) = serde_json::from_str::<YtdlpVideo>(line) {
let published_at = video
.upload_date
.and_then(|d| chrono::NaiveDate::parse_from_str(&d, "%Y%m%d").ok())
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
results.push(VideoDocument::new(
format!("ytdlp-{}", video.id),
video.title,
video.description,
video.thumbnail.unwrap_or_default(),
video.webpage_url,
"yt-dlp".to_string(),
video.duration,
video.uploader,
Some(video.view_count),
published_at,
"video".to_string(),
8,
));
}
}
Ok(results)
}
}
#[derive(Debug, Deserialize)]
struct YtdlpVideo {
id: String,
title: String,
description: Option<String>,
thumbnail: Option<String>,
#[serde(rename = "webpage_url")]
webpage_url: String,
duration: Option<u32>,
uploader: Option<String>,
view_count: u64,
#[serde(rename = "upload_date")]
upload_date: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_video_document_to_feed_item() {
let doc = VideoDocument::new(
"test-1".to_string(),
"Test Video".to_string(),
Some("Description".to_string()),
"https://example.com/thumb.jpg".to_string(),
"https://example.com/video".to_string(),
"Test".to_string(),
Some(120),
Some("User".to_string()),
Some(1000),
None,
"video".to_string(),
8,
);
let feed: FeedItem = doc.into();
assert_eq!(feed.id, "test-1");
assert_eq!(feed.title, "Test Video");
assert_eq!(feed.source, "Test");
}
#[test]
fn test_video_discovery_config_from_app_config() {
let app_config = crate::config::VideoDiscoveryConfig::default();
let config = VideoDiscoveryConfig::from_app_config(&app_config);
assert_eq!(config.ytdlp_path, "yt-dlp");
assert!(config.enabled_sources.contains(&"piped".to_string()));
}
}
//! Video discovery module for IntentForge v2
//!
//! Provides multi-source video discovery from:
//! - Piped API (YouTube frontend)
//! - Invidious API (YouTube fallback)
//! - Internet Archive (public domain)
//! - Vimeo (professional content)
//! - Dailymotion
//! - yt-dlp (CLI-based batch crawling)
//!
//! Includes intent-first scoring for videos.
mod scoring;
use anyhow::{Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::future::join_all;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{Duration, Instant};
use crate::trending::FeedItem;
use scoring::VideoIntentScorer;
pub struct VideoDocument {
pub id: String,
pub title: String,
pub description: Option<String>,
pub thumbnail: String,
pub url: String,
pub source: String,
pub duration_secs: Option<u32>,
pub uploader: Option<String>,
pub view_count: Option<u64>,
pub published_at: Option<DateTime<Utc>>,
pub category: String,
pub priority: i32,
/// Intent-first scoring
pub intent_score: f32,
pub relevance_score: f32,
pub commercial_score: f32,
pub spam_score: f32,
pub intent_category: String,
pub quality_gate: bool,
}
impl VideoDocument {
/// Create a new VideoDocument with default intent scores
/// Scores will be computed later by VideoIntentScorer
fn new(
id: String,
title: String,
description: Option<String>,
thumbnail: String,
url: String,
source: String,
duration_secs: Option<u32>,
uploader: Option<String>,
view_count: Option<u64>,
published_at: Option<DateTime<Utc>>,
category: String,
priority: i32,
) -> Self {
Self {
id,
title,
description,
thumbnail,
url,
source,
duration_secs,
uploader,
view_count,
published_at,
category,
priority,
intent_score: 0.5,
relevance_score: 0.5,
commercial_score: 0.5,
spam_score: 0.5,
intent_category: "Unknown".to_string(),
quality_gate: true,
}
}
}
impl From<VideoDocument> for FeedItem {
fn from(doc: VideoDocument) -> Self {
FeedItem {
id: doc.id,
title: doc.title,
link: doc.url,