Spaces:
Build error
Build error
Download src/sources/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 36.5 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/sources/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/sources/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/sources/mod.rs
36.5 kB
#![allow(dead_code)]
//! API-based data sources for IntentForge v2
//!
//! Integrates with Hacker News Algolia, YouTube (Invidious), StackOverflow,
//! academic APIs (PubMed, bioRxiv, Semantic Scholar), and social platforms
//! (Reddit, Lobsters) for high-signal content discovery.
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use crate::trending::FeedItem;
/// Hacker News Algolia API client
///
/// Uses the public Algolia REST API (no keys required).
/// Rate limit: ~10k requests/hour (generous for our use case).
#[derive(Debug, Clone)]
pub struct HackerNewsAlgoliaClient {
client: reqwest::Client,
base_url: String,
}
#[derive(Debug, Deserialize)]
struct HnAlgoliaResponse {
hits: Vec<HnAlgoliaHit>,
}
#[derive(Debug, Deserialize)]
struct HnAlgoliaHit {
#[serde(rename = "objectID")]
object_id: String,
title: Option<String>,
url: Option<String>,
#[serde(rename = "created_at")]
created_at: String,
points: Option<u64>,
#[serde(rename = "num_comments")]
num_comments: Option<u64>,
}
impl HackerNewsAlgoliaClient {
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
base_url: "https://hn.algolia.com/api/v1".to_string(),
}
}
/// Search Hacker News stories by query
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"{}/search?query={}&tags=story&hitsPerPage={}",
self.base_url,
urlencoding::encode(query),
limit
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Failed to search HN Algolia: {}", query))?;
let data: HnAlgoliaResponse = response
.json()
.await
.with_context(|| "Failed to parse HN Algolia response")?;
let items = data
.hits
.into_iter()
.filter_map(|hit| {
let link = match hit.url {
Some(url) if !url.is_empty() => url,
_ => return None,
};
let published_at = chrono::DateTime::parse_from_rfc3339(&hit.created_at)
.ok()
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("hn-algolia-{}", hit.object_id),
title: hit.title.unwrap_or_else(|| "Untitled HN Story".to_string()),
link,
description: Some(format!(
"HN: {} points, {} comments",
hit.points.unwrap_or(0),
hit.num_comments.unwrap_or(0)
)),
published_at,
source: "Hacker News Algolia".to_string(),
category: "tech".to_string(),
priority: 10,
})
})
.collect();
Ok(items)
}
/// Fetch front page stories (by relevance/points)
pub async fn front_page(&self, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"{}/search?tags=front_page&hitsPerPage={}",
self.base_url, limit
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to fetch HN front page from Algolia")?;
let data: HnAlgoliaResponse = response
.json()
.await
.with_context(|| "Failed to parse HN Algolia response")?;
let items = data
.hits
.into_iter()
.filter_map(|hit| {
let link = match hit.url {
Some(url) if !url.is_empty() => url,
_ => return None,
};
let published_at = chrono::DateTime::parse_from_rfc3339(&hit.created_at)
.ok()
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("hn-algolia-{}", hit.object_id),
title: hit.title.unwrap_or_else(|| "Untitled HN Story".to_string()),
link,
description: Some(format!(
"HN front page: {} points, {} comments",
hit.points.unwrap_or(0),
hit.num_comments.unwrap_or(0)
)),
published_at,
source: "Hacker News Algolia".to_string(),
category: "tech".to_string(),
priority: 10,
})
})
.collect();
Ok(items)
}
}
/// YouTube client via Invidious public instances
///
/// Invidious provides a privacy-focused YouTube API proxy.
/// Uses public instances with automatic failover.
#[derive(Debug, Clone)]
pub struct InvidiousClient {
client: reqwest::Client,
instances: Vec<String>,
current_instance: usize,
}
#[derive(Debug, Deserialize)]
struct InvidiousVideo {
video_id: String,
title: String,
description: Option<String>,
published: Option<i64>,
view_count: Option<u64>,
author: Option<String>,
}
impl InvidiousClient {
/// Create a new Invidious client with public instance list
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
instances: vec![
"https://invidious.nerdvpn.de".to_string(),
"https://inv.tux.pizza".to_string(),
"https://invidious.privacyredirect.com".to_string(),
"https://yewtu.be".to_string(),
],
current_instance: 0,
}
}
fn base_url(&self) -> &str {
&self.instances[self.current_instance]
}
fn rotate_instance(&mut self) {
self.current_instance = (self.current_instance + 1) % self.instances.len();
}
/// Search YouTube videos via Invidious API
pub async fn search(&mut self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"{}/api/v1/search?q={}&type=video&page=0",
self.base_url(),
urlencoding::encode(query)
);
let response = match self.client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => resp,
Ok(resp) => {
tracing::warn!(
"Invidious instance {} returned {}, rotating",
self.base_url(),
resp.status()
);
self.rotate_instance();
let url = format!(
"{}/api/v1/search?q={}&type=video&page=0",
self.base_url(),
urlencoding::encode(query)
);
self.client
.get(&url)
.send()
.await
.with_context(|| "All Invidious instances failed")?
}
Err(e) => {
tracing::warn!(
"Invidious instance {} failed: {}, rotating",
self.base_url(),
e
);
self.rotate_instance();
let url = format!(
"{}/api/v1/search?q={}&type=video&page=0",
self.base_url(),
urlencoding::encode(query)
);
self.client
.get(&url)
.send()
.await
.with_context(|| "All Invidious instances failed")?
}
};
let videos: Vec<InvidiousVideo> = response
.json()
.await
.with_context(|| "Failed to parse Invidious response")?;
let items = 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));
FeedItem {
id: format!("yt-{}", v.video_id),
title: v.title,
link: format!("https://www.youtube.com/watch?v={}", v.video_id),
description: v.description.or(v.author.map(|a| format!("By {}", a))),
published_at,
source: "YouTube".to_string(),
category: "tech".to_string(),
priority: 7,
}
})
.collect();
Ok(items)
}
/// Fetch trending videos from Invidious
pub async fn trending(&mut self, region: &str) -> Result<Vec<FeedItem>> {
let url = format!(
"{}/api/v1/trending?type=default®ion={}",
self.base_url(),
region
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to fetch YouTube trending via Invidious")?;
let videos: Vec<InvidiousVideo> = response
.json()
.await
.with_context(|| "Failed to parse Invidious trending response")?;
let items = 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));
FeedItem {
id: format!("yt-trending-{}", v.video_id),
title: v.title,
link: format!("https://www.youtube.com/watch?v={}", v.video_id),
description: v.description.or(v.author.map(|a| format!("By {}", a))),
published_at,
source: "YouTube Trending".to_string(),
category: "tech".to_string(),
priority: 8,
}
})
.collect();
Ok(items)
}
}
/// StackOverflow client via StackExchange API
///
/// Anonymous access up to 300 requests/day.
/// Uses the official StackExchange API v2.3.
#[derive(Debug, Clone)]
pub struct StackOverflowClient {
client: reqwest::Client,
api_key: Option<String>,
}
#[derive(Debug, Deserialize)]
struct StackExchangeResponse {
items: Vec<StackExchangeQuestion>,
#[serde(rename = "quota_remaining")]
quota_remaining: Option<u32>,
}
#[derive(Debug, Deserialize)]
struct StackExchangeQuestion {
#[serde(rename = "question_id")]
question_id: u64,
title: String,
link: String,
score: i64,
tags: Vec<String>,
#[serde(rename = "creation_date")]
creation_date: i64,
#[serde(rename = "answer_count")]
answer_count: Option<u64>,
#[serde(rename = "view_count")]
view_count: Option<u64>,
}
impl StackOverflowClient {
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
api_key: None,
}
}
pub fn with_api_key(mut self, key: &str) -> Self {
self.api_key = Some(key.to_string());
self
}
/// Search StackOverflow questions
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let mut url = format!(
"https://api.stackexchange.com/2.3/search/advanced?order=desc&sort=relevance&q={}&site=stackoverflow&pagesize={}",
urlencoding::encode(query),
limit
);
if let Some(ref key) = self.api_key {
url.push_str(&format!("&key={}", key));
}
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to search StackOverflow")?;
let data: StackExchangeResponse = response
.json()
.await
.with_context(|| "Failed to parse StackOverflow response")?;
if let Some(remaining) = data.quota_remaining {
tracing::debug!("StackExchange API quota remaining: {}", remaining);
if remaining < 10 {
tracing::warn!("StackExchange API quota running low: {}", remaining);
}
}
let items = data
.items
.into_iter()
.map(|q| {
let published_at =
DateTime::from_timestamp(q.creation_date, 0).map(|dt| dt.with_timezone(&Utc));
FeedItem {
id: format!("so-{}", q.question_id),
title: html_decode(&q.title),
link: q.link,
description: Some(format!(
"Score: {}, Answers: {}, Views: {}",
q.score,
q.answer_count.unwrap_or(0),
q.view_count.unwrap_or(0)
)),
published_at,
source: "StackOverflow".to_string(),
category: "devtools".to_string(),
priority: 9,
}
})
.collect();
Ok(items)
}
/// Fetch hot questions from StackOverflow
pub async fn hot_questions(&self, limit: usize) -> Result<Vec<FeedItem>> {
let mut url = format!(
"https://api.stackexchange.com/2.3/questions?order=desc&sort=hot&site=stackoverflow&pagesize={}",
limit
);
if let Some(ref key) = self.api_key {
url.push_str(&format!("&key={}", key));
}
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to fetch hot StackOverflow questions")?;
let data: StackExchangeResponse = response
.json()
.await
.with_context(|| "Failed to parse StackOverflow response")?;
let items = data
.items
.into_iter()
.map(|q| {
let published_at =
DateTime::from_timestamp(q.creation_date, 0).map(|dt| dt.with_timezone(&Utc));
FeedItem {
id: format!("so-hot-{}", q.question_id),
title: html_decode(&q.title),
link: q.link,
description: Some(format!(
"Hot: Score {}, {} answers",
q.score,
q.answer_count.unwrap_or(0)
)),
published_at,
source: "StackOverflow Hot".to_string(),
category: "devtools".to_string(),
priority: 9,
}
})
.collect();
Ok(items)
}
}
/// PubMed E-utilities API client
#[derive(Debug, Clone)]
pub struct PubMedClient {
client: reqwest::Client,
api_key: Option<String>,
}
#[derive(Debug, Deserialize)]
struct PubMedSearchResponse {
esearchresult: PubMedSearchResult,
}
#[derive(Debug, Deserialize)]
struct PubMedSearchResult {
idlist: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct PubMedSummaryResponse {
result: serde_json::Value,
}
impl PubMedClient {
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
api_key: None,
}
}
pub fn with_api_key(mut self, key: &str) -> Self {
self.api_key = Some(key.to_string());
self
}
/// Search PubMed articles
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let mut url = format!(
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax={}&sort=relevance&retmode=json&term={}",
limit,
urlencoding::encode(query)
);
if let Some(ref key) = self.api_key {
url.push_str(&format!("&api_key={}", key));
}
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to search PubMed")?;
let search_data: PubMedSearchResponse = response
.json()
.await
.with_context(|| "Failed to parse PubMed search response")?;
if search_data.esearchresult.idlist.is_empty() {
return Ok(Vec::new());
}
// Fetch summaries for the IDs
let ids = search_data.esearchresult.idlist.join(",");
let mut summary_url = format!(
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&id={}",
ids
);
if let Some(ref key) = self.api_key {
summary_url.push_str(&format!("&api_key={}", key));
}
let summary_response = self
.client
.get(&summary_url)
.send()
.await
.with_context(|| "Failed to fetch PubMed summaries")?;
let summary_data: PubMedSummaryResponse = summary_response
.json()
.await
.with_context(|| "Failed to parse PubMed summary response")?;
let mut items = Vec::new();
if let Some(result_map) = summary_data.result.as_object() {
for (id, data) in result_map {
if id == "uids" {
continue;
}
let title = data["title"].as_str().unwrap_or("Untitled").to_string();
let source_name = data["source"].as_str().unwrap_or("PubMed").to_string();
let pub_date = data["pubdate"].as_str().unwrap_or("").to_string();
let published_at = chrono::NaiveDate::parse_from_str(
&pub_date
.split_whitespace()
.take(3)
.collect::<Vec<_>>()
.join(" "),
"%Y %b %d",
)
.ok()
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
items.push(FeedItem {
id: format!("pubmed-{}", id),
title: html_decode(&title),
link: format!("https://pubmed.ncbi.nlm.nih.gov/{}/", id),
description: Some(format!("Published in {}", source_name)),
published_at,
source: "PubMed".to_string(),
category: "science".to_string(),
priority: 9,
});
}
}
Ok(items)
}
}
/// Semantic Scholar API client
#[derive(Debug, Clone)]
pub struct SemanticScholarClient {
client: reqwest::Client,
api_key: Option<String>,
}
#[derive(Debug, Deserialize)]
struct SemanticScholarResponse {
data: Vec<SemanticScholarPaper>,
}
#[derive(Debug, Deserialize)]
struct SemanticScholarPaper {
#[serde(rename = "paperId")]
paper_id: String,
title: String,
#[serde(rename = "abstract")]
abstract_text: Option<String>,
url: Option<String>,
#[serde(rename = "publicationDate")]
publication_date: Option<String>,
#[serde(rename = "citationCount")]
citation_count: Option<u64>,
venue: Option<String>,
}
impl SemanticScholarClient {
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
api_key: None,
}
}
pub fn with_api_key(mut self, key: &str) -> Self {
self.api_key = Some(key.to_string());
self
}
/// Search papers on Semantic Scholar
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"https://api.semanticscholar.org/graph/v1/paper/search?query={}&limit={}&fields=title,abstract,url,publicationDate,citationCount,venue",
urlencoding::encode(query),
limit
);
let mut request = self.client.get(&url);
if let Some(ref key) = self.api_key {
request = request.header("x-api-key", key);
}
let response = request
.send()
.await
.with_context(|| "Failed to search Semantic Scholar")?;
let data: SemanticScholarResponse = response
.json()
.await
.with_context(|| "Failed to parse Semantic Scholar response")?;
let items = data
.data
.into_iter()
.map(|p| {
let published_at = p
.publication_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));
FeedItem {
id: format!("s2-{}", p.paper_id),
title: p.title,
link: p.url.unwrap_or_else(|| {
format!("https://www.semanticscholar.org/paper/{}", p.paper_id)
}),
description: p.abstract_text.or(p.venue.map(|v| {
format!(
"Citations: {} | Venue: {}",
p.citation_count.unwrap_or(0),
v
)
})),
published_at,
source: "Semantic Scholar".to_string(),
category: "science".to_string(),
priority: 9,
}
})
.collect();
Ok(items)
}
}
/// bioRxiv API client (date-based polling)
///
/// bioRxiv doesn't have a traditional search API, so we poll by date range.
#[derive(Debug, Clone)]
pub struct BioRxivClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct BioRxivResponse {
collection: Vec<BioRxivPaper>,
}
#[derive(Debug, Deserialize)]
struct BioRxivPaper {
doi: String,
title: String,
authors: Option<String>,
#[serde(rename = "abstract")]
abstract_text: Option<String>,
date: String,
category: Option<String>,
server: Option<String>,
}
impl BioRxivClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
/// Fetch recent papers from bioRxiv (last N days)
pub async fn recent(&self, days: u64, limit: usize) -> Result<Vec<FeedItem>> {
let end = Utc::now().date_naive();
let start = end - chrono::Duration::days(days as i64);
let url = format!(
"https://api.biorxiv.org/details/biorxiv/{}/{}",
start.format("%Y-%m-%d"),
end.format("%Y-%m-%d")
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| "Failed to fetch bioRxiv papers")?;
let data: BioRxivResponse = response
.json()
.await
.with_context(|| "Failed to parse bioRxiv response")?;
let items = data
.collection
.into_iter()
.take(limit)
.map(|p| {
let published_at = chrono::NaiveDate::parse_from_str(&p.date, "%Y-%m-%d")
.ok()
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|dt| DateTime::from_naive_utc_and_offset(dt, Utc));
FeedItem {
id: format!("biorxiv-{}", p.doi.replace('/', "-")),
title: p.title,
link: format!("https://doi.org/{}", p.doi),
description: p
.abstract_text
.or(p.authors.map(|a| format!("Authors: {}", a))),
published_at,
source: "bioRxiv".to_string(),
category: "science".to_string(),
priority: 8,
}
})
.collect();
Ok(items)
}
}
/// Reddit client (JSON endpoint via .json suffix)
#[derive(Debug, Clone)]
pub struct RedditClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct RedditResponse {
data: RedditListing,
}
#[derive(Debug, Deserialize)]
struct RedditListing {
children: Vec<RedditChild>,
}
#[derive(Debug, Deserialize)]
struct RedditChild {
data: RedditPost,
}
#[derive(Debug, Deserialize)]
struct RedditPost {
id: String,
title: String,
url: String,
selftext: Option<String>,
score: i64,
num_comments: u64,
subreddit: String,
created_utc: f64,
}
impl RedditClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
/// Fetch posts from a subreddit
pub async fn subreddit(&self, name: &str, sort: &str, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"https://www.reddit.com/r/{}/{}.json?limit={}",
name, sort, limit
);
let response = self
.client
.get(&url)
.header("User-Agent", "IntentForge/0.1 (Content Discovery)")
.send()
.await
.with_context(|| format!("Failed to fetch subreddit r/{}", name))?;
let data: RedditResponse = response
.json()
.await
.with_context(|| format!("Failed to parse Reddit response for r/{}", name))?;
let items = data
.data
.children
.into_iter()
.filter_map(|child| {
let post = child.data;
// Skip Reddit internal links (self posts)
if post.url.starts_with("https://www.reddit.com/") {
return None;
}
let published_at = DateTime::from_timestamp(post.created_utc as i64, 0)
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("reddit-{}", post.id),
title: post.title,
link: post.url,
description: Some(format!(
"r/{}: {} points, {} comments",
post.subreddit, post.score, post.num_comments
)),
published_at,
source: format!("Reddit r/{}", post.subreddit),
category: "tech".to_string(),
priority: 7,
})
})
.collect();
Ok(items)
}
}
/// Lobsters client (JSON endpoint)
#[derive(Debug, Clone)]
pub struct LobstersClient {
client: reqwest::Client,
}
#[derive(Debug, Deserialize)]
struct LobstersStory {
short_id: String,
title: String,
url: String,
description: Option<String>,
score: i64,
comment_count: u64,
created_at: String,
tags: Vec<String>,
}
impl LobstersClient {
pub fn new(client: reqwest::Client) -> Self {
Self { client }
}
/// Fetch hottest stories from Lobsters
pub async fn hottest(&self, limit: usize) -> Result<Vec<FeedItem>> {
let url = "https://lobste.rs/hottest.json";
let response = self
.client
.get(url)
.send()
.await
.with_context(|| "Failed to fetch Lobsters hottest")?;
let stories: Vec<LobstersStory> = response
.json()
.await
.with_context(|| "Failed to parse Lobsters response")?;
let items = stories
.into_iter()
.take(limit)
.filter_map(|s| {
if s.url.is_empty() {
return None;
}
let published_at = chrono::DateTime::parse_from_rfc3339(&s.created_at)
.ok()
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("lobsters-{}", s.short_id),
title: s.title,
link: s.url,
description: s.description.or(Some(format!(
"Score: {}, Comments: {}",
s.score, s.comment_count
))),
published_at,
source: "Lobsters".to_string(),
category: "tech".to_string(),
priority: 7,
})
})
.collect();
Ok(items)
}
/// Fetch newest stories from Lobsters
pub async fn newest(&self, limit: usize) -> Result<Vec<FeedItem>> {
let url = "https://lobste.rs/newest.json";
let response = self
.client
.get(url)
.send()
.await
.with_context(|| "Failed to fetch Lobsters newest")?;
let stories: Vec<LobstersStory> = response
.json()
.await
.with_context(|| "Failed to parse Lobsters response")?;
let items = stories
.into_iter()
.take(limit)
.filter_map(|s| {
if s.url.is_empty() {
return None;
}
let published_at = chrono::DateTime::parse_from_rfc3339(&s.created_at)
.ok()
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("lobsters-newest-{}", s.short_id),
title: s.title,
link: s.url,
description: s.description.or(Some(format!(
"Score: {}, Comments: {}",
s.score, s.comment_count
))),
published_at,
source: "Lobsters Newest".to_string(),
category: "tech".to_string(),
priority: 6,
})
})
.collect();
Ok(items)
}
}
/// Unified API sources aggregator
pub struct ApiSources {
hn: HackerNewsAlgoliaClient,
youtube: InvidiousClient,
stackoverflow: StackOverflowClient,
pubmed: PubMedClient,
semantic_scholar: SemanticScholarClient,
biorxiv: BioRxivClient,
reddit: RedditClient,
lobsters: LobstersClient,
}
impl ApiSources {
/// Create a new API sources aggregator
pub fn new(client: reqwest::Client) -> Self {
Self {
hn: HackerNewsAlgoliaClient::new(client.clone()),
youtube: InvidiousClient::new(client.clone()),
stackoverflow: StackOverflowClient::new(client.clone()),
pubmed: PubMedClient::new(client.clone()),
semantic_scholar: SemanticScholarClient::new(client.clone()),
biorxiv: BioRxivClient::new(client.clone()),
reddit: RedditClient::new(client.clone()),
lobsters: LobstersClient::new(client),
}
}
/// Fetch all sources and aggregate results
pub async fn fetch_all(&mut self, per_source_limit: usize) -> Vec<FeedItem> {
let mut all_items = Vec::new();
// Hacker News Algolia front page
match self.hn.front_page(per_source_limit).await {
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("HN Algolia failed: {}", e),
}
// YouTube trending
match self.youtube.trending("US").await {
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("YouTube trending failed: {}", e),
}
// StackOverflow hot
match self.stackoverflow.hot_questions(per_source_limit).await {
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("StackOverflow hot failed: {}", e),
}
// PubMed recent AI papers
match self
.pubmed
.search("artificial intelligence", per_source_limit)
.await
{
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("PubMed search failed: {}", e),
}
// Semantic Scholar recent AI papers
match self
.semantic_scholar
.search("machine learning", per_source_limit)
.await
{
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("Semantic Scholar search failed: {}", e),
}
// bioRxiv recent papers
match self.biorxiv.recent(7, per_source_limit).await {
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("bioRxiv fetch failed: {}", e),
}
// Reddit tech subreddits
for subreddit in &["programming", "machinelearning", "technology"] {
match self
.reddit
.subreddit(subreddit, "hot", per_source_limit)
.await
{
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("Reddit r/{} failed: {}", subreddit, e),
}
}
// Lobsters
match self.lobsters.hottest(per_source_limit).await {
Ok(items) => all_items.extend(items),
Err(e) => tracing::warn!("Lobsters failed: {}", e),
}
all_items
}
}
/// Decode HTML entities in strings
fn html_decode(s: &str) -> String {
s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_html_decode() {
assert_eq!(html_decode("Test & Page"), "Test & Page");
assert_eq!(html_decode("A < B"), "A < B");
assert_eq!(html_decode("Quote "test""), "Quote \"test\"");
}
#[test]
fn test_hn_algolia_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let hn = HackerNewsAlgoliaClient::new(client);
assert_eq!(hn.base_url, "https://hn.algolia.com/api/v1");
}
#[test]
fn test_invidious_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let yt = InvidiousClient::new(client);
assert!(!yt.instances.is_empty());
assert_eq!(yt.current_instance, 0);
}
#[test]
fn test_invidious_instance_rotation() {
let client = reqwest::Client::builder().build().unwrap();
let mut yt = InvidiousClient::new(client);
yt.rotate_instance();
// After rotation, index should change (unless only 1 instance)
assert_eq!(yt.current_instance, 1);
}
#[test]
fn test_stackoverflow_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let so = StackOverflowClient::new(client);
assert!(so.api_key.is_none());
}
#[test]
fn test_stackoverflow_client_with_key() {
let client = reqwest::Client::builder().build().unwrap();
let so = StackOverflowClient::new(client).with_api_key("test-key");
assert_eq!(so.api_key, Some("test-key".to_string()));
}
#[test]
fn test_reddit_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _reddit = RedditClient::new(client);
}
#[test]
fn test_lobsters_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _lobsters = LobstersClient::new(client);
}
#[test]
fn test_pubmed_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _pubmed = PubMedClient::new(client);
}
#[test]
fn test_semantic_scholar_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _s2 = SemanticScholarClient::new(client);
}
#[test]
fn test_biorxiv_client_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _biorxiv = BioRxivClient::new(client);
}
#[test]
fn test_api_sources_aggregator_creation() {
let client = reqwest::Client::builder().build().unwrap();
let _sources = ApiSources::new(client);
}
}
//! API-based data sources for IntentForge v2
//!
//! Integrates with Hacker News Algolia, YouTube (Invidious), StackOverflow,
//! academic APIs (PubMed, bioRxiv, Semantic Scholar), and social platforms
//! (Reddit, Lobsters) for high-signal content discovery.
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use crate::trending::FeedItem;
/// Hacker News Algolia API client
///
/// Uses the public Algolia REST API (no keys required).
/// Rate limit: ~10k requests/hour (generous for our use case).
pub struct HackerNewsAlgoliaClient {
client: reqwest::Client,
base_url: String,
}
struct HnAlgoliaResponse {
hits: Vec<HnAlgoliaHit>,
}
struct HnAlgoliaHit {
object_id: String,
title: Option<String>,
url: Option<String>,
created_at: String,
points: Option<u64>,
num_comments: Option<u64>,
}
impl HackerNewsAlgoliaClient {
pub fn new(client: reqwest::Client) -> Self {
Self {
client,
base_url: "https://hn.algolia.com/api/v1".to_string(),
}
}
/// Search Hacker News stories by query
pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<FeedItem>> {
let url = format!(
"{}/search?query={}&tags=story&hitsPerPage={}",
self.base_url,
urlencoding::encode(query),
limit
);
let response = self
.client
.get(&url)
.send()
.await
.with_context(|| format!("Failed to search HN Algolia: {}", query))?;
let data: HnAlgoliaResponse = response
.json()
.await
.with_context(|| "Failed to parse HN Algolia response")?;
let items = data
.hits
.into_iter()
.filter_map(|hit| {
let link = match hit.url {
Some(url) if !url.is_empty() => url,
_ => return None,
};
let published_at = chrono::DateTime::parse_from_rfc3339(&hit.created_at)
.ok()
.map(|dt| dt.with_timezone(&Utc));
Some(FeedItem {
id: format!("hn-algolia-{}", hit.object_id),
title: hit.title.unwrap_or_else(|| "Untitled HN Story".to_string()),
link,
description: Some(format!(
"HN: {} points, {} comments",
hit.points.unwrap_or(0),
hit.num_comments.unwrap_or(0)
)),
published_at,
source: "Hacker News Algolia".to_string(),
category: "tech".to_string(),
priority: 10,
})
})
.collect();