lodestone-scraper/src/lib.rs

89 lines
2.1 KiB
Rust
Raw Normal View History

2022-06-16 14:12:13 +00:00
pub extern crate lodestone_parser;
2018-09-04 20:13:11 +00:00
use lazy_static::lazy_static;
use lodestone_parser::models::{
character::Character,
free_company::FreeCompany,
};
2018-09-05 04:57:02 +00:00
use reqwest::{Client, StatusCode};
2018-09-04 20:13:11 +00:00
use url::Url;
use std::str::FromStr;
pub mod builder;
pub mod error;
pub mod models;
2022-06-16 14:12:13 +00:00
pub(crate) mod util;
2018-09-04 20:13:11 +00:00
use crate::error::*;
#[derive(Debug)]
pub struct LodestoneScraper {
client: Client,
}
impl Default for LodestoneScraper {
fn default() -> Self {
let client = Client::new();
LodestoneScraper { client }
}
}
lazy_static! {
static ref LODESTONE_URL: Url = Url::from_str("https://na.finalfantasyxiv.com/lodestone/").unwrap();
}
impl LodestoneScraper {
fn route(s: &str) -> Result<Url> {
LODESTONE_URL.join(s).map_err(Error::Url)
}
2022-06-16 14:12:13 +00:00
pub(crate) async fn text(&self, url: Url) -> Result<String> {
2020-07-23 18:42:47 +00:00
let res = self.client
2018-09-04 20:13:11 +00:00
.get(url)
.send()
2020-07-23 18:42:47 +00:00
.await
2018-09-04 20:13:11 +00:00
.map_err(Error::Net)?;
2018-09-05 04:57:02 +00:00
match res.status() {
StatusCode::OK => {},
StatusCode::NOT_FOUND => return Err(Error::NotFound),
2018-09-05 04:57:02 +00:00
x => return Err(Error::UnexpectedResponse(x)),
}
res
.text()
2020-07-23 18:42:47 +00:00
.await
2018-09-05 04:57:02 +00:00
.map_err(Error::Net)
}
2020-07-23 18:42:47 +00:00
pub async fn character(&self, id: u64) -> Result<Character> {
2018-09-05 04:57:02 +00:00
let url = LodestoneScraper::route(&format!("character/{}", id))?;
2020-07-23 18:42:47 +00:00
let text = self.text(url).await?;
2018-09-04 20:13:11 +00:00
lodestone_parser::parse_character(id, &text).map_err(Error::Parse)
}
pub fn character_search(&self) -> builder::CharacterSearchBuilder {
builder::CharacterSearchBuilder::new(self)
}
2020-07-23 18:42:47 +00:00
pub async fn free_company(&self, id: u64) -> Result<FreeCompany> {
2018-09-04 20:13:11 +00:00
let url = LodestoneScraper::route(&format!("freecompany/{}", id))?;
2020-07-23 18:42:47 +00:00
let text = self.text(url).await?;
2018-09-04 20:13:11 +00:00
lodestone_parser::parse_free_company(id, &text).map_err(Error::Parse)
}
pub fn free_company_search(&self) -> builder::FreeCompanySearchBuilder {
builder::FreeCompanySearchBuilder::new(self)
}
2018-10-28 21:42:34 +00:00
pub fn linkshell(&self, id: u64) -> builder::LinkshellBuilder {
builder::LinkshellBuilder::new(self, id)
}
pub fn linkshell_search(&self) -> builder::LinkshellSearchBuilder {
builder::LinkshellSearchBuilder::new(self)
}
2018-09-04 20:13:11 +00:00
}