summaryrefslogtreecommitdiff
path: root/src/betterttv.rs
blob: 1fc99b25e1fbc076733aabda18698f2a341d3681 (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
85
86
87
88
89
use reqwest::{Client, Error};
use serde::Deserialize;
use serde_json::Value;

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

#[derive(Debug, Deserialize, Clone)]
pub struct BetterTTVEmote {
    pub id: String,
    pub code: String,
    #[serde(rename = "originalCode")]
    pub original_code: Option<String>,
    #[serde(rename = "imageType")]
    pub image_type: String,
    pub animated: bool,
}

impl EmoteBase for BetterTTVEmote {
    fn get_id(&self) -> &String {
        &self.id
    }

    fn get_code(&self) -> &String {
        &self.code
    }

    fn get_original_code(&self) -> &Option<String> {
        &self.original_code
    }
}

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

impl BetterTTVAPIClient {
    pub fn new() -> Self {
        Self {
            client: Client::new(),
            base_url: "https://api.betterttv.net/3".into(),
        }
    }
}

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

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

        let mut emotes = Vec::new();

        if let Some(shared_emotes) = json.get("sharedEmotes") {
            let shared_emotes: Vec<BetterTTVEmote> =
                serde_json::from_value(shared_emotes.clone()).unwrap();
            emotes.extend(shared_emotes);
        }

        if let Some(channel_emotes) = json.get("channelEmotes") {
            let channel_emotes: Vec<BetterTTVEmote> =
                serde_json::from_value(channel_emotes.clone()).unwrap();
            emotes.extend(channel_emotes);
        }

        Ok(emotes)
    }

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

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

        Ok(serde_json::from_value(json).unwrap())
    }
}