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
use {
    crate::{
        converter,
        models::{Chapter, Details, Language, Rating, State, Story},
        select,
        utils::{req, sleep, word_count},
        Error, ScrapeError, Uri,
    },
    chrono::{DateTime, NaiveDate, Utc},
    html5ever::{
        driver::{self, ParseOpts},
        tendril::stream::TendrilSink,
    },
    scraper::{Html, Selector},
};

lazy_static::lazy_static! {
    static ref CHAPTER_NAME: Selector = Selector::parse(r#"#chapters > .chapter > div[role="complementary"] > h3"#,).unwrap();
    static ref CHAPTER_TEXT: Selector = Selector::parse(r#"#chapters > .chapter > div[role="article"] > p"#).unwrap();

    static ref STORY_AUTHOR: Selector = Selector::parse(r#"#workskin > .preface > .byline.heading > a[rel="author"]"#).unwrap();
    static ref STORY_SUMMARY: Selector = Selector::parse("#workskin > .preface > .summary > blockquote > p").unwrap();
    static ref STORY_NAME: Selector = Selector::parse("#workskin > .preface > .title").unwrap();

    static ref STORY_RATING: Selector = Selector::parse(".work > .rating.tags > ul > li > .tag").unwrap();
    static ref STORY_ORIGINS: Selector = Selector::parse(".work > .fandom.tags > ul > li > .tag").unwrap();

    static ref STORY_STATS_CHAPTERS: Selector = Selector::parse("dl.work > dd.stats > dl.stats > dd.chapters").unwrap();
    static ref STORY_STATS_LANGUAGE: Selector = Selector::parse("dl.work > dd.language").unwrap();
    static ref STORY_STATS_CREATED: Selector = Selector::parse("dl.work > dd.stats > dl.stats > dd.published").unwrap();
    static ref STORY_STATS_UPDATED: Selector = Selector::parse("dl.work > dd.stats > dl.stats > dd.status").unwrap();

    static ref STORY_ACTIONS: Selector = Selector::parse("#feedback > .actions > li > a").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);

    let first = url
        .path()
        .split('/')
        .filter(|s| !s.is_empty())
        .nth(3)
        .and_then(|id_hash| id_hash.split('#').next().map(String::from))
        .expect("No story ID found in URL");

    if chapters != 1 {
        let mut next = Some(first);

        for num in 1..=chapters {
            if let Some(ch) = next {
                log::info!("[{}] Scraping chapter {} [{}]", url, num, ch);

                sleep().await?;

                let uri = format!("https://archiveofourown.org/works/{}/chapters/{}", id, &ch)
                    .parse::<Uri>()?;

                let body = req(&uri).await?;

                let (n, chapter) = tokio::task::spawn_blocking(|| get_chapter(body))
                    .await
                    .expect("Thread pool closed")?;

                next = n;

                story.chapters.push(chapter);
            } else {
                log::error!("[error] The scraper is trying to access a chapter that doesn't exist, this isn't good");
            }
        }
    } else {
        log::info!("[{}] Scraping chapter 1 [{}]", url, first);

        sleep().await?;

        let uri = format!(
            "https://archiveofourown.org/works/{}/chapters/{}",
            id, &first
        )
        .parse::<Uri>()?;

        let body = req(&uri).await?;

        story.chapters.push(
            tokio::task::spawn_blocking(|| get_chapter(body))
                .await
                .expect("Thread pool closed")?
                .1,
        );
    }

    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 authors: Vec<String> = select!(string[] <> html => &STORY_AUTHOR);
    let origins: Vec<String> = select!(string[] <> html => &STORY_ORIGINS);

    let name: String = select!(string <> html => &STORY_NAME).trim().to_string();
    let summary: String = select!(string <> html => &STORY_SUMMARY);

    let chapter_expected: String = select!(string <> html => &STORY_STATS_CHAPTERS);

    let chapters: u32 = chapter_expected
        .split('/')
        .next()
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap();

    let language: Language = match select!(string <> html => &STORY_STATS_LANGUAGE).trim() {
        "English" => Language::English,
        _ => unreachable!(),
    };

    let rating: Rating = match select!(string <> html => &STORY_RATING).trim() {
        "Explicit" => Rating::Explicit,
        "Mature" => Rating::Mature,
        "Teen And Up Audiences" => Rating::Teen,
        "General Audiences" => Rating::General,
        _ => unreachable!(),
    };

    let state = {
        let mut split = chapter_expected.split('/');

        let current: &str = split.next().unwrap();
        let expected: &str = split.next().unwrap();

        if current == expected {
            State::Completed
        } else {
            State::InProgress
        }
    };

    let created: Option<DateTime<Utc>> =
        NaiveDate::parse_from_str(&select!(string <> html => &STORY_STATS_CREATED), "%Y-%m-%d")
            .map(|date| date.and_hms(0, 0, 0))
            .map(|dt| DateTime::from_utc(dt, Utc))
            .ok();

    let updated: Option<DateTime<Utc>> = if state != State::Completed || chapters != 1 {
        NaiveDate::parse_from_str(&select!(string <> html => &STORY_STATS_UPDATED), "%Y-%m-%d")
            .map(|date| date.and_hms(0, 0, 0))
            .map(|dt| DateTime::from_utc(dt, Utc))
            .ok()
    } else {
        None
    };

    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<(Option<String>, Chapter), ScrapeError> {
    let parser = driver::parse_document(Html::new_document(), ParseOpts::default());

    let html = parser.one(body);

    let next: Option<String> = html
        .select(&STORY_ACTIONS)
        .find(node_filter)
        .and_then(|node| {
            node.value().attr("href").and_then(|href| {
                // figure out a way to remove the &str -> String
                href.split('/')
                    .nth(4)
                    .and_then(|id_hash| id_hash.split('#').next().map(String::from))
            })
        });

    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(),
    )?;

    let name: String = select!(string <> html => &CHAPTER_NAME);

    Ok((
        next,
        Chapter {
            name,
            words: word_count(&main),
            pre: String::new(),
            post: String::new(),
            main,
        },
    ))
}

fn node_filter(node: &scraper::element_ref::ElementRef<'_>) -> bool {
    node.value()
        .attr("href")
        .map(|href| href.starts_with("/works/"))
        .unwrap_or_else(|| false)
        && node
            .text()
            .next()
            .map(|text| text == "Next Chapter →")
            .unwrap_or_else(|| false)
}