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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use {
    crate::{
        converter,
        models::{Chapter, Details, Language, Rating, State, Story},
        select,
        utils::{request, sleep, word_count, RequestError},
    },
    chrono::{DateTime, NaiveDate, Utc},
    http_req::uri::Uri,
    scraper::{Html, Selector},
};

#[derive(Debug)]
pub enum ArchiveOfOurOwnError {
    Io { err: std::io::Error },
    Utf8 { err: std::str::Utf8Error },

    InvalidEncoding,
    Non200Response,
    Http { err: http::Error },
    HttpReq { err: http_req::error::Error },
}

impl From<RequestError> for ArchiveOfOurOwnError {
    fn from(err: RequestError) -> ArchiveOfOurOwnError {
        match err {
            RequestError::Io { err } => ArchiveOfOurOwnError::Io { err },

            RequestError::InvalidEncoding => ArchiveOfOurOwnError::InvalidEncoding,
            RequestError::Non200Response => ArchiveOfOurOwnError::Non200Response,
            RequestError::Http { err } => ArchiveOfOurOwnError::Http { err },
            RequestError::HttpReq { err } => ArchiveOfOurOwnError::HttpReq { err },
        }
    }
}

impl std::fmt::Display for ArchiveOfOurOwnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ArchiveOfOurOwnError::Io { err } => write!(f, "(Io) {}", err),
            ArchiveOfOurOwnError::Utf8 { err } => write!(f, "(Utf8) {}", err),

            ArchiveOfOurOwnError::InvalidEncoding => write!(
                f,
                "(InvalidEncoding) Server returned with and encoding that the scraper can't handle"
            ),
            ArchiveOfOurOwnError::Non200Response => write!(
                f,
                "(Non200Response) Server returned with a non 200 status code"
            ),
            ArchiveOfOurOwnError::Http { ref err } => write!(f, "(Http) {}", err),
            ArchiveOfOurOwnError::HttpReq { ref err } => write!(f, "(HttpReq) {}", err),
        }
    }
}

impl From<std::io::Error> for ArchiveOfOurOwnError {
    fn from(err: std::io::Error) -> ArchiveOfOurOwnError {
        ArchiveOfOurOwnError::Io { err }
    }
}

impl From<std::str::Utf8Error> for ArchiveOfOurOwnError {
    fn from(err: std::str::Utf8Error) -> ArchiveOfOurOwnError {
        ArchiveOfOurOwnError::Utf8 { err }
    }
}

impl From<http::Error> for ArchiveOfOurOwnError {
    fn from(err: http::Error) -> ArchiveOfOurOwnError {
        ArchiveOfOurOwnError::Http { err }
    }
}

impl From<http_req::error::Error> for ArchiveOfOurOwnError {
    fn from(err: http_req::error::Error) -> ArchiveOfOurOwnError {
        ArchiveOfOurOwnError::HttpReq { err }
    }
}

impl std::error::Error for ArchiveOfOurOwnError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ArchiveOfOurOwnError::Io { ref err } => Some(err),
            ArchiveOfOurOwnError::Utf8 { ref err } => Some(err),

            ArchiveOfOurOwnError::InvalidEncoding => None,
            ArchiveOfOurOwnError::Non200Response => None,
            ArchiveOfOurOwnError::Http { ref err } => Some(err),
            ArchiveOfOurOwnError::HttpReq { ref err } => Some(err),
        }
    }
}

#[derive(Debug)]
pub struct ArchiveOfOurOwn {
    chapter_name: Selector,
    chapter_text: Selector,

    story_author: Selector,
    story_summary: Selector,
    story_name: Selector,

    story_rating: Selector,
    story_origins: Selector,

    story_stats_chapters: Selector,
    story_stats_language: Selector,
    story_stats_created: Selector,
    story_stats_updated: Selector,

    story_actions: Selector,
}

impl ArchiveOfOurOwn {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn scrape(&self, url: &Uri) -> Result<Story, ArchiveOfOurOwnError> {
        let id = url
            .path()
            .and_then(|p| p.split('/').filter(|s| !s.is_empty()).nth(1))
            .expect("No story ID found in URL");

        log::info!("[{}] Scraping initial details", url);

        let details = self.get_details(url)?;

        let chapters = details.chapters;

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

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

        let first = url
            .path()
            .and_then(|p| {
                p.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);

                    let (n, chapter) = self.get_chapter(id, &ch)?;

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

            story.chapters.push(self.get_chapter(id, &first)?.1);
        }

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

        Ok(story)
    }

    pub fn get_details(&self, url: &Uri) -> Result<Details, ArchiveOfOurOwnError> {
        let res = request(url).map_err(ArchiveOfOurOwnError::from)?;

        let html = Html::parse_document(std::str::from_utf8(&res)?);

        let authors: Vec<String> = select!(string[] <> html => &self.story_author);
        let origins: Vec<String> = select!(string[] <> html => &self.story_origins);

        let name: String = select!(string <> html => &self.story_name)
            .trim()
            .to_string();
        let summary: String = select!(string <> html => &self.story_summary);

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

        let rating: Rating = match select!(string <> html => &self.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 => &self.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 => &self.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(
        &self,
        id: &str,
        chapter: &str,
    ) -> Result<(Option<String>, Chapter), ArchiveOfOurOwnError> {
        sleep();

        let url = format!(
            "https://archiveofourown.org/works/{}/chapters/{}",
            id, chapter
        )
        .as_str()
        .parse()?;

        let res = request(&url).map_err(ArchiveOfOurOwnError::from)?;

        let html = Html::parse_document(std::str::from_utf8(&res)?);

        let next: Option<String> = html
            .select(&self.story_actions)
            .find(Self::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(&self.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 => &self.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)
    }
}

impl Default for ArchiveOfOurOwn {
    fn default() -> Self {
        Self {
            chapter_name: Selector::parse(
                r#"#chapters > .chapter > div[role="complementary"] > h3"#,
            )
            .unwrap(),
            chapter_text: Selector::parse(r#"#chapters > .chapter > div[role="article"] > p"#)
                .unwrap(),

            story_author: Selector::parse(
                r#"#workskin > .preface > .byline.heading > a[rel="author"]"#,
            )
            .unwrap(),
            story_summary: Selector::parse("#workskin > .preface > .summary > blockquote > p")
                .unwrap(),
            story_name: Selector::parse("#workskin > .preface > .title").unwrap(),

            story_rating: Selector::parse(".work > .rating.tags > ul > li > .tag").unwrap(),
            story_origins: Selector::parse(".work > .fandom.tags > ul > li > .tag").unwrap(),

            story_stats_chapters: Selector::parse("dl.work > dd.stats > dl.stats > dd.chapters")
                .unwrap(),
            story_stats_language: Selector::parse("dl.work > dd.language").unwrap(),
            story_stats_created: Selector::parse("dl.work > dd.stats > dl.stats > dd.published")
                .unwrap(),
            story_stats_updated: Selector::parse("dl.work > dd.stats > dl.stats > dd.status")
                .unwrap(),

            story_actions: Selector::parse("#feedback > .actions > li > a").unwrap(),
        }
    }
}