lodestone-parser/src/logic.rs

85 lines
2.0 KiB
Rust
Raw Normal View History

2018-09-03 20:40:30 +00:00
use crate::{
error::*,
models::{
GrandCompany,
character::GrandCompanyInfo,
},
};
2018-09-03 20:40:30 +00:00
use scraper::{
Html,
2018-09-03 23:27:34 +00:00
ElementRef,
2018-09-03 20:40:30 +00:00
node::Element,
};
2018-09-02 19:12:52 +00:00
macro_rules! selectors {
($($name:ident => $selector:expr);+$(;)?) => {
use lazy_static::lazy_static;
2018-09-02 19:12:52 +00:00
lazy_static! {
$(
static ref $name: scraper::Selector = scraper::Selector::parse($selector).unwrap();
)+
}
}
}
pub mod character;
pub mod free_company;
2018-10-28 21:29:54 +00:00
pub mod linkshell;
2018-09-03 20:40:30 +00:00
pub mod search;
2018-09-04 18:44:23 +00:00
pub use self::{
character::parse as parse_character,
free_company::parse as parse_free_company,
2018-10-28 21:31:51 +00:00
linkshell::parse as parse_linkshell,
2018-09-04 18:44:23 +00:00
search::*,
};
2022-06-16 14:10:03 +00:00
pub(crate) fn plain_parse(html: &Html, select: &scraper::Selector) -> Result<String> {
let string = html
2018-09-03 23:27:34 +00:00
.select(select)
.next()
.ok_or_else(|| Error::missing_element(select))?
2018-09-03 23:27:34 +00:00
.text()
.collect();
Ok(string)
}
2022-06-16 14:10:03 +00:00
pub(crate) fn plain_parse_elem<'a>(html: ElementRef<'a>, select: &scraper::Selector) -> Result<String> {
2018-09-03 23:27:34 +00:00
let string = html
.select(select)
.next()
.ok_or_else(|| Error::missing_element(select))?
.text()
.collect();
Ok(string)
}
2018-09-03 20:40:30 +00:00
2022-06-16 14:10:03 +00:00
pub(crate) fn parse_id(a: &Element) -> Result<u64> {
2018-09-03 20:40:30 +00:00
let href = a.attr("href").ok_or_else(|| Error::invalid_content("href on link", None))?;
let last = href
.split('/')
.filter(|x| !x.is_empty())
.last()
.ok_or_else(|| Error::invalid_content("href separated by `/`", Some(&href)))?;
last.parse().map_err(Error::InvalidNumber)
}
2022-06-16 14:10:03 +00:00
pub(crate) fn parse_grand_company(text: &str) -> Result<GrandCompanyInfo> {
2018-09-03 20:40:30 +00:00
let mut x = text.split(" / ");
let gc_str = x
.next()
.ok_or_else(|| Error::invalid_content("gc/rank separated by `/`", Some(&text)))?;
let name = GrandCompany::parse(gc_str)
2018-09-03 20:40:30 +00:00
.ok_or_else(|| Error::invalid_content("valid grand company", Some(&text)))?;
let rank = x
.next()
.ok_or_else(|| Error::invalid_content("gc/rank separated by `/`", Some(&text)))?
.to_string();
Ok(GrandCompanyInfo {
name,
2018-09-03 20:40:30 +00:00
rank,
})
}