summaryrefslogtreecommitdiff
path: root/src/seventv.rs
blob: 97d462b747608aafd75dfd29ff59cbebb7aa809a (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use reqwest::{Client, Error};
use serde_json::Value;

use crate::emotes::{Emote, RetrieveEmoteAPI};

pub struct SevenTVAPIClient {
    client: Client,
    base_url: String,
}

impl SevenTVAPIClient {
    pub fn new() -> Self {
        Self {
            client: Client::new(),
            base_url: "https://7tv.io/v3".into(),
        }
    }

    fn parse_emoteset(&self, emotesets_json: &Value) -> Vec<Emote> {
        let mut emotes = Vec::new();

        let emote_values = emotesets_json.get("emotes").unwrap().as_array().unwrap();

        for emote_value in emote_values {
            let id = emote_value.get("id").unwrap().as_str().unwrap().to_string();
            let code = emote_value
                .get("name")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string();
            let o_code = emote_value
                .get("data")
                .unwrap()
                .get("name")
                .unwrap()
                .to_string();

            let original_code: Option<String> = if code.eq(&o_code) { None } else { Some(o_code) };

            emotes.push(Emote {
                id,
                code,
                original_code,
            });
        }

        emotes
    }
}

impl RetrieveEmoteAPI<Emote> for SevenTVAPIClient {
    async fn get_channel_emotes(&self, channel_id: &str) -> Result<Vec<Emote>, Error> {
        let response = self
            .client
            .get(format!("{}/users/twitch/{}", self.base_url, channel_id))
            .send()
            .await?
            .error_for_status()?;

        let json: Value = response.json().await?;

        let set = json.get("emote_set").unwrap();

        let emotes = self.parse_emoteset(set);

        Ok(emotes)
    }

    async fn get_global_emotes(&self) -> Result<Vec<Emote>, Error> {
        let response = self
            .client
            .get(format!("{}/emote-sets/global", self.base_url))
            .send()
            .await?
            .error_for_status()?;

        let json: Value = response.json().await?;

        let emotes = self.parse_emoteset(&json);

        Ok(emotes)
    }
}