File size: 2,296 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
#![allow(dead_code)]
use crate::meta_search::models::SearchResult;
use crate::meta_search::providers::{SearchContext, SearchProvider};
use anyhow::Result;
use async_trait::async_trait;
use scraper::{Html, Selector};
use std::sync::Arc;

pub struct MediumProvider;

#[async_trait]
impl SearchProvider for MediumProvider {
    fn name(&self) -> &'static str {
        "medium"
    }

    async fn search(&self, query: &str, ctx: Arc<SearchContext>) -> Result<Vec<SearchResult>> {
        let client = crate::meta_search::providers::build_client_with_transport(&ctx, 15).await?;
        let url = format!("https://medium.com/search?q={}", urlencoding::encode(query));

        let resp = client.get(url).send().await?.text().await?;
        let document = Html::parse_document(&resp);

        let article_selector = Selector::parse("article").unwrap();
        let title_selector = Selector::parse("h2").unwrap();
        let link_selector = Selector::parse("a[href*='/p/']").unwrap();

        let mut results = Vec::new();
        for element in document.select(&article_selector) {
            if let Some(title_el) = element.select(&title_selector).next() {
                let title = title_el.text().collect::<String>();
                let url = element
                    .select(&link_selector)
                    .next()
                    .and_then(|e| e.value().attr("href"))
                    .unwrap_or("");

                let final_url = if url.starts_with('/') {
                    format!("https://medium.com{}", url)
                } else {
                    url.to_string()
                };

                if !final_url.is_empty() && !title.is_empty() {
                    results.push(SearchResult {
                        title: title.trim().to_string(),
                        url: final_url,
                        description: "Article on Medium".to_string(),
                        source: "medium".to_string(),
                        score: 0.6,
                        media_type: "text".to_string(),
                        thumbnail_url: None,
                        published_at: None,
                    });
                }
            }
        }

        Ok(results)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}