1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
use { crate::{ converter, models::{Chapter, Details, Language, Rating, State, Story}, select, utils::{req, sleep, word_count}, Error, ScrapeError, Uri, }, chrono::{DateTime, Datelike, NaiveTime, TimeZone, Utc}, html5ever::{ driver::{self, ParseOpts}, tendril::stream::TendrilSink, }, scraper::{Html, Selector}, std::str, }; lazy_static::lazy_static! { static ref CHAPTER_NAME: Selector = Selector::parse("select#chap_select > option[selected]").unwrap(); static ref CHAPTER_TEXT: Selector = Selector::parse("#storytext").unwrap(); static ref STORY_AUTHOR: Selector = Selector::parse("#profile_top > a.xcontrast_txt:not([title])").unwrap(); static ref STORY_DETAILS: Selector = Selector::parse("#profile_top > span.xgray.xcontrast_txt").unwrap(); static ref STORY_SUMMARY: Selector = Selector::parse("#profile_top > div.xcontrast_txt").unwrap(); static ref STORY_NAME: Selector = Selector::parse("#profile_top > b.xcontrast_txt").unwrap(); static ref STORY_ORIGINS: Selector = Selector::parse("#pre_story_links > span.lc-left > a.xcontrast_txt:last-child",).unwrap(); } pub async fn scrape(url: &Uri) -> Result<Story, Error> { let id = url .path() .split('/') .filter(|s| !s.is_empty()) .nth(1) .expect("No story ID found in URL"); log::info!("[{}] Scraping initial details", url); let body = req(&url).await?; let details = tokio::task::spawn_blocking(|| get_details(body)) .await .expect("Thread pool closed")?; let chapters = details.chapters; let mut story = Story::new(details); log::info!("[{}] Beginning chapter scraping", url); if chapters != 1 { for page in 1..=chapters { log::info!("[{}] Scraping chapter {}", url, page); sleep().await?; let url = format!("https://www.fanfiction.net/s/{}/{}", id, page) .as_str() .parse()?; let body = req(&url).await?; story.chapters.push( tokio::task::spawn_blocking(|| get_chapter(body)) .await .expect("Thread pool closed")?, ); } } else { log::info!("[{}] Scraping chapter {}", url, 1); sleep().await?; let url = format!("https://www.fanfiction.net/s/{}/{}", id, 1) .as_str() .parse()?; let body = req(&url).await?; story.chapters.push( tokio::task::spawn_blocking(|| get_chapter(body)) .await .expect("Thread pool closed")?, ); } story.words = story.chapters.iter().map(|c| word_count(&c.main)).sum(); Ok(story) } pub fn get_details(body: String) -> Result<Details, ScrapeError> { let parser = driver::parse_document(Html::new_document(), ParseOpts::default()); let html = parser.one(body); let name: String = select!(string <> html => &STORY_NAME); let summary: String = select!(string <> html => &STORY_SUMMARY); let details: String = select!(string <> html => &STORY_DETAILS); let authors: Vec<String> = select!(string[] <> html => &STORY_AUTHOR); let origins: Vec<String> = select!(string[] <> html => &STORY_ORIGINS); let mut chapters = 1u32; let mut language = Language::English; let mut rating = Rating::Teen; let mut state = State::InProgress; let mut created: Option<DateTime<Utc>> = None; let mut updated: Option<DateTime<Utc>> = None; let words = details.split('-').count(); for (i, s) in details.split('-').map(str::trim).rev().enumerate() { if s.starts_with("Chapters: ") { if let Some(ch) = s .split(':') .map(str::trim) .nth(1) .and_then(|s| s.parse::<u32>().ok()) { chapters = ch; } } if i == words - 2 { language = match s { "English" => Language::English, _ => unreachable!(), }; } if s.starts_with("Rated: ") { if let Some(ra) = s.split(':').map(str::trim).nth(1).and_then(|s| { s.split(' ') .map(str::trim) .filter(|s| !s.is_empty()) .nth(1) .map(|s| match s { "MA" => Rating::Explicit, "M" => Rating::Mature, "T" => Rating::Teen, "K" | "K+" => Rating::General, _ => unreachable!("Unknown rating found, please report this"), }) }) { rating = ra; } } if s.starts_with("Status: ") { if let Some(st) = s.split(':').map(str::trim).nth(1).map(|s| match s { "Complete" => State::Completed, _ => unreachable!(), }) { state = st; } } if s.starts_with("Published: ") { if let Some(cr) = s.split(':').map(str::trim).nth(1).and_then(time) { if updated.is_none() { updated = Some(cr); } created = Some(cr); } } if s.starts_with("Updated: ") { if let Some(cr) = s.split(':').map(str::trim).nth(1).and_then(time) { updated = Some(cr); } } } Ok(Details { name, summary, chapters, language, rating, state, authors, origins, tags: Vec::new(), created: created.unwrap_or_else(Utc::now), updated: updated.unwrap_or_else(Utc::now), }) } pub fn get_chapter(body: String) -> Result<Chapter, ScrapeError> { let parser = driver::parse_document(Html::new_document(), ParseOpts::default()); let html = parser.one(body); let main = converter::parse( html.select(&CHAPTER_TEXT) .next() .expect("[chapter_text] HTML is missing the chapter text node, did the html change?") .inner_html(), )?; Ok(Chapter { name: html .select(&CHAPTER_NAME) .next() .and_then(|cn| cn.text().next()) .map(|cn| cn.split(' ').skip(1).collect::<Vec<_>>().join(" ")) .expect("[chapter_name] No text in selected element"), words: word_count(&main), pre: String::new(), post: String::new(), main, }) } fn time(text: &str) -> Option<DateTime<Utc>> { let mut parts = text.split('/'); parts .next() .and_then(|t| t.parse::<u32>().ok()) .and_then(|m| { parts .next() .and_then(|t| t.parse::<u32>().ok()) .and_then(|d| { let y = parts .next() .and_then(|t| t.parse::<i32>().ok()) .unwrap_or_else(|| Utc::today().year()); Utc.ymd(y, m, d).and_time(NaiveTime::from_hms(0, 0, 0)) }) }) }