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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
use {
    crate::{
        converter,
        models::{Chapter, Details, Language, Rating, State, Story},
        query::Document,
        select,
        utils::{req, sleep, word_count},
        Error, ScrapeError, Uri,
    },
    chrono::{TimeZone, Utc},
    std::str,
};

const NAME: &str = "fanfiction";

const CHAPTER_NAME: &str = "select#chap_select > option[selected]";
const CHAPTER_TEXT: &str = "#storytext";

const STORY_AUTHOR: &str = "#profile_top > a.xcontrast_txt";
const STORY_DETAILS: &str = "#profile_top > span.xgray.xcontrast_txt";
const STORY_DETAILS_RATING: &str =
    r#"#profile_top > span.xgray.xcontrast_txt > a[target="rating"]"#;
const STORY_DETAILS_DATES: &str = "#profile_top > span.xgray.xcontrast_txt > span[data-xutime]";
const STORY_SUMMARY: &str = "#profile_top > div.xcontrast_txt";
const STORY_NAME: &str = "#profile_top > b.xcontrast_txt";
const STORY_ORIGINS: &str = "#pre_story_links > span.lc-left > a.xcontrast_txt";

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");

    tracing::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);

    tracing::info!("[{}] Beginning chapter scraping", url);

    if chapters != 1 {
        for page in 1..=chapters {
            tracing::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 {
        tracing::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: impl Into<Document>) -> Result<Details, ScrapeError> {
    let html = body.into();

    let name: String = select!(string <> NAME; html => STORY_NAME)?;
    let summary: String = select!(string <> NAME; html => STORY_SUMMARY)?;
    let details: String = select!(string <> NAME; html => STORY_DETAILS)?;

    let author: String = html
        .select(STORY_AUTHOR)
        .into_iter()
        .next()
        .map(|ele| ele.text())
        .flatten()
        .ok_or(crate::error::ScrapeError::ElementNotFound(
            NAME,
            &STORY_AUTHOR,
        ))?;

    let origins: Vec<String> = html
        .select(STORY_ORIGINS)
        .into_iter()
        .last()
        .map(|ele| {
            ele.text()
                .map(|mut text| {
                    if text.ends_with("Crossover") {
                        let len = text.len();
                        let new_len = len.saturating_sub("Crossover".len());

                        text.truncate(new_len);
                    }

                    text
                })
                .map(|text| {
                    text.split(" + ")
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .map(String::from)
                        .collect::<Vec<String>>()
                })
        })
        .flatten()
        .ok_or(crate::error::ScrapeError::ElementNotFound(
            NAME,
            &STORY_ORIGINS,
        ))?;

    let mut chapters = 1u32;
    let mut language = Language::English;
    let rating = match select!(string <> NAME; html => STORY_DETAILS_RATING)?
        .as_str()
        .split(' ')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .nth(1)
    {
        Some("MA") => Rating::Explicit,
        Some("M") => Rating::Mature,
        Some("T") => Rating::Teen,
        Some("K") | Some("K+") => Rating::General,
        rating => unreachable!("Unknown rating found, please report this: {:?}", rating),
    };
    let mut state = State::InProgress;

    let (created, mut updated) = match html.select(STORY_DETAILS_DATES).as_slice() {
        [first] => {
            let published = first
                .attr("data-xutime")
                .ok_or_else(|| ScrapeError::AttributeNotFound(NAME, "data-xutime"))?;

            (Utc.datetime_from_str(&published, "%s").ok(), None)
        }
        [first, second] => {
            let updated = first
                .attr("data-xutime")
                .ok_or_else(|| ScrapeError::AttributeNotFound(NAME, "data-xutime"))?;
            let published = second
                .attr("data-xutime")
                .ok_or_else(|| ScrapeError::AttributeNotFound(NAME, "data-xutime"))?;

            (
                Utc.datetime_from_str(&published, "%s").ok(),
                Utc.datetime_from_str(&updated, "%s").ok(),
            )
        }
        _ => {
            return Err(ScrapeError::UnparsableDate(NAME));
        }
    };

    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("Status: ") {
            if let Some(st) = s.split(':').map(str::trim).nth(1).map(|s| match s {
                "Complete" => State::Completed,
                _ => unreachable!(),
            }) {
                state = st;
            }
        }
    }

    if updated.is_none() && created.is_some() {
        updated = created;
    }

    Ok(Details {
        name,
        summary,

        chapters,
        language,
        rating,
        state,

        authors: vec![author],
        origins,
        tags: Vec::new(),

        created: created.ok_or_else(|| ScrapeError::UnparsableDate(NAME))?,
        updated: updated.ok_or_else(|| ScrapeError::UnparsableDate(NAME))?,
    })
}

pub fn get_chapter(body: impl Into<Document>) -> Result<Chapter, ScrapeError> {
    let html = body.into();

    let mut main = converter::parse(
        html.select(CHAPTER_TEXT)
            .first()
            .and_then(|node| node.inner_html())
            .expect("[chapter_text] HTML is missing the chapter text node, did the html change?"),
    )?;

    while main.ends_with(' ') {
        let len = main.len();
        let new_len = len.saturating_sub(" ".len());

        main.truncate(new_len);
    }

    Ok(Chapter {
        name: html
            .select(CHAPTER_NAME)
            .first()
            .and_then(|cn| cn.text())
            .map(|cn| cn.split(' ').skip(1).collect::<Vec<_>>().join(" "))
            .or_else(|| {
                Some(
                    select!(string <> NAME; html => STORY_NAME).expect(
                        "[chapter_name] Unable to use story title as fallback chapter title",
                    ),
                )
            })
            .expect("[chapter_name] No text in selected element"),
        words: word_count(&main),
        pre: String::new(),
        post: String::new(),
        main,
    })
}