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>(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::() { 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::>() .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) }); } }