Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame Contribute Delete
3.99 kB
#![allow(dead_code)]
//! LibreX search provider - Lightweight PHP metasearch
//!
//! LibreX is a zero-config, lightweight metasearch engine.
//! This provider uses a self-hosted instance for maximum privacy and speed.
use crate::meta_search::models::SearchResult;
use crate::meta_search::providers::{SearchContext, SearchProvider};
use anyhow::{Context, Result};
use async_trait::async_trait;
use reqwest::Client;
use serde::Deserialize;
use std::sync::Arc;
use tokio::time::{timeout, Duration};
#[derive(Debug, Deserialize)]
struct LibreXResponse {
#[serde(default)]
results: Vec<LibreXResult>,
}
#[derive(Debug, Deserialize)]
struct LibreXResult {
#[serde(default)]
title: String,
#[serde(default)]
url: String,
#[serde(default)]
snippet: String,
}
/// Self-hosted LibreX provider
pub struct LibreXProvider {
client: Arc<Client>,
instance_url: String,
}
impl LibreXProvider {
pub fn new(client: Arc<Client>, instance_url: &str) -> Self {
Self {
client,
instance_url: instance_url.to_string(),
}
}
async fn query_instance(
&self,
query: &str,
ctx: Arc<SearchContext>,
) -> Result<Vec<SearchResult>> {
let url = format!(
"{}/search.php?q={}&format=json",
self.instance_url,
urlencoding::encode(query)
);
// Strategy: First attempt with direct client, if blocked try with proxy
let resp = match timeout(Duration::from_millis(1500), self.client.get(&url).send()).await {
Ok(Ok(r)) if r.status().is_success() => r,
_ => {
// If direct failed or timed out, try with a proxy if available
if let Some(proxy) = ctx.proxy_manager.get_random_proxy().await {
let proxy_client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all(proxy.to_url())?)
.timeout(Duration::from_secs(5))
.build()?;
match timeout(Duration::from_secs(5), proxy_client.get(&url).send()).await {
Ok(Ok(r)) if r.status().is_success() => r,
_ => return Ok(vec![]),
}
} else {
return Ok(vec![]);
}
}
};
if !resp.status().is_success() {
return Ok(vec![]);
}
let body = resp.text().await?;
if body.contains("CAPTCHA")
|| body.contains("503 Service Unavailable")
|| body.contains("Too many requests")
{
tracing::warn!("LibreX instance blocked by backend engine");
return Ok(vec![]);
}
let parsed: LibreXResponse = serde_json::from_str(&body)?;
let results: Vec<SearchResult> = parsed
.results
.into_iter()
.filter(|r| !r.url.is_empty() && !r.title.is_empty())
.map(|r| SearchResult {
title: r.title.trim().to_string(),
url: r.url,
description: r.snippet.trim().to_string(),
source: "librex(self-hosted)".to_string(),
score: 0.75,
media_type: "text".to_string(),
thumbnail_url: None,
published_at: None,
})
.collect();
Ok(results)
}
}
#[async_trait]
impl SearchProvider for LibreXProvider {
fn name(&self) -> &'static str {
"librex"
}
async fn search(&self, query: &str, ctx: Arc<SearchContext>) -> Result<Vec<SearchResult>> {
self.query_instance(query, ctx)
.await
.with_context(|| format!("LibreX self-hosted instance failed for '{}'", query))
.or_else(|e| {
tracing::debug!("{}", e);
Ok(vec![])
})
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}