Spaces:
Build error
Build error
File size: 3,985 Bytes
0ca462b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | #![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
}
}
|