2023-04-27 17:53:28 +03:00
|
|
|
//! This module provides the functionality to scrape and gathers all the results from the upstream
|
|
|
|
//! search engines and then removes duplicate results.
|
|
|
|
|
2023-08-23 13:11:09 +03:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
io::{BufReader, Read},
|
|
|
|
time::Duration,
|
|
|
|
};
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-04-25 16:30:04 +03:00
|
|
|
use super::{
|
2023-08-18 10:43:53 +02:00
|
|
|
aggregation_models::{EngineErrorInfo, SearchResult, SearchResults},
|
2023-04-25 16:30:04 +03:00
|
|
|
user_agent::random_user_agent,
|
|
|
|
};
|
2023-08-22 19:16:37 +03:00
|
|
|
use error_stack::Report;
|
|
|
|
use rand::Rng;
|
|
|
|
use regex::Regex;
|
|
|
|
use std::{fs::File, io::BufRead};
|
|
|
|
use tokio::task::JoinHandle;
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-08-22 19:16:37 +03:00
|
|
|
use crate::{
|
|
|
|
engines::engine_models::{EngineError, EngineHandler},
|
|
|
|
handler::paths::{file_path, FileType},
|
|
|
|
};
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-07-15 13:36:46 +03:00
|
|
|
/// Aliases for long type annotations
|
2023-08-18 10:43:53 +02:00
|
|
|
type FutureVec = Vec<JoinHandle<Result<HashMap<String, SearchResult>, Report<EngineError>>>>;
|
2023-07-14 21:27:23 +03:00
|
|
|
|
2023-07-17 10:47:29 +03:00
|
|
|
/// The function aggregates the scraped results from the user-selected upstream search engines.
|
|
|
|
/// These engines can be chosen either from the user interface (UI) or from the configuration file.
|
|
|
|
/// The code handles this process by matching the selected search engines and adding them to a vector.
|
|
|
|
/// This vector is then used to create an asynchronous task vector using `tokio::spawn`, which returns
|
|
|
|
/// a future. This future is awaited in another loop. Once the results are collected, they are filtered
|
|
|
|
/// to remove any errors and ensure only proper results are included. If an error is encountered, it is
|
|
|
|
/// sent to the UI along with the name of the engine and the type of error. This information is finally
|
|
|
|
/// placed in the returned `SearchResults` struct.
|
|
|
|
///
|
|
|
|
/// Additionally, the function eliminates duplicate results. If two results are identified as coming from
|
|
|
|
/// multiple engines, their names are combined to indicate that the results were fetched from these upstream
|
|
|
|
/// engines. After this, all the data in the `HashMap` is removed and placed into a struct that contains all
|
|
|
|
/// the aggregated results in a vector. Furthermore, the query used is also added to the struct. This step is
|
|
|
|
/// necessary to ensure that the search bar in the search remains populated even when searched from the query URL.
|
|
|
|
///
|
|
|
|
/// Overall, this function serves to aggregate scraped results from user-selected search engines, handling errors,
|
|
|
|
/// removing duplicates, and organizing the data for display in the UI.
|
2023-04-27 17:53:28 +03:00
|
|
|
///
|
|
|
|
/// # Example:
|
|
|
|
///
|
|
|
|
/// If you search from the url like `https://127.0.0.1/search?q=huston` then the search bar should
|
|
|
|
/// contain the word huston and not remain empty.
|
2023-05-07 21:18:19 +03:00
|
|
|
///
|
2023-04-27 17:53:28 +03:00
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `query` - Accepts a string to query with the above upstream search engines.
|
2023-05-02 11:58:21 +03:00
|
|
|
/// * `page` - Accepts an u32 page number.
|
2023-05-22 01:13:06 +00:00
|
|
|
/// * `random_delay` - Accepts a boolean value to add a random delay before making the request.
|
2023-07-15 13:36:46 +03:00
|
|
|
/// * `debug` - Accepts a boolean value to enable or disable debug mode option.
|
|
|
|
/// * `upstream_search_engines` - Accepts a vector of search engine names which was selected by the
|
2023-07-30 17:08:47 +03:00
|
|
|
/// * `request_timeout` - Accepts a time (secs) as a value which controls the server request timeout.
|
2023-07-15 13:36:46 +03:00
|
|
|
/// user through the UI or the config file.
|
2023-04-27 17:53:28 +03:00
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
2023-05-07 21:18:19 +03:00
|
|
|
/// Returns an error a reqwest and scraping selector errors if any error occurs in the results
|
2023-04-27 17:53:28 +03:00
|
|
|
/// function in either `searx` or `duckduckgo` or both otherwise returns a `SearchResults struct`
|
|
|
|
/// containing appropriate values.
|
2023-04-22 14:35:07 +03:00
|
|
|
pub async fn aggregate(
|
2023-07-11 19:44:38 +03:00
|
|
|
query: String,
|
2023-05-02 11:58:21 +03:00
|
|
|
page: u32,
|
2023-05-22 01:13:06 +00:00
|
|
|
random_delay: bool,
|
2023-05-29 21:28:09 +03:00
|
|
|
debug: bool,
|
2023-08-18 10:43:53 +02:00
|
|
|
upstream_search_engines: Vec<EngineHandler>,
|
2023-07-30 10:53:48 +03:00
|
|
|
request_timeout: u8,
|
2023-04-22 14:35:07 +03:00
|
|
|
) -> Result<SearchResults, Box<dyn std::error::Error>> {
|
2023-04-25 16:30:04 +03:00
|
|
|
let user_agent: String = random_user_agent();
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-05-07 21:18:19 +03:00
|
|
|
// Add a random delay before making the request.
|
2023-05-29 21:28:09 +03:00
|
|
|
if random_delay || !debug {
|
2023-05-22 01:13:06 +00:00
|
|
|
let mut rng = rand::thread_rng();
|
|
|
|
let delay_secs = rng.gen_range(1..10);
|
2023-08-17 21:45:48 +02:00
|
|
|
tokio::time::sleep(Duration::from_secs(delay_secs)).await;
|
2023-05-22 01:13:06 +00:00
|
|
|
}
|
2023-05-07 21:18:19 +03:00
|
|
|
|
2023-08-18 10:43:53 +02:00
|
|
|
let mut names: Vec<&str> = vec![];
|
|
|
|
|
2023-08-17 22:48:20 +02:00
|
|
|
// create tasks for upstream result fetching
|
2023-08-18 10:43:53 +02:00
|
|
|
let mut tasks: FutureVec = FutureVec::new();
|
|
|
|
|
|
|
|
for engine_handler in upstream_search_engines {
|
|
|
|
let (name, search_engine) = engine_handler.into_name_engine();
|
|
|
|
names.push(name);
|
|
|
|
let query: String = query.clone();
|
|
|
|
let user_agent: String = user_agent.clone();
|
|
|
|
tasks.push(tokio::spawn(async move {
|
|
|
|
search_engine
|
|
|
|
.results(query, page, user_agent.clone(), request_timeout)
|
|
|
|
.await
|
|
|
|
}));
|
|
|
|
}
|
2023-06-15 06:27:45 +08:00
|
|
|
|
2023-08-17 22:48:20 +02:00
|
|
|
// get upstream responses
|
|
|
|
let mut responses = Vec::with_capacity(tasks.len());
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-07-11 19:44:38 +03:00
|
|
|
for task in tasks {
|
2023-07-14 12:56:06 +03:00
|
|
|
if let Ok(result) = task.await {
|
2023-08-17 22:48:20 +02:00
|
|
|
responses.push(result)
|
2023-07-14 12:56:06 +03:00
|
|
|
}
|
2023-07-11 19:44:38 +03:00
|
|
|
}
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-08-17 22:48:20 +02:00
|
|
|
// aggregate search results, removing duplicates and handling errors the upstream engines returned
|
2023-08-18 10:43:53 +02:00
|
|
|
let mut result_map: HashMap<String, SearchResult> = HashMap::new();
|
2023-07-14 21:27:23 +03:00
|
|
|
let mut engine_errors_info: Vec<EngineErrorInfo> = Vec::new();
|
|
|
|
|
2023-08-17 22:48:20 +02:00
|
|
|
let mut handle_error = |error: Report<EngineError>, engine_name: String| {
|
|
|
|
log::error!("Engine Error: {:?}", error);
|
|
|
|
engine_errors_info.push(EngineErrorInfo::new(
|
|
|
|
error.downcast_ref::<EngineError>().unwrap(),
|
2023-08-22 19:16:37 +03:00
|
|
|
engine_name,
|
2023-08-17 22:48:20 +02:00
|
|
|
));
|
|
|
|
};
|
|
|
|
|
|
|
|
for _ in 0..responses.len() {
|
|
|
|
let response = responses.pop().unwrap();
|
2023-08-18 10:43:53 +02:00
|
|
|
let engine = names.pop().unwrap().to_string();
|
2023-08-17 22:48:20 +02:00
|
|
|
|
|
|
|
if result_map.is_empty() {
|
|
|
|
match response {
|
|
|
|
Ok(results) => {
|
|
|
|
result_map = results.clone();
|
2023-07-11 19:44:38 +03:00
|
|
|
}
|
2023-08-17 22:48:20 +02:00
|
|
|
Err(error) => {
|
2023-08-18 10:43:53 +02:00
|
|
|
handle_error(error, engine);
|
2023-07-11 19:44:38 +03:00
|
|
|
}
|
|
|
|
}
|
2023-08-17 22:48:20 +02:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
match response {
|
|
|
|
Ok(result) => {
|
|
|
|
result.into_iter().for_each(|(key, value)| {
|
|
|
|
result_map
|
|
|
|
.entry(key)
|
|
|
|
.and_modify(|result| {
|
2023-08-18 10:43:53 +02:00
|
|
|
result.add_engines(engine.clone());
|
2023-08-17 22:48:20 +02:00
|
|
|
})
|
2023-08-18 10:43:53 +02:00
|
|
|
.or_insert_with(|| -> SearchResult { value });
|
2023-08-17 22:48:20 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
Err(error) => {
|
2023-08-18 10:43:53 +02:00
|
|
|
handle_error(error, engine);
|
2023-07-11 19:44:38 +03:00
|
|
|
}
|
|
|
|
}
|
2023-08-17 22:48:20 +02:00
|
|
|
}
|
|
|
|
|
2023-08-22 19:16:37 +03:00
|
|
|
let mut blacklist_map: HashMap<String, SearchResult> = HashMap::new();
|
|
|
|
filter_with_lists(
|
|
|
|
&mut result_map,
|
|
|
|
&mut blacklist_map,
|
|
|
|
&file_path(FileType::BlockList)?,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
filter_with_lists(
|
|
|
|
&mut blacklist_map,
|
|
|
|
&mut result_map,
|
|
|
|
&file_path(FileType::AllowList)?,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
drop(blacklist_map);
|
|
|
|
|
|
|
|
let results: Vec<SearchResult> = result_map.into_values().collect();
|
2023-04-22 14:35:07 +03:00
|
|
|
|
2023-04-25 16:30:04 +03:00
|
|
|
Ok(SearchResults::new(
|
2023-08-17 22:48:20 +02:00
|
|
|
results,
|
2023-04-25 16:30:04 +03:00
|
|
|
query.to_string(),
|
2023-07-14 21:27:23 +03:00
|
|
|
engine_errors_info,
|
2023-04-25 16:30:04 +03:00
|
|
|
))
|
2023-04-22 14:35:07 +03:00
|
|
|
}
|
2023-08-22 19:16:37 +03:00
|
|
|
|
2023-08-24 09:29:08 +08:00
|
|
|
/// Filters a map of search results using a list of regex patterns.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `map_to_be_filtered` - A mutable reference to a `HashMap` of search results to filter, where the filtered results will be removed from.
|
|
|
|
/// * `resultant_map` - A mutable reference to a `HashMap` to hold the filtered results.
|
|
|
|
/// * `file_path` - A `&str` representing the path to a file containing regex patterns to use for filtering.
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// Returns an error if the file at `file_path` cannot be opened or read, or if a regex pattern is invalid.
|
|
|
|
pub fn filter_with_lists(
|
2023-08-22 19:16:37 +03:00
|
|
|
map_to_be_filtered: &mut HashMap<String, SearchResult>,
|
|
|
|
resultant_map: &mut HashMap<String, SearchResult>,
|
|
|
|
file_path: &str,
|
|
|
|
) -> Result<(), Box<dyn std::error::Error>> {
|
2023-08-23 13:11:09 +03:00
|
|
|
let mut reader = BufReader::new(File::open(file_path)?);
|
2023-08-24 09:29:08 +08:00
|
|
|
|
2023-08-23 13:11:09 +03:00
|
|
|
for line in reader.by_ref().lines() {
|
|
|
|
let re = Regex::new(&line?)?;
|
2023-08-24 09:29:08 +08:00
|
|
|
|
|
|
|
// Iterate over each search result in the map and check if it matches the regex pattern
|
2023-08-23 13:11:09 +03:00
|
|
|
for (url, search_result) in map_to_be_filtered.clone().into_iter() {
|
2023-08-22 19:16:37 +03:00
|
|
|
if re.is_match(&url.to_lowercase())
|
|
|
|
|| re.is_match(&search_result.title.to_lowercase())
|
|
|
|
|| re.is_match(&search_result.description.to_lowercase())
|
|
|
|
{
|
2023-08-24 09:29:08 +08:00
|
|
|
// If the search result matches the regex pattern, move it from the original map to the resultant map
|
2023-08-22 19:16:37 +03:00
|
|
|
resultant_map.insert(url.clone(), map_to_be_filtered.remove(&url).unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-08-24 09:29:08 +08:00
|
|
|
|
2023-08-22 19:16:37 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
2023-08-24 09:29:08 +08:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::io::Write;
|
|
|
|
use tempfile::NamedTempFile;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_filter_with_lists() -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
// Create a map of search results to filter
|
|
|
|
let mut map_to_be_filtered = HashMap::new();
|
|
|
|
map_to_be_filtered.insert(
|
|
|
|
"https://www.example.com".to_string(),
|
|
|
|
SearchResult {
|
|
|
|
title: "Example Domain".to_string(),
|
|
|
|
url: "https://www.example.com".to_string(),
|
|
|
|
description: "This domain is for use in illustrative examples in documents.".to_string(),
|
|
|
|
engine: vec!["Google".to_string(), "Bing".to_string()],
|
|
|
|
},
|
|
|
|
);
|
|
|
|
map_to_be_filtered.insert(
|
|
|
|
"https://www.rust-lang.org/".to_string(),
|
|
|
|
SearchResult {
|
|
|
|
title: "Rust Programming Language".to_string(),
|
|
|
|
url: "https://www.rust-lang.org/".to_string(),
|
|
|
|
description: "A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.".to_string(),
|
|
|
|
engine: vec!["Google".to_string(), "DuckDuckGo".to_string()],
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
// Create a temporary file with regex patterns
|
|
|
|
let mut file = NamedTempFile::new()?;
|
|
|
|
writeln!(file, "example")?;
|
|
|
|
writeln!(file, "rust")?;
|
|
|
|
file.flush()?;
|
|
|
|
|
|
|
|
let mut resultant_map = HashMap::new();
|
|
|
|
filter_with_lists(&mut map_to_be_filtered, &mut resultant_map, file.path().to_str().unwrap())?;
|
|
|
|
|
|
|
|
assert_eq!(resultant_map.len(), 2);
|
|
|
|
assert!(resultant_map.contains_key("https://www.example.com"));
|
|
|
|
assert!(resultant_map.contains_key("https://www.rust-lang.org/"));
|
|
|
|
assert_eq!(map_to_be_filtered.len(), 0);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2023-08-24 09:32:22 +08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_filter_with_lists_file_not_found() {
|
|
|
|
let mut map_to_be_filtered = HashMap::new();
|
|
|
|
|
|
|
|
let mut resultant_map = HashMap::new();
|
|
|
|
|
|
|
|
// Call the `filter_with_lists` function with a non-existent file path
|
|
|
|
let result = filter_with_lists(&mut map_to_be_filtered, &mut resultant_map, "non-existent-file.txt");
|
|
|
|
|
|
|
|
assert!(result.is_err());
|
|
|
|
}
|
2023-08-24 09:36:08 +08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_filter_with_lists_invalid_regex() {
|
|
|
|
let mut map_to_be_filtered = HashMap::new();
|
|
|
|
map_to_be_filtered.insert(
|
|
|
|
"https://www.example.com".to_string(),
|
|
|
|
SearchResult {
|
|
|
|
title: "Example Domain".to_string(),
|
|
|
|
url: "https://www.example.com".to_string(),
|
|
|
|
description: "This domain is for use in illustrative examples in documents.".to_string(),
|
|
|
|
engine: vec!["Google".to_string(), "Bing".to_string()],
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let mut resultant_map = HashMap::new();
|
|
|
|
|
|
|
|
// Create a temporary file with an invalid regex pattern
|
|
|
|
let mut file = NamedTempFile::new().unwrap();
|
|
|
|
writeln!(file, "example(").unwrap();
|
|
|
|
file.flush().unwrap();
|
|
|
|
|
|
|
|
let result = filter_with_lists(&mut map_to_be_filtered, &mut resultant_map, file.path().to_str().unwrap());
|
|
|
|
|
|
|
|
assert!(result.is_err());
|
|
|
|
}
|
2023-08-24 09:29:08 +08:00
|
|
|
}
|