File size: 7,535 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Enhanced discovery features for IntentForge v2
//!
//! Additional content discovery mechanisms including:
//! - Common Crawl URL extraction
//! - Additional sitemap sources
//! - API-based content discovery

use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::Path;

/// State of a Common Crawl ingestion
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CrawlState {
    pub crawl_id: String,
    pub completed_at: String,
    pub urls_enqueued: u64,
    pub urls_verified: u64,
    pub urls_total: u64,
}

impl CrawlState {
    pub fn load(data_dir: &str) -> Option<Self> {
        let path = Path::new(data_dir).join("cc_state.json");
        if let Ok(content) = std::fs::read_to_string(path) {
            serde_json::from_str(&content).ok()
        } else {
            None
        }
    }

    pub fn save(&self, data_dir: &str) -> Result<()> {
        let path = Path::new(data_dir).join("cc_state.json");
        let content = serde_json::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }
}

/// Common Crawl API integration for URL discovery
pub struct CommonCrawlDiscovery {
    client: Client,
    base_url: String,
}

impl CommonCrawlDiscovery {
    pub fn new() -> Result<Self> {
        let client = Client::builder()
            .user_agent("IntentForge/0.1 (Content Discovery Bot)")
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .context("Failed to create HTTP client for CommonCrawlDiscovery")?;

        Ok(Self {
            client,
            base_url: "https://index.commoncrawl.org".to_string(),
        })
    }

    /// Search Common Crawl index for URLs matching a query
    pub async fn search_urls(&self, query: &str, limit: usize) -> Result<Vec<String>> {
        let latest_index = self.get_latest_index().await?;
        let url = format!(
            "{}/{}-index/search?url=*&output=json&limit={}&q={}",
            self.base_url,
            latest_index,
            limit,
            urlencoding::encode(query)
        );

        let response = self
            .client
            .get(&url)
            .send()
            .await
            .context("Failed to fetch from Common Crawl API")?;

        if !response.status().is_success() {
            anyhow::bail!("Common Crawl API returned status {}", response.status());
        }

        let text = response.text().await?;
        let urls = self.parse_common_crawl_response(&text)?;

        Ok(urls)
    }

    /// Parse Common Crawl JSON response
    fn parse_common_crawl_response(&self, text: &str) -> Result<Vec<String>> {
        let mut urls = Vec::new();
        let mut seen = HashSet::new();

        // Common Crawl returns JSON lines
        for line in text.lines() {
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
                if let Some(url) = json.get("url").and_then(|v| v.as_str()) {
                    if seen.insert(url.to_string()) {
                        urls.push(url.to_string());
                    }
                }
            }
        }

        Ok(urls)
    }

    /// Get latest crawl index metadata
    pub async fn get_latest_index(&self) -> Result<String> {
        let response = self
            .client
            .get(format!("{}/collinfo.json", self.base_url))
            .send()
            .await
            .context("Failed to fetch Common Crawl index info")?;

        let indexes: Vec<serde_json::Value> = response.json().await?;

        if let Some(latest) = indexes.first() {
            if let Some(id) = latest.get("id").and_then(|v| v.as_str()) {
                return Ok(id.to_string());
            }
        }

        anyhow::bail!("No Common Crawl index found");
    }
}

/// Additional sitemap discovery for tech content
pub fn get_additional_sitemaps() -> Vec<(String, String, String)> {
    vec![
        // Tech blogs
        (
            "Netflix Tech Blog".to_string(),
            "https://netflixtechblog.com/feed/".to_string(),
            "tech".to_string(),
        ),
        (
            "Uber Engineering".to_string(),
            "https://eng.uber.com/feed/".to_string(),
            "tech".to_string(),
        ),
        (
            "Airbnb Engineering".to_string(),
            "https://medium.com/feed/airbnb-engineering".to_string(),
            "tech".to_string(),
        ),
        (
            "Spotify Labs".to_string(),
            "https://engineering.atspotify.com/feed/".to_string(),
            "tech".to_string(),
        ),
        (
            "Stripe Engineering".to_string(),
            "https://stripe.com/blog/engineering/feed".to_string(),
            "tech".to_string(),
        ),
        // AI/ML specific
        (
            "Distill.pub".to_string(),
            "https://distill.pub/rss.xml".to_string(),
            "ai".to_string(),
        ),
        (
            "Towards Data Science".to_string(),
            "https://towardsdatascience.com/feed".to_string(),
            "ai".to_string(),
        ),
        (
            "The Batch by DeepLearning.AI".to_string(),
            "https://www.deeplearning.ai/the-batch/feed/".to_string(),
            "ai".to_string(),
        ),
        // Developer resources
        (
            "CSS-Tricks".to_string(),
            "https://css-tricks.com/feed/".to_string(),
            "devtools".to_string(),
        ),
        (
            "Smashing Magazine".to_string(),
            "https://www.smashingmagazine.com/feed/".to_string(),
            "devtools".to_string(),
        ),
        (
            "A List Apart".to_string(),
            "https://alistapart.com/main/feed/".to_string(),
            "devtools".to_string(),
        ),
        // Security
        (
            "Krebs on Security".to_string(),
            "https://krebsonsecurity.com/feed/".to_string(),
            "tech".to_string(),
        ),
        (
            "Schneier on Security".to_string(),
            "https://www.schneier.com/feed/atom/".to_string(),
            "tech".to_string(),
        ),
    ]
}

/// Get additional domains to monitor with sitemaps
pub fn get_additional_domains() -> Vec<(String, String, String, Option<String>)> {
    vec![
        (
            "Medium".to_string(),
            "https://medium.com".to_string(),
            "tech".to_string(),
            Some("https://medium.com/sitemap/sitemap.xml".to_string()),
        ),
        (
            "Dev.to".to_string(),
            "https://dev.to".to_string(),
            "devtools".to_string(),
            Some("https://dev.to/sitemap.xml".to_string()),
        ),
        (
            "Hashnode".to_string(),
            "https://hashnode.com".to_string(),
            "devtools".to_string(),
            Some("https://hashnode.com/sitemap.xml".to_string()),
        ),
        (
            "Ars Technica".to_string(),
            "https://arstechnica.com".to_string(),
            "tech".to_string(),
            Some("https://arstechnica.com/sitemap.xml".to_string()),
        ),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_additional_sitemaps_not_empty() {
        let sitemaps = get_additional_sitemaps();
        assert!(!sitemaps.is_empty());
        assert!(sitemaps.len() > 10);
    }

    #[test]
    fn test_additional_domains_not_empty() {
        let domains = get_additional_domains();
        assert!(!domains.is_empty());
    }
}