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
use {
    crate::{
        converter,
        models::{Chapter, Details, Language, Rating, State, Story},
        query::{Document, Element},
        select,
        utils::{req, word_count},
        Error, ScrapeError, Uri,
    },
    chrono::{DateTime, NaiveDate, Utc},
    std::{fmt::Write, sync::Arc},
};

const NAME: &str = "archive of our own";

const MULTIPLE_CHAPTER_NAME: &str = r#"#chapters > .chapter > div[role="complementary"] > h3"#;
const SINGLE_CHAPTER_NAME: &str = r#"#workskin > .preface > .title"#;
const CHAPTER_SINGLE: &str = r#"#chapters .userstuff > p"#;
const CHAPTER_MULTI_START: &str = r#"#chapters > #chapter-"#;
const CHAPTER_MULTI_END: &str = r#" .userstuff > p"#;

const STORY_AUTHOR: &str = r#"#workskin > .preface > .byline.heading > a[rel="author"]"#;
const STORY_SUMMARY: &str = "#workskin > .preface > .summary > blockquote";
const STORY_NAME: &str = "#workskin > .preface > .title";

const STORY_RATING: &str = ".work > .rating.tags > ul > li > .tag";
const STORY_ORIGINS: &str = ".work > .fandom.tags > ul > li > .tag";

const STORY_STATS_CHAPTERS: &str = "dl.work > dd.stats > dl.stats > dd.chapters";
const STORY_STATS_LANGUAGE: &str = "dl.work > dd.language";
const STORY_STATS_CREATED: &str = "dl.work > dd.stats > dl.stats > dd.published";
const STORY_STATS_UPDATED: &str = "dl.work > dd.stats > dl.stats > dd.status";

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 url = format!(
        "https://archiveofourown.org/works/{}?view_full_work=true",
        id
    )
    .parse::<Uri>()?;

    let body = req(&url).await?;
    let html = Arc::new(body);

    let details = tokio::task::spawn_blocking({
        let html = html.clone();
        || get_details(html)
    })
    .await
    .expect("Thread pool closed")?;

    let chapters = details.chapters;

    let mut story = Story::new(details);

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

    for chapter_number in 1..=chapters {
        let chapter = tokio::task::spawn_blocking({
            let html = html.clone();

            move || get_chapter(html, chapter_number)
        })
        .await
        .expect("Thread pool closed")?;

        story.chapters.push(chapter);
    }

    story.words = story.chapters.iter().map(|c| word_count(&c.main)).sum();

    Ok(story)
}

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

    let authors: Vec<String> = select!(string[] <> NAME; html => STORY_AUTHOR)?;
    let origins: Vec<String> = select!(string[] <> NAME; html => STORY_ORIGINS)?;

    let name: String = select!(string <> NAME; html => STORY_NAME)?
        .trim()
        .to_string();
    let summary: String = converter::parse(select!(inner_html <> NAME; html => STORY_SUMMARY)?)?;

    let chapter_expected: String = select!(string <> NAME; 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 <> NAME; html => STORY_STATS_LANGUAGE)?.trim() {
        "English" => Language::English,
        _ => unreachable!(),
    };

    let rating: Rating = match select!(string <> NAME; 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 <> NAME; 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 <> NAME; html => STORY_STATS_UPDATED)?,
            "%Y-%m-%d",
        )
        .map(|date| date.and_hms(0, 0, 0))
        .map(|dt| DateTime::from_utc(dt, Utc))
        .ok()
    } else if created.is_some() {
        created
    } else {
        None
    };

    Ok(Details {
        name,
        summary,

        chapters,
        language,
        rating,
        state,

        authors,
        origins,
        tags: Vec::new(),

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

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

    let multi = html.select(format!("{}{}{}", CHAPTER_MULTI_START, chapter, CHAPTER_MULTI_END));

    let elements: Vec<Element> = if multi.is_empty() {
        html.select(CHAPTER_SINGLE)
    } else {
        multi
    };

    let content = converter::parse(
        elements
            .into_iter()
            .map(|n| n.html())
            .fold(Some(String::new()), |mut buffer, html| {
                if let Some(mut buff) = buffer.take() {
                    if let Some(raw) = html {
                        write!(buff, "{}", raw).unwrap();

                        buffer = Some(buff);
                    }
                }

                buffer
            })
            .expect("[chapter_text] HTML is missing the chapter text node, did the html change?"),
    )?
    .trim()
    .replace('“', "\"")
    .replace('”', "\"");

    let name: String = select!(string <> NAME; html => MULTIPLE_CHAPTER_NAME)
        .or_else(|_| select!(string <> NAME; html => SINGLE_CHAPTER_NAME))
        .map(|title| {
            let mut title = title.trim().to_string();

            if title.starts_with(':') {
                title.remove(0);

                title.trim().to_string()
            } else {
                title
            }
        })?;

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