aboutsummaryrefslogtreecommitdiff
path: root/lib/mi/src/lib.rs
blob: 6ac2620bae6ff15497d79189251cd17f8a665966 (plain)
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
use color_eyre::eyre::Result;
use reqwest::header;
use serde::{Deserialize, Serialize};
use tracing::instrument;

const USER_AGENT_BASE: &str = concat!(
    "library/",
    env!("CARGO_PKG_NAME"),
    "/",
    env!("CARGO_PKG_VERSION")
);

pub struct Client {
    cli: reqwest::Client,
    base_url: String,
}

impl Client {
    pub fn new(token: String, user_agent: String) -> Result<Self> {
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::AUTHORIZATION,
            header::HeaderValue::from_str(&token.clone())?,
        );

        let cli = reqwest::Client::builder()
            .user_agent(&format!("{} {}", user_agent, USER_AGENT_BASE))
            .default_headers(headers)
            .build()?;

        Ok(Self {
            cli,
            base_url: "https://mi.within.website".to_string(),
        })
    }

    #[instrument(skip(self), err)]
    pub async fn mentioners(&self, url: String) -> Result<Vec<WebMention>> {
        Ok(self
            .cli
            .get(&format!("{}/api/webmention/for", self.base_url))
            .query(&[("target", &url)])
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    #[instrument(skip(self), err)]
    pub async fn refresh(&self) -> Result<()> {
        self.cli
            .post("https://mi.within.website/api/blog/refresh")
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }
}

#[derive(Debug, Deserialize, Eq, PartialEq, Clone, Serialize)]
pub struct WebMention {
    pub source: String,
    pub title: Option<String>,
}