added async support with tokio, modularised lua and removed the test functions from backend
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -14,3 +14,4 @@ devenv.local.yaml
|
|||||||
|
|
||||||
/target
|
/target
|
||||||
/.session
|
/.session
|
||||||
|
/frontend/.session
|
||||||
|
|||||||
109
Cargo.lock
generated
109
Cargo.lock
generated
@@ -32,6 +32,12 @@ dependencies = [
|
|||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes"
|
||||||
|
version = "1.12.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.11.2"
|
version = "1.11.2"
|
||||||
@@ -149,6 +155,16 @@ version = "1.19.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "errno"
|
||||||
|
version = "0.3.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
@@ -167,6 +183,31 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"backend",
|
"backend",
|
||||||
"mlua",
|
"mlua",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-core"
|
||||||
|
version = "0.3.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-task"
|
||||||
|
version = "0.3.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-util"
|
||||||
|
version = "0.3.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||||
|
dependencies = [
|
||||||
|
"futures-core",
|
||||||
|
"futures-task",
|
||||||
|
"pin-project-lite",
|
||||||
|
"slab",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -264,6 +305,17 @@ version = "2.8.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mio"
|
||||||
|
version = "1.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"wasi",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mlua"
|
name = "mlua"
|
||||||
version = "0.12.2"
|
version = "0.12.2"
|
||||||
@@ -272,6 +324,7 @@ checksum = "7a7ae6b65bf54b7fdd4cf5b6f44f60862350ebf3fe3779b3a9cc005e7fa14f81"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"bstr",
|
"bstr",
|
||||||
"either",
|
"either",
|
||||||
|
"futures-util",
|
||||||
"libc",
|
"libc",
|
||||||
"mlua-sys",
|
"mlua-sys",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
@@ -402,6 +455,12 @@ dependencies = [
|
|||||||
"siphasher",
|
"siphasher",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pin-project-lite"
|
||||||
|
version = "0.2.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkg-config"
|
name = "pkg-config"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@@ -552,12 +611,28 @@ version = "2.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook-registry"
|
||||||
|
version = "1.4.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||||
|
dependencies = [
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "siphasher"
|
name = "siphasher"
|
||||||
version = "1.0.4"
|
version = "1.0.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "slab"
|
||||||
|
version = "0.4.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "smallvec"
|
name = "smallvec"
|
||||||
version = "1.16.5"
|
version = "1.16.5"
|
||||||
@@ -635,6 +710,34 @@ dependencies = [
|
|||||||
"new_debug_unreachable",
|
"new_debug_unreachable",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio"
|
||||||
|
version = "1.54.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"libc",
|
||||||
|
"mio",
|
||||||
|
"parking_lot",
|
||||||
|
"pin-project-lite",
|
||||||
|
"signal-hook-registry",
|
||||||
|
"socket2",
|
||||||
|
"tokio-macros",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-macros"
|
||||||
|
version = "2.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -653,6 +756,12 @@ version = "0.2.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "web_atoms"
|
name = "web_atoms"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use curl::easy::Easy;
|
use curl::easy::Easy;
|
||||||
pub use scraper;
|
pub use scraper;
|
||||||
use scraper::{ElementRef, Html, Selector};
|
use scraper::Html;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct SearchResult {
|
pub struct SearchResult {
|
||||||
@@ -15,84 +15,27 @@ pub struct SiteHtmlFilter {
|
|||||||
pub url_selector: String,
|
pub url_selector: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn return_results_vec() -> Vec<SearchResult> {
|
|
||||||
let url = "https://lite.duckduckgo.com/lite?q=test";
|
|
||||||
|
|
||||||
let returned_html = scrape_url(url);
|
|
||||||
|
|
||||||
let html_tree = get_sanitised_html_graph(&returned_html);
|
|
||||||
|
|
||||||
let ddg: SiteHtmlFilter = SiteHtmlFilter {
|
|
||||||
title_selector: "tbody tr td a.result-link".to_string(),
|
|
||||||
snippet_selector: "tbody tr td.result-snippet".to_string(),
|
|
||||||
url_selector: "tbody tr td a.result-link".to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let filtered_results = filter_html(&html_tree, &ddg);
|
|
||||||
|
|
||||||
println!("{:#?}", filtered_results);
|
|
||||||
|
|
||||||
return filtered_results;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn filter_html(html_tree: &Html, filter_set: &SiteHtmlFilter) -> Vec<SearchResult> {
|
|
||||||
let mut found_results: Vec<SearchResult> = Vec::new();
|
|
||||||
|
|
||||||
let title_selector = Selector::parse(&filter_set.title_selector).unwrap();
|
|
||||||
let snippet_selector = Selector::parse(&filter_set.snippet_selector).unwrap();
|
|
||||||
let url_selector = Selector::parse(&filter_set.url_selector).unwrap();
|
|
||||||
|
|
||||||
let titles: Vec<_> = html_tree.select(&title_selector).collect();
|
|
||||||
let snippets: Vec<_> = html_tree.select(&snippet_selector).collect();
|
|
||||||
let urls: Vec<_> = html_tree.select(&url_selector).collect();
|
|
||||||
|
|
||||||
for (index, title) in titles.iter().enumerate() {
|
|
||||||
let element_to_string =
|
|
||||||
|element: ElementRef<'_>| -> String { element.text().collect::<Vec<_>>().join(" ") };
|
|
||||||
|
|
||||||
let snippet = snippets
|
|
||||||
.get(index)
|
|
||||||
.map(|element| element_to_string(*element))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let link = urls
|
|
||||||
.get(index)
|
|
||||||
.and_then(|element| element.value().attr("href"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let new_result = SearchResult {
|
|
||||||
title: element_to_string(*title),
|
|
||||||
snippet,
|
|
||||||
link,
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("{:#?}", new_result);
|
|
||||||
|
|
||||||
found_results.push(new_result);
|
|
||||||
}
|
|
||||||
|
|
||||||
found_results
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_sanitised_html_graph(plaintext: &str) -> Html {
|
pub fn get_sanitised_html_graph(plaintext: &str) -> Html {
|
||||||
let tree = Html::parse_document(plaintext);
|
let tree = Html::parse_document(plaintext);
|
||||||
return tree;
|
return tree;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scrape_url(url: &str) -> String {
|
pub fn scrape_url_blocking(url: &str) -> String {
|
||||||
let mut data = Vec::new();
|
let mut data = Vec::new();
|
||||||
|
|
||||||
let mut handle = Easy::new();
|
let mut handle = Easy::new();
|
||||||
handle.url(url).unwrap();
|
handle.url(url).unwrap();
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut transfer = handle.transfer();
|
let mut transfer = handle.transfer();
|
||||||
|
|
||||||
transfer
|
transfer
|
||||||
.write_function(|new_data| {
|
.write_function(|new_data| {
|
||||||
data.extend_from_slice(new_data);
|
data.extend_from_slice(new_data);
|
||||||
Ok(new_data.len())
|
Ok(new_data.len())
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
transfer.perform().unwrap();
|
transfer.perform().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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]
|
[dependencies]
|
||||||
backend = {path = "../backend/"}
|
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;
|
extern crate backend;
|
||||||
use backend::scraper;
|
use mlua::{Lua, Table};
|
||||||
use mlua::{Lua, Table, UserData, UserDataMethods};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
struct LuaHtml {
|
mod luahtml;
|
||||||
document: scraper::Html,
|
use luahtml::LuaHtml;
|
||||||
}
|
|
||||||
|
|
||||||
impl UserData for LuaHtml {
|
mod engine_decoder;
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_instance() -> mlua::Lua {
|
pub fn create_instance() -> mlua::Lua {
|
||||||
mlua::Lua::new()
|
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> {
|
fn create_lua_function_table(lua: &Lua) -> mlua::Result<Table> {
|
||||||
let idx_table = lua.create_table()?;
|
let idx_table = lua.create_table()?;
|
||||||
|
|
||||||
|
lua.globals().set(
|
||||||
|
"DefaultBuilder",
|
||||||
|
"function (values) return '<p>'..values.title..'</p>'",
|
||||||
|
)?;
|
||||||
|
|
||||||
idx_table.set(
|
idx_table.set(
|
||||||
"fetchUrl",
|
"fetchUrl",
|
||||||
lua.create_function(|_, url: String| {
|
lua.create_async_function(|_, url: String| async move {
|
||||||
let scraped_data = backend::scrape_url(&url);
|
let scraped_data =
|
||||||
|
tokio::task::spawn_blocking(move || backend::scrape_url_blocking(&url))
|
||||||
|
.await
|
||||||
|
.map_err(mlua::Error::external)?;
|
||||||
Ok(scraped_data)
|
Ok(scraped_data)
|
||||||
})?,
|
})?,
|
||||||
)?;
|
)?;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use std::{env, process};
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut args = env::args();
|
let mut args = env::args();
|
||||||
let bin = args.next();
|
let _bin = args.next();
|
||||||
// let something = return_results_vec();
|
// let something = return_results_vec();
|
||||||
|
|
||||||
let mut config_location: Option<String> = None;
|
let mut config_location: Option<String> = None;
|
||||||
@@ -42,6 +42,7 @@ fn main() {
|
|||||||
.expect("Could Not Unwrap DefaultBuilder");
|
.expect("Could Not Unwrap DefaultBuilder");
|
||||||
|
|
||||||
match functions {
|
match functions {
|
||||||
|
// If only grabber is supplied
|
||||||
mlua::Value::Function(function) => grabber_function = Some(function),
|
mlua::Value::Function(function) => grabber_function = Some(function),
|
||||||
mlua::Value::Table(table) => {
|
mlua::Value::Table(table) => {
|
||||||
for inner_pair in table.pairs::<String, mlua::Function>() {
|
for inner_pair in table.pairs::<String, mlua::Function>() {
|
||||||
|
|||||||
Reference in New Issue
Block a user