added async support with tokio, modularised lua and removed the test functions from backend
This commit is contained in:
@@ -1,50 +0,0 @@
|
||||
let SessionLoad = 1
|
||||
let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
|
||||
let v:this_session=expand("<sfile>:p")
|
||||
doautoall SessionLoadPre
|
||||
silent only
|
||||
silent tabonly
|
||||
cd ~/Projects/search-engine/frontend
|
||||
if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
|
||||
let s:wipebuf = bufnr('%')
|
||||
endif
|
||||
let s:shortmess_save = &shortmess
|
||||
set shortmess+=aoO
|
||||
badd +7 Cargo.toml
|
||||
argglobal
|
||||
%argdel
|
||||
$argadd Cargo.toml
|
||||
edit Cargo.toml
|
||||
argglobal
|
||||
setlocal foldmethod=manual
|
||||
setlocal foldexpr=0
|
||||
setlocal foldmarker={{{,}}}
|
||||
setlocal foldignore=#
|
||||
setlocal foldlevel=0
|
||||
setlocal foldminlines=1
|
||||
setlocal foldnestmax=20
|
||||
setlocal foldenable
|
||||
silent! normal! zE
|
||||
let &fdl = &fdl
|
||||
let s:l = 7 - ((6 * winheight(0) + 22) / 44)
|
||||
if s:l < 1 | let s:l = 1 | endif
|
||||
keepjumps exe s:l
|
||||
normal! zt
|
||||
keepjumps 7
|
||||
normal! 032|
|
||||
tabnext 1
|
||||
if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
|
||||
silent exe 'bwipe ' . s:wipebuf
|
||||
endif
|
||||
unlet! s:wipebuf
|
||||
set winheight=1 winwidth=20
|
||||
let &shortmess = s:shortmess_save
|
||||
let s:sx = expand("<sfile>:p:r")."x.vim"
|
||||
if filereadable(s:sx)
|
||||
exe "source " . fnameescape(s:sx)
|
||||
endif
|
||||
let &g:so = s:so_save | let &g:siso = s:siso_save
|
||||
nohlsearch
|
||||
doautoall SessionLoadPost
|
||||
unlet SessionLoad
|
||||
" vim: set ft=vim :
|
||||
@@ -5,4 +5,5 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
backend = {path = "../backend/"}
|
||||
mlua = { version = "0.12.2", features = ["lua54", "vendored"] }
|
||||
mlua = { version = "0.12.2", features = ["lua54", "async", "vendored"] }
|
||||
tokio = { version = "1.54.1", features = ["full"] }
|
||||
|
||||
121
frontend/src/lua/luahtml.rs
Normal file
121
frontend/src/lua/luahtml.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use 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)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,127 +1,11 @@
|
||||
extern crate backend;
|
||||
use backend::scraper;
|
||||
use mlua::{Lua, Table, UserData, UserDataMethods};
|
||||
use std::collections::HashMap;
|
||||
use mlua::{Lua, Table};
|
||||
use std::fs;
|
||||
|
||||
struct LuaHtml {
|
||||
document: scraper::Html,
|
||||
}
|
||||
mod luahtml;
|
||||
use luahtml::LuaHtml;
|
||||
|
||||
impl UserData for LuaHtml {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_meta_method(mlua::MetaMethod::ToString, |_, this, ()| {
|
||||
Ok(this.document.root_element().html())
|
||||
});
|
||||
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)
|
||||
});
|
||||
|
||||
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?;
|
||||
|
||||
// The source field is configuration metadata, not a selector.
|
||||
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)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct DataSelector {
|
||||
title: String,
|
||||
snippet: String,
|
||||
url: String,
|
||||
}
|
||||
mod engine_decoder;
|
||||
|
||||
pub fn create_instance() -> mlua::Lua {
|
||||
mlua::Lua::new()
|
||||
@@ -146,10 +30,18 @@ pub fn intialise_lua(instance: &mut mlua::Lua, path: Option<String>) -> mlua::Re
|
||||
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(
|
||||
"fetchUrl",
|
||||
lua.create_function(|_, url: String| {
|
||||
let scraped_data = backend::scrape_url(&url);
|
||||
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)
|
||||
})?,
|
||||
)?;
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::{env, process};
|
||||
|
||||
fn main() {
|
||||
let mut args = env::args();
|
||||
let bin = args.next();
|
||||
let _bin = args.next();
|
||||
// let something = return_results_vec();
|
||||
|
||||
let mut config_location: Option<String> = None;
|
||||
@@ -42,6 +42,7 @@ fn main() {
|
||||
.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>() {
|
||||
|
||||
Reference in New Issue
Block a user