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
pub mod archive_of_our_own;
pub mod fanfiction;

use {
    crate::{
        models::{Chapter, Details},
        utils::req,
        Error, Uri,
    },
    std::{fmt, sync::Arc},
};

#[macro_export]
macro_rules! select {
    (inner_html <> $site:expr; $html:expr => $selector:expr) => {
        $html
            .select($selector)
            .first()
            .and_then(|sd| sd.inner_html())
            .ok_or(crate::error::ScrapeError::ElementNotFound($site, $selector))
    };
    (string <> $site:expr; $html:expr => $selector:expr) => {
        $html
            .select($selector)
            .first()
            .and_then(|sd| sd.text())
            .ok_or(crate::error::ScrapeError::ElementNotFound($site, $selector))
    };
    (string[] <> $site:expr; $html:expr => $selector:expr) => {
        $html
            .select($selector)
            .into_iter()
            .map(|ele| ele.text())
            .collect::<Option<Vec<_>>>()
            .ok_or(crate::error::ScrapeError::ElementNotFound($site, $selector))
    };
}

#[derive(Clone, Copy, Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub enum Sites {
    ArchiveOfOurOwn,
    FanFictionNet,
}

impl Sites {
    pub fn url(&self) -> &'static str {
        match self {
            Sites::ArchiveOfOurOwn => "https://archiveofourown.org/",
            Sites::FanFictionNet => "https://fanfiction.net/",
        }
    }
}

impl fmt::Display for Sites {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Sites::ArchiveOfOurOwn => write!(f, "Archive of Our Own"),
            Sites::FanFictionNet => write!(f, "FanFiction.net"),
        }
    }
}

pub struct SiteRef {
    inner: Inner,
}

impl SiteRef {
    pub async fn get_details(&mut self) -> Result<Details, Error> {
        match &mut self.inner {
            Inner::ArchiveOfOurOwn { id, document } => {
                if document.is_none() {
                    let url = format!(
                        "https://archiveofourown.org/works/{}?view_full_work=true",
                        id
                    )
                    .parse::<Uri>()?;

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

                    *document = Some(Arc::new(body));
                }

                let document = document.clone().expect("This should not be `None`");

                let details =
                    tokio::task::spawn_blocking(|| archive_of_our_own::get_details(document))
                        .await
                        .expect("Thread pool closed")?;

                Ok(details)
            }
            Inner::FanFictionNet { id } => {
                let url = format!("https://www.fanfiction.net/s/{}/{}", id, 1).parse::<Uri>()?;

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

                let details = tokio::task::spawn_blocking(|| fanfiction::get_details(body))
                    .await
                    .expect("Thread pool closed")?;

                Ok(details)
            }
        }
    }

    pub async fn get_chapter(&mut self, chapter: u32) -> Result<Chapter, Error> {
        match &mut self.inner {
            Inner::ArchiveOfOurOwn { id, document } => {
                if document.is_none() {
                    let url = format!(
                        "https://archiveofourown.org/works/{}?view_full_work=true",
                        id
                    )
                    .parse::<Uri>()?;

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

                    *document = Some(Arc::new(body));
                }

                todo!()
            }
            Inner::FanFictionNet { id } => {
                let url =
                    format!("https://www.fanfiction.net/s/{}/{}", id, chapter).parse::<Uri>()?;

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

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

                Ok(chapter)
            }
        }
    }
}

enum Inner {
    ArchiveOfOurOwn {
        id: String,
        document: Option<Arc<String>>,
    },
    FanFictionNet {
        id: String,
    },
}

pub trait Site: Copy {
    fn init(self, id: impl Into<String>) -> SiteRef;
}

impl Site for Sites {
    fn init(self, id: impl Into<String>) -> SiteRef {
        match self {
            Sites::ArchiveOfOurOwn => SiteRef {
                inner: Inner::ArchiveOfOurOwn {
                    id: id.into(),
                    document: None,
                },
            },
            Sites::FanFictionNet => SiteRef {
                inner: Inner::FanFictionNet { id: id.into() },
            },
        }
    }
}