//! Trending monitor module for IntentForge v2 //! //! Monitors RSS feeds and GitHub trending to discover high-signal content. use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// RSS feed source configuration #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FeedSource { pub name: String, pub url: String, pub category: String, #[serde(default = "default_priority")] pub priority: u32, } /// Domain to monitor #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DomainSource { pub name: String, pub base_url: String, pub category: String, #[serde(default = "default_priority")] pub priority: u32, pub sitemap: Option, } /// Seed URL configuration #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SeedSource { pub name: String, pub url: String, pub category: String, #[serde(default = "default_priority")] pub priority: u32, } fn default_priority() -> u32 { 5 } /// Parsed feed item #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FeedItem { pub id: String, pub title: String, pub link: String, pub description: Option, pub published_at: Option>, pub source: String, pub category: String, pub priority: u32, } /// Trending item with scores #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TrendingItem { pub id: String, pub title: String, pub url: String, pub category: String, pub source: String, pub trending_score: f32, pub velocity: f32, pub published_at: Option>, } /// Feed sources configuration #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SourcesConfig { pub sources: Vec, #[serde(default)] pub domains: Vec, #[serde(default)] pub seed_urls: Vec, } impl SourcesConfig { /// Load sources from YAML file pub fn from_file>(path: P) -> Result { let file = std::fs::File::open(path.as_ref()) .with_context(|| format!("Failed to open sources file: {:?}", path.as_ref()))?; let config: SourcesConfig = serde_yaml::from_reader(file).with_context(|| "Failed to parse sources YAML")?; Ok(config) } /// Group sources by category pub fn by_category(&self) -> HashMap> { let mut by_cat: HashMap> = HashMap::new(); for source in &self.sources { by_cat .entry(source.category.clone()) .or_default() .push(source); } by_cat } } /// Trending monitor pub struct TrendingMonitor { sources: Vec, client: reqwest::Client, } /// List of human-like user agents to rotate const USER_AGENTS: &[&str] = &[ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", ]; impl TrendingMonitor { /// Create a new trending monitor pub fn new(sources: Vec) -> Result { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::ACCEPT, reqwest::header::HeaderValue::from_static( "application/rss+xml, application/atom+xml, application/xml, text/xml, */*", ), ); headers.insert( reqwest::header::ACCEPT_ENCODING, reqwest::header::HeaderValue::from_static("gzip, deflate, br"), ); headers.insert( reqwest::header::ACCEPT_LANGUAGE, reqwest::header::HeaderValue::from_static("en-US,en;q=0.9"), ); headers.insert( reqwest::header::CACHE_CONTROL, reqwest::header::HeaderValue::from_static("max-age=0"), ); // Use first user agent by default let user_agent = USER_AGENTS[0]; let client = reqwest::Client::builder() .user_agent(user_agent) .default_headers(headers) .timeout(std::time::Duration::from_secs(30)) .build() .with_context(|| "Failed to create HTTP client")?; Ok(Self { sources, client }) } /// Get a random user agent fn random_user_agent() -> &'static str { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); std::time::SystemTime::now().hash(&mut hasher); let idx = (hasher.finish() as usize) % USER_AGENTS.len(); USER_AGENTS[idx] } /// Add random delay between requests (100-500ms) async fn random_delay() { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); std::time::SystemTime::now().hash(&mut hasher); let delay_ms = 100 + (hasher.finish() % 400); tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await; } /// Fetch and parse a single RSS feed with retry logic and HTML fallback pub async fn fetch_feed(&self, source: &FeedSource) -> Result> { let mut last_err = None; let max_retries = 3; for attempt in 1..=max_retries { match self.fetch_feed_internal(source).await { Ok(items) => { if !items.is_empty() { return Ok(items); } // Empty feed, try HTML scraping as fallback } Err(e) => { tracing::warn!( "Attempt {}/{} failed for {}: {}", attempt, max_retries, source.name, e ); last_err = Some(e); if attempt < max_retries { tokio::time::sleep(std::time::Duration::from_secs(attempt * 2)).await; } } } } // If RSS failed, try HTML scraping as fallback tracing::info!( "RSS failed for {}, trying HTML scraping fallback", source.name ); match self.scrape_html_fallback(source).await { Ok(items) if !items.is_empty() => { tracing::info!( "HTML scraping found {} items for {}", items.len(), source.name ); return Ok(items); } _ => {} } Err(last_err.unwrap_or_else(|| { anyhow::anyhow!("Failed to fetch feed after {} attempts", max_retries) })) } /// HTML scraping fallback when RSS fails async fn scrape_html_fallback(&self, source: &FeedSource) -> Result> { // Get the base URL from the feed URL let base_url = if let Ok(url) = url::Url::parse(&source.url) { format!("{}://{}", url.scheme(), url.host_str().unwrap_or("")) } else { return Ok(Vec::new()); }; // Try common article pages let paths = vec!["/", "/blog", "/news", "/articles"]; let mut all_items = Vec::new(); for path in paths { let url = format!("{}{}", base_url.trim_end_matches('/'), path); match self .client .get(&url) .header("User-Agent", Self::random_user_agent()) .header("Accept", "text/html,application/xhtml+xml") .send() .await { Ok(resp) if resp.status().is_success() => { if let Ok(html) = resp.text().await { let items = self.extract_links_from_html(&html, &base_url, source); all_items.extend(items); } } _ => continue, } if !all_items.is_empty() { break; } } // Deduplicate by URL let mut seen_urls = std::collections::HashSet::new(); all_items.retain(|item| seen_urls.insert(item.link.clone())); // Limit to 10 items all_items.truncate(10); Ok(all_items) } /// Extract links from HTML as feed items fn extract_links_from_html( &self, html: &str, base_url: &str, source: &FeedSource, ) -> Vec { let mut items = Vec::new(); // Simple regex to find links with titles let link_regex = regex::Regex::new(r#"]+href="([^"]+)"[^>]*>([^<]{20,200})"#).unwrap(); for cap in link_regex.captures_iter(html) { if let (Some(href), Some(title)) = (cap.get(1), cap.get(2)) { let href = href.as_str(); let title = title.as_str().trim(); // Skip navigation links, etc. if title.len() < 20 || title.len() > 200 { continue; } if href.starts_with('#') || href.starts_with("javascript:") { continue; } // Build full URL let full_url = if href.starts_with("http") { href.to_string() } else if href.starts_with('/') { format!("{}{}", base_url.trim_end_matches('/'), href) } else { format!("{}/{}", base_url.trim_end_matches('/'), href) }; // Skip if same domain as base (likely navigation) if let (Ok(base), Ok(link)) = (url::Url::parse(base_url), url::Url::parse(&full_url)) { if base.host_str() == link.host_str() { items.push(FeedItem { id: format!("scraped-{}", items.len()), title: title.to_string(), link: full_url, description: Some(format!("Scraped from {}", source.name)), published_at: Some(chrono::Utc::now()), source: source.name.clone(), category: source.category.clone(), priority: source.priority, }); } } } } items } /// Internal fetch logic with human-like headers async fn fetch_feed_internal(&self, source: &FeedSource) -> Result> { // Add random delay between requests Self::random_delay().await; // Build request with human-like headers let response = self .client .get(&source.url) .header("User-Agent", Self::random_user_agent()) .header( "Accept", "application/rss+xml, application/atom+xml, application/xml, text/xml, */*", ) .header("Accept-Language", "en-US,en;q=0.9") .header("Referer", "https://www.google.com/") .header("DNT", "1") .header("Connection", "keep-alive") .header("Upgrade-Insecure-Requests", "1") .send() .await .with_context(|| format!("Network error fetching feed: {}", source.url))?; let status = response.status(); let content_type = response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .unwrap_or("unknown") .to_string(); // Handle 403 Forbidden - try with different approach if status == 403 { // Try fetching via HTTPS with different user agent let https_url = source.url.replace("http://", "https://"); if https_url != source.url { tracing::info!("Retrying {} with HTTPS", source.name); return self.fetch_with_different_client(&https_url, source).await; } anyhow::bail!("HTTP 403 Forbidden (site blocks automated access)"); } if !status.is_success() { anyhow::bail!("HTTP {} (Content-Type: {})", status, content_type); } let bytes = response .bytes() .await .with_context(|| format!("Failed to read feed body: {}", source.url))?; // Parse RSS/Atom feed match self.parse_feed(&bytes, source) { Ok(items) => Ok(items), Err(e) => { let body_preview = String::from_utf8_lossy(&bytes); let preview_len = body_preview.len().min(256); anyhow::bail!( "Parsing error: {} - Body start: {}", e, &body_preview[..preview_len] ); } } } /// Try fetching with a different HTTP client configuration async fn fetch_with_different_client( &self, url: &str, source: &FeedSource, ) -> Result> { // Create a new client with different settings let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::ACCEPT, reqwest::header::HeaderValue::from_static("*/*"), ); headers.insert( reqwest::header::ACCEPT_LANGUAGE, reqwest::header::HeaderValue::from_static("en-US,en;q=0.5"), ); let client = reqwest::Client::builder() .user_agent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)") .default_headers(headers) .timeout(std::time::Duration::from_secs(30)) .build()?; let response = client .get(url) .send() .await .with_context(|| format!("Network error fetching feed: {}", url))?; if !response.status().is_success() { anyhow::bail!("HTTP {} even with different client", response.status()); } let bytes = response.bytes().await?; self.parse_feed(&bytes, source) } /// Parse RSS/Atom XML into feed items fn parse_feed(&self, xml_bytes: &[u8], source: &FeedSource) -> Result> { let feed = feed_rs::parser::parse(xml_bytes) .with_context(|| format!("Failed to parse feed from {}", source.name))?; let mut items = Vec::new(); for entry in feed.entries { let id = entry.id; let title = entry .title .map(|t| t.content) .unwrap_or_else(|| "Untitled".to_string()); let link = entry .links .first() .map(|l| l.href.clone()) .unwrap_or_default(); let description = entry.summary.map(|s| s.content); let published_at = entry.published.or(entry.updated); items.push(FeedItem { id, title, link, description, published_at, source: source.name.clone(), category: source.category.clone(), priority: source.priority, }); } Ok(items) } /// Fetch all feeds and return items pub async fn fetch_all(self: std::sync::Arc) -> Result> { let mut all_items = Vec::new(); let mut set = tokio::task::JoinSet::new(); for source in self.sources.clone() { let self_clone = self.clone(); set.spawn(async move { // Add a timeout to individual feed fetches to prevent stalling match tokio::time::timeout( std::time::Duration::from_secs(30), self_clone.fetch_feed(&source), ) .await { Ok(Ok(items)) => Ok((source.name, items)), Ok(Err(e)) => Err(format!("{}: {}", source.name, e)), Err(_) => Err(format!("{}: Timeout after 30s", source.name)), } }); } while let Some(res) = set.join_next().await { match res { Ok(Ok((_name, items))) => all_items.extend(items), Ok(Err(e)) => tracing::warn!("Failed to fetch feed: {}", e), Err(e) => tracing::error!("Join error: {}", e), } } // Also fetch GitHub trending (single source, sequential is fine) match self.fetch_github_trending().await { Ok(items) => all_items.extend(items), Err(e) => tracing::warn!("Failed to fetch GitHub trending: {}", e), } // Also fetch Hacker News New Stories match self.fetch_hacker_news().await { Ok(items) => all_items.extend(items), Err(e) => tracing::warn!("Failed to fetch Hacker News: {}", e), } Ok(all_items) } /// Fetch Hacker News New Stories using the Firebase API pub async fn fetch_hacker_news(&self) -> Result> { let url = "https://hacker-news.firebaseio.com/v0/newstories.json"; let response = self .client .get(url) .send() .await .with_context(|| "Failed to fetch Hacker News new stories IDs")?; let ids: Vec = response .json() .await .with_context(|| "Failed to parse HN story IDs")?; let mut items = Vec::new(); // Limit to top 30 new stories to avoid rate limiting and excessive work let top_ids = &ids[..30.min(ids.len())]; let mut fetch_tasks = Vec::new(); for &id in top_ids { let client = self.client.clone(); fetch_tasks.push(tokio::spawn(async move { let story_url = format!("https://hacker-news.firebaseio.com/v0/item/{}.json", id); match client.get(&story_url).send().await { Ok(resp) => resp.json::().await.ok(), Err(_) => None, } })); } let results = futures::future::join_all(fetch_tasks).await; for result in results { if let Ok(Some(story)) = result { let id = story["id"].as_u64().unwrap_or(0).to_string(); let title = story["title"] .as_str() .unwrap_or("Untitled Hacker News Story") .to_string(); let link = match story["url"].as_str() { Some(l) => l.to_string(), None => continue, // Skip stories with no external link (Ask HN, etc.) }; let published_at = story["time"] .as_i64() .map(|t| DateTime::from_timestamp(t, 0).unwrap_or_default()); items.push(FeedItem { id: format!("hn-{}", id), title, link, description: Some(format!("New story on Hacker News (ID: {})", id)), published_at, source: "Hacker News".to_string(), category: "tech".to_string(), priority: 8, }); } } Ok(items) } /// Get pre-computed embedding for a category (placeholder) pub fn get_category_embedding(&self, category: &str) -> Vec { // Pre-computed embeddings for categories using a 384-dim vector (MiniLM-L6-v2) // For now, returning a deterministic dummy vector based on category name let mut vector = vec![0.0; 384]; for (i, byte) in category.as_bytes().iter().enumerate() { if i < 384 { vector[i] = (*byte as f32) / 255.0; } } vector } /// Fetch GitHub trending repositories pub async fn fetch_github_trending(&self) -> Result> { let url = "https://github.com/trending"; let response = self .client .get(url) .send() .await .with_context(|| "Failed to fetch GitHub trending")?; let html = response .text() .await .with_context(|| "Failed to read GitHub trending body")?; let document = scraper::Html::parse_document(&html); // Select repo rows from the trending page let row_selector = scraper::Selector::parse("article.Box-row") .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?; let repo_selector = scraper::Selector::parse("h2 a") .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?; let desc_selector = scraper::Selector::parse("p") .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?; let lang_selector = scraper::Selector::parse("[itemprop=programmingLanguage]") .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?; let stars_selector = scraper::Selector::parse("a[href*='/stargazers']") .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?; let mut items = Vec::new(); for row in document.select(&row_selector) { // Extract repo path from link let repo_path = row .select(&repo_selector) .next() .and_then(|el| el.value().attr("href")) .map(|s| s.trim().trim_start_matches('/').to_string()); let repo_name = match repo_path { Some(name) if !name.is_empty() => name, _ => continue, }; // Extract description let description = row .select(&desc_selector) .next() .map(|el| el.text().collect::().trim().to_string()) .filter(|s| !s.is_empty()); // Extract language let language = row .select(&lang_selector) .next() .map(|el| el.text().collect::().trim().to_string()); // Extract star count let stars = row .select(&stars_selector) .next() .map(|el| el.text().collect::().trim().replace(",", "")) .and_then(|s| s.parse::().ok()); let mut tags = Vec::new(); if let Some(lang) = language { tags.push(lang); } let mut desc_text = description.unwrap_or_else(|| "Trending repository on GitHub".to_string()); if let Some(stars) = stars { desc_text.push_str(&format!(" ({} stars)", stars)); } items.push(FeedItem { id: format!("gh-trending-{}", repo_name.replace("/", "-")), title: format!("GitHub: {}", repo_name), link: format!("https://github.com/{}", repo_name), description: Some(desc_text), published_at: Some(Utc::now()), source: "GitHub Trending".to_string(), category: "devtools".to_string(), priority: 9, }); if items.len() >= 25 { break; } } if items.is_empty() { tracing::warn!( "No trending repos found on GitHub page, HTML structure may have changed" ); } Ok(items) } /// Calculate trending score for items pub fn calculate_trending(&self, items: Vec) -> Vec { let now = Utc::now(); items .into_iter() .map(|item| { // Calculate velocity based on recency and priority let age_hours = item .published_at .map(|t| now.signed_duration_since(t).num_seconds() as f32 / 3600.0) .unwrap_or(24.0); // Decay function: newer items get higher velocity let velocity = (item.priority as f32) / (age_hours + 1.0).ln(); // Trending score combines velocity with category weight let trending_score = velocity * get_category_weight(&item.category); TrendingItem { id: item.id, title: item.title, url: item.link, category: item.category, source: item.source, trending_score, velocity, published_at: item.published_at, } }) .collect() } } /// Get category weight for trending calculation fn get_category_weight(category: &str) -> f32 { match category { "ai" => 1.5, "tech" => 1.2, "startups" => 1.1, "devtools" => 1.0, "science" => 1.3, "products" => 1.2, _ => 1.0, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_category_weight() { assert_eq!(get_category_weight("ai"), 1.5); assert_eq!(get_category_weight("tech"), 1.2); assert_eq!(get_category_weight("unknown"), 1.0); } }