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
use clap::Parser;
use serde::{Deserialize, Serialize};
use std::time::Instant;
use url::Url;

use super::crawlers::default_crawlers;
use super::*;

pub enum Next {
    Finished,
    NextPage(Url),
}

#[async_trait::async_trait]
pub trait Crawler: Send + Sync {
    async fn next(&self, _feed_page: FetchedFeedPage) -> anyhow::Result<Next> {
        Ok(Next::Finished)
    }
    fn domains(&self) -> Vec<String> {
        vec![]
    }
}

#[derive(Parser, Debug)]
pub struct FetchOpts {
    /// Feed URL
    url: Url,
    /// Force update
    #[clap(short, long)]
    update: bool,
}

#[derive(Parser, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CrawlOpts {
    /// Feed URL to ingest
    url: Url,
    /// Crawl a paginated feed recursively.
    #[clap(short, long)]
    crawl: bool,

    /// Stop on first existing post.
    #[clap(long)]
    update: bool,

    /// Max number of pages to crawl.
    #[clap(long)]
    max_pages: Option<usize>,
}

impl CrawlOpts {
    pub fn new(url: Url) -> Self {
        Self {
            url,
            crawl: true,
            max_pages: None,
            update: false,
        }
    }

    pub fn crawl(url: Url, max_pages: Option<usize>, update: bool) -> Self {
        Self {
            url,
            crawl: true,
            max_pages,
            update,
        }
    }
}

pub async fn crawl_and_save(db: &CouchDB, opts: &CrawlOpts) -> RssResult<()> {
    let url = &opts.url;
    let crawlers = default_crawlers();

    let domain = url
        .domain()
        .ok_or_else(|| RssError::MissingCrawlRule(url.to_string()))?;
    for crawler in crawlers.into_iter() {
        if crawler.domains().contains(&domain.to_string()) {
            return crawler_loop(db, opts, &*crawler).await;
        }
    }
    Err(RssError::MissingCrawlRule(domain.to_string()))
}

#[derive(Debug, Clone)]
pub struct FetchedFeedPage {
    pub url: Url,
    pub items: Vec<UntypedRecord>,
    pub feed: FeedWatcher,
    pub put_result: Vec<PutResult>,
}

pub async fn crawler_loop(
    db: &CouchDB,
    opts: &CrawlOpts,
    crawler: &dyn Crawler, // crawler: T,
) -> RssResult<()> {
    let client = reqwest::Client::new();
    let mut url = opts.url.clone();
    let mut total = 0;
    let max_pages = opts.max_pages.unwrap_or(usize::MAX);
    let start = Instant::now();
    for _i in 0..max_pages {
        log::debug!("fetching {}", url);
        let feed_page = fetch_and_save_with_client(client.clone(), db, &url, opts.update).await?;

        // Check if the batch put to db contained any errors.
        // An error should occur when putting an existing ID
        // (i.e. existing URL).
        // TODO: Actually check the error.
        if !opts.update {
            let contains_existing = feed_page.put_result.iter().find_map(|result| match result {
                PutResult::Err(err) => Some(err),
                _ => None,
            });
            if let Some(err) = contains_existing {
                log::debug!("breaking crawl loop on {}", err);
                break;
            }
        }

        log::debug!(
            "imported {} items from {}",
            feed_page.items.len(),
            feed_page.url
        );

        total += feed_page.items.len();
        let next = crawler.next(feed_page).await?;
        url = match next {
            Next::Finished => {
                log::debug!("breaking crawl loop: finished");
                break;
            }
            Next::NextPage(url) => url,
        };
    }
    let duration = start.elapsed();
    let per_second = total as f32 / duration.as_secs_f32();
    log::info!(
        "Imported {} items in {:?} ({}/s) from {}",
        total,
        duration,
        per_second,
        url
    );
    Ok(())
}

pub async fn fetch_and_save_with_client(
    client: reqwest::Client,
    db: &CouchDB,
    url: &Url,
    update: bool,
) -> RssResult<FetchedFeedPage> {
    let mut feed = FeedWatcher::with_client(client, &url, None, Default::default(), None).unwrap();
    feed.load().await?;
    let (put_result, records) = feed.save(db, update).await?;
    let feed_page = FetchedFeedPage {
        url: feed.url.clone(),
        feed,
        items: records,
        put_result,
    };
    Ok(feed_page)
}

pub async fn fetch_and_save(db: &CouchDB, opts: &FetchOpts) -> RssResult<FetchedFeedPage> {
    let mut feed = FeedWatcher::new(&opts.url, None, Default::default(), None).unwrap();
    feed.load().await?;
    let (put_result, records) = feed.save(db, opts.update).await?;
    let feed_page = FetchedFeedPage {
        url: feed.url.clone(),
        feed,
        items: records,
        put_result,
    };
    Ok(feed_page)
}