rearranged to singular module
This commit is contained in:
43
src/backend/mod.rs
Normal file
43
src/backend/mod.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use curl::easy::Easy;
|
||||
pub use scraper;
|
||||
use scraper::Html;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SearchResult {
|
||||
pub title: String,
|
||||
pub snippet: String,
|
||||
pub link: String,
|
||||
}
|
||||
|
||||
pub struct SiteHtmlFilter {
|
||||
pub title_selector: String,
|
||||
pub snippet_selector: String,
|
||||
pub url_selector: String,
|
||||
}
|
||||
|
||||
pub fn get_sanitised_html_graph(plaintext: &str) -> Html {
|
||||
let tree = Html::parse_document(plaintext);
|
||||
return tree;
|
||||
}
|
||||
|
||||
pub fn scrape_url_blocking(url: &str) -> String {
|
||||
let mut data = Vec::new();
|
||||
|
||||
let mut handle = Easy::new();
|
||||
handle.url(url).unwrap();
|
||||
|
||||
{
|
||||
let mut transfer = handle.transfer();
|
||||
|
||||
transfer
|
||||
.write_function(|new_data| {
|
||||
data.extend_from_slice(new_data);
|
||||
Ok(new_data.len())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
transfer.perform().unwrap();
|
||||
}
|
||||
|
||||
String::from_utf8(data).unwrap()
|
||||
}
|
||||
58
src/lua/engine_decoder.rs
Normal file
58
src/lua/engine_decoder.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use mlua::Function;
|
||||
|
||||
pub struct Engine {
|
||||
pub grabber: Function,
|
||||
pub builder: Function,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub fn get_engine_vec(
|
||||
lua_instance: &mut mlua::Lua,
|
||||
engine_table: mlua::Table,
|
||||
) -> mlua::Result<Vec<Engine>> {
|
||||
let mut engine_vec: Vec<Engine> = Vec::new();
|
||||
|
||||
for pair in engine_table.pairs::<String, mlua::Value>() {
|
||||
let (name, functions) = pair.expect("Invalid Search Engine Pair");
|
||||
|
||||
println!("{}", name);
|
||||
|
||||
let mut grabber_function: Option<mlua::Function> = None;
|
||||
let mut builder_function: Option<mlua::Function> = lua_instance
|
||||
.globals()
|
||||
.get("DefaultBuilder")
|
||||
.expect("Could Not Unwrap DefaultBuilder");
|
||||
|
||||
match functions {
|
||||
// If only grabber is supplied
|
||||
mlua::Value::Function(function) => grabber_function = Some(function),
|
||||
mlua::Value::Table(table) => {
|
||||
for inner_pair in table.pairs::<String, mlua::Function>() {
|
||||
let (name, function) = inner_pair.expect("Error decoding pairs");
|
||||
|
||||
match name.as_str() {
|
||||
"grabber" => grabber_function = Some(function),
|
||||
"builder" => builder_function = Some(function),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
eprintln!("Unexpected value in returned lua table")
|
||||
}
|
||||
}
|
||||
let current_engine = Engine {
|
||||
name: name,
|
||||
builder: builder_function.ok_or(mlua::Error::RuntimeError(
|
||||
"Missing Builder Function".to_string(),
|
||||
))?,
|
||||
grabber: grabber_function.ok_or(mlua::Error::RuntimeError(
|
||||
"Missing Grabber Function".to_string(),
|
||||
))?,
|
||||
};
|
||||
|
||||
engine_vec.push(current_engine)
|
||||
}
|
||||
Ok(engine_vec)
|
||||
}
|
||||
121
src/lua/luahtml.rs
Normal file
121
src/lua/luahtml.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use crate::backend::scraper;
|
||||
use mlua::{Table, UserData, UserDataMethods};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct LuaHtml {
|
||||
pub document: scraper::Html,
|
||||
}
|
||||
|
||||
impl UserData for LuaHtml {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
// Allow documents to be implicitly converted to strings
|
||||
methods.add_meta_method(mlua::MetaMethod::ToString, |_, this, ()| {
|
||||
Ok(this.document.root_element().html())
|
||||
});
|
||||
|
||||
// Return table of all snippets (as LuaHtml objects) matching a certain css selector
|
||||
methods.add_method("filter", |lua, this, filter: String| {
|
||||
let selector = scraper::Selector::parse(&filter).map_err(mlua::Error::external)?;
|
||||
|
||||
let output = lua.create_table()?;
|
||||
|
||||
for (index, element) in this.document.select(&selector).enumerate() {
|
||||
let html = element.html();
|
||||
|
||||
let document = scraper::Html::parse_fragment(&html);
|
||||
|
||||
output.set(index + 1, lua.create_userdata(LuaHtml { document })?)?;
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
});
|
||||
|
||||
// Return a table of tables matching the input schema, with all found results
|
||||
// requires source attribute that matches one of the given fields, ie title
|
||||
methods.add_method("scrape", |lua, this, config: Table| {
|
||||
let mut selectors = Vec::new();
|
||||
|
||||
// Determine which configured selector provides the result containers.
|
||||
let source_name: String = config.get("source")?;
|
||||
|
||||
// Compile all configured selectors.
|
||||
for pair in config.pairs::<String, String>() {
|
||||
let (name, selector_string) = pair?;
|
||||
|
||||
// First element heirarchically, other fields have to be found after this
|
||||
if name == "source" {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (selector_string, attribute) = match selector_string.split_once('/') {
|
||||
Some((selector, attribute)) => (selector, Some(attribute.to_string())),
|
||||
None => (selector_string.as_str(), None),
|
||||
};
|
||||
|
||||
let css_selector =
|
||||
scraper::Selector::parse(selector_string).map_err(mlua::Error::external)?;
|
||||
|
||||
selectors.push((name, css_selector, attribute));
|
||||
}
|
||||
|
||||
// Find the explicitly configured source selector.
|
||||
let source_selector = selectors
|
||||
.iter()
|
||||
.find(|(name, _, _)| name == &source_name)
|
||||
.map(|(_, selector, _)| selector)
|
||||
.ok_or_else(|| {
|
||||
mlua::Error::external(format!("Source selector '{}' not found", source_name))
|
||||
})?;
|
||||
|
||||
// Collect source elements.
|
||||
let source_elements: Vec<_> = this.document.select(source_selector).collect();
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
// Extract matching elements by index.
|
||||
for (index, _) in source_elements.iter().enumerate() {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
for (name, selector, attribute) in &selectors {
|
||||
let value = this.document.select(selector).nth(index);
|
||||
|
||||
let extracted = match (value, attribute) {
|
||||
(Some(element), Some(attribute)) => {
|
||||
element.value().attr(attribute).unwrap_or("").to_string()
|
||||
}
|
||||
|
||||
(Some(element), None) => element
|
||||
.text()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.trim()
|
||||
.to_string(),
|
||||
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
|
||||
result.insert(name.clone(), extracted);
|
||||
}
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Convert results into Lua tables.
|
||||
let output = lua.create_table()?;
|
||||
|
||||
for (index, result) in results.iter().enumerate() {
|
||||
let result_table = lua.create_table()?;
|
||||
|
||||
for (key, value) in result {
|
||||
result_table.set(key.as_str(), value.as_str())?;
|
||||
}
|
||||
|
||||
output.set(index + 1, result_table)?;
|
||||
}
|
||||
|
||||
// println!("output {:#?}", &output);
|
||||
|
||||
Ok(output)
|
||||
});
|
||||
}
|
||||
}
|
||||
58
src/lua/mod.rs
Normal file
58
src/lua/mod.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use crate::backend;
|
||||
use mlua::{Lua, Table};
|
||||
use std::fs;
|
||||
|
||||
mod luahtml;
|
||||
use luahtml::LuaHtml;
|
||||
|
||||
pub mod engine_decoder;
|
||||
|
||||
pub fn create_instance() -> mlua::Lua {
|
||||
mlua::Lua::new()
|
||||
}
|
||||
|
||||
pub fn intialise_lua(instance: &mut mlua::Lua, path: Option<String>) -> mlua::Result<Table> {
|
||||
let lua = instance;
|
||||
|
||||
let function_table = create_lua_function_table(&lua)?;
|
||||
|
||||
lua.globals().set("idx", function_table)?;
|
||||
|
||||
let path = path.unwrap_or("./config.lua".to_string());
|
||||
let file_info = fs::read_to_string(path)?;
|
||||
|
||||
lua.load(&file_info).exec()?;
|
||||
|
||||
let search_engines: Table = lua.globals().get("SearchEngines")?;
|
||||
Ok(search_engines)
|
||||
}
|
||||
|
||||
fn create_lua_function_table(lua: &Lua) -> mlua::Result<Table> {
|
||||
let idx_table = lua.create_table()?;
|
||||
|
||||
// lua.globals().set(
|
||||
// "DefaultBuilder",
|
||||
// "function (values) return '<p>'..values.title..'</p>'",
|
||||
// )?;
|
||||
|
||||
idx_table.set(
|
||||
"request",
|
||||
lua.create_async_function(|_, url: String| async move {
|
||||
let scraped_data =
|
||||
tokio::task::spawn_blocking(move || backend::scrape_url_blocking(&url))
|
||||
.await
|
||||
.map_err(mlua::Error::external)?;
|
||||
Ok(scraped_data)
|
||||
})?,
|
||||
)?;
|
||||
|
||||
idx_table.set(
|
||||
"decodeHtml",
|
||||
lua.create_function(|_, result: String| {
|
||||
let document = backend::get_sanitised_html_graph(&result);
|
||||
Ok(LuaHtml { document })
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(idx_table)
|
||||
}
|
||||
43
src/main.rs
Normal file
43
src/main.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
mod lua;
|
||||
use lua::engine_decoder;
|
||||
|
||||
pub mod backend;
|
||||
|
||||
use std::{env, process};
|
||||
|
||||
mod runner;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let mut args = env::args();
|
||||
let _bin = args.next();
|
||||
|
||||
let mut config_location: Option<String> = None;
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--config" | "-c" => {
|
||||
config_location = args.next().or_else(|| {
|
||||
eprintln!("--config needs a path");
|
||||
process::exit(1)
|
||||
})
|
||||
}
|
||||
&_ => {
|
||||
eprintln!("Unknown command line option {}", arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Long lived lua instance
|
||||
let mut lua_instance = lua::create_instance();
|
||||
|
||||
let engine_table: mlua::Table =
|
||||
lua::intialise_lua(&mut lua_instance, config_location).expect("Failed to initialise lua");
|
||||
|
||||
let engine_vec = engine_decoder::get_engine_vec(&mut lua_instance, engine_table)
|
||||
.expect("could not get engines");
|
||||
|
||||
let results = runner::run_engines(engine_vec, "test".to_string()).await;
|
||||
|
||||
println!("{:#?}", results)
|
||||
}
|
||||
41
src/runner.rs
Normal file
41
src/runner.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use crate::engine_decoder::Engine;
|
||||
use futures::future::try_join_all;
|
||||
use mlua::{Table, Value};
|
||||
|
||||
pub async fn run_engines(
|
||||
engines: Vec<Engine>,
|
||||
query: String,
|
||||
) -> mlua::Result<Vec<(String, Value)>> {
|
||||
let engine_futures = engines.into_iter().map(|engine| {
|
||||
let value = query.clone();
|
||||
async move {
|
||||
let results: Table = engine.grabber.call_async(value).await?;
|
||||
|
||||
let items: Vec<Value> = results
|
||||
.sequence_values::<Value>()
|
||||
.collect::<Result<Vec<Value>, mlua::Error>>()?;
|
||||
|
||||
let builder = engine.builder;
|
||||
let engine_name = engine.name;
|
||||
|
||||
let builder_futures = items.into_iter().map(|item| {
|
||||
let builder = builder.clone();
|
||||
let engine_name = engine_name.clone();
|
||||
|
||||
async move {
|
||||
let result: Value = builder.call_async((item, "test")).await?;
|
||||
|
||||
Ok::<_, mlua::Error>((engine_name, result))
|
||||
}
|
||||
});
|
||||
|
||||
try_join_all(builder_futures).await
|
||||
}
|
||||
});
|
||||
|
||||
let results: Vec<Vec<(String, Value)>> = try_join_all(engine_futures).await?;
|
||||
|
||||
let flattened: Vec<(String, Value)> = results.into_iter().flatten().collect();
|
||||
|
||||
Ok(flattened)
|
||||
}
|
||||
Reference in New Issue
Block a user