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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use async_trait::async_trait;
use futures::{SinkExt, StreamExt};
use serde::Deserialize;
use serde_json::json;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use url::Url;
use uuid::Uuid;

use config::{API_URL, TIME_OUT};
use user::{TopUserWrapper, User};

mod config;
pub mod prelude;
mod user;

/// In order to use EvenHandler you must first define a struct and then
/// implement EvenHandler for that struct.
///
/// Then you must pass that struct as an argument to add_event_handler
/// which is defined on Client.
/// ```
/// #[async_trait]
/// impl EventHandler for Handler {
///   async fn on_message(&self, msg: String) {
///     println!("{}", msg);
///   }
///
///   async fn on_pong(&self) {
///     println!("Received ping")
///   }
///
///   async fn connection_closed(&self) {
///     println!("Connection has closed");
///     std::process::exit(1);
///   }
///
///   async fn on_ready(&self, user: &User) {
///     println!("{} is ready", user.display_name);
///   }
/// }
/// ```
#[async_trait]
pub trait EventHandler {
    async fn on_message(&self, _msg: String);
    async fn on_pong(&self);
    async fn connection_closed(&self);
    async fn on_ready(&self, _user: &User);
}

#[derive(Clone)]
pub struct Client<'a, T>
where
    T: EventHandler + Sync,
{
    token: String,
    refresh_token: String,
    bot_token: Option<String>,
    bot_refresh_token: Option<String>,
    room_id: Option<&'a str>,
    event_handler: Option<T>,
}

impl<'a, T> Client<'a, T>
where
    T: EventHandler + Sync,
{
    pub fn new(token: String, refresh_token: String) -> Self {
        Self {
            token,
            refresh_token,
            bot_token: None,
            bot_refresh_token: None,
            room_id: None,
            event_handler: None,
        }
    }

    /// In order to create a bot make sure to first authenticate with your normal tokens and create a client
    /// ```
    /// let mut client = Client::new(
    ///   token,
    ///   refresh_token
    /// ).add_event_handler(Handler);
    /// ```
    /// Then call use_create_bot on client with a username and a boolean value to tell dogehouse-rs
    /// if you want your bot tokens to be shown.
    /// use_create_bot is an async function so make sure to use await or a blocking call.
    /// ```
    /// client.use_create_bot("bot_name", true").await?;
    /// ```
    pub async fn use_create_bot(
        &mut self,
        username: &'a str,
        show_bot_tokens: bool,
    ) -> anyhow::Result<()> {
        let url = Url::parse(API_URL)?;

        let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
        let (mut write, mut read) = ws_stream.split();

        write
            .send(Message::Text(
                json!(
                    {
                        "op": "auth",
                        "d": {
                            "accessToken": self.token,
                            "refreshToken": self.refresh_token,
                            "reconnectToVoice": false,
                            "currentRoomId": "",
                            "muted": true,
                            "platform": "dogehouse-rs"
                        }
                    }
                )
                .to_string(),
            ))
            .await?;

        #[derive(Deserialize)]
        struct CreateBotResponse {
            op: String,
            p: CreateBotResponseP,
        }

        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct CreateBotResponseP {
            api_key: serde_json::Value,
            is_username_taken: serde_json::Value,
            error: serde_json::Value,
        }

        write
            .send(Message::Text(
                json!(
                    {
                        "op": config::user::CREATE_BOT,
                        "p": {
                            "username": username
                        },
                        "ref": "[uuid]",
                        "v": "0.2.0",
                    }
                )
                .to_string(),
            ))
            .await?;

        // Skip messages from first two requests
        read.next().await;
        read.next().await;

        let n = read.next().await.unwrap()?.to_string();
        let bot_response =
            serde_json::from_str::<CreateBotResponse>(&n).expect("Error invalid bot name");
        if bot_response.p.is_username_taken.is_boolean() {
            return Err(anyhow::Error::msg("Bot name is taken."));
        }

        #[derive(Deserialize, Debug)]
        #[serde(rename_all = "camelCase")]
        struct BotAccount {
            access_token: String,
            refresh_token: String,
        }

        let bot_account = reqwest::Client::new()
            .post("https://api.dogehouse.tv/bot/auth")
            .header("content-type", "application/json")
            .body(
                json!(
                    {
                        "apiKey": bot_response.p.api_key.as_str()
                    }
                )
                .to_string(),
            )
            .send()
            .await?
            .json::<BotAccount>()
            .await?;

        if show_bot_tokens {
            println!("Bot tokens: {:?}", &bot_account);
        }

        self.bot_token = Some(bot_account.access_token);
        self.bot_refresh_token = Some(bot_account.refresh_token);
        Ok(())
    }

    /// Let user assign an event handler that implements EventHandler trait
    pub fn add_event_handler(mut self, handler: T) -> Self {
        self.event_handler = Some(handler);
        self
    }

    pub async fn start(&mut self, room_id: &'a str) -> anyhow::Result<()> {
        self.room_id = Some(room_id);

        let token = match self.bot_token.is_some() {
            true => &self.bot_token.as_ref().unwrap(),
            false => &self.token,
        };

        let refresh_token = match self.bot_refresh_token.is_some() {
            true => &self.bot_refresh_token.as_ref().unwrap(),
            false => &self.refresh_token,
        };

        let url = Url::parse(API_URL)?;

        let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
        let (mut write, mut read) = ws_stream.split();

        write
            .send(Message::Text(
                json!(
                    {
                        "op": "auth",
                        "d": {
                            "accessToken": token,
                            "refreshToken": refresh_token,
                            "reconnectToVoice": false,
                            "currentRoomId": self.room_id.unwrap(),
                            "muted": true,
                            "platform": "dogehouse-rs"
                        }
                    }
                )
                .to_string(),
            ))
            .await?;

        let n = read.next().await.unwrap()?.to_string();
        println!("{}", &n);

        let account: TopUserWrapper = serde_json::from_str(&n)?;
        self.event_handler
            .as_ref()
            .unwrap()
            .on_ready(&account.d.user)
            .await;

        let room_join_ref = Uuid::new_v4();

        write
            .send(Message::Text(
                json!({
                    "op": "room:join",
                    "d": {
                        "roomId": self.room_id.unwrap()
                    },
                    "ref": room_join_ref.to_string(),
                    "v": "0.2.0",
                })
                .to_string(),
            ))
            .await?;

        tokio::spawn(async move {
            loop {
                write.send("ping".into()).await.unwrap();
                std::thread::sleep(std::time::Duration::new(TIME_OUT, 0));
            }
        });

        while let Some(msg) = read.next().await {
            let msg = msg?;
            if msg.is_close() {
                self.event_handler
                    .as_ref()
                    .unwrap()
                    .connection_closed()
                    .await;
                continue;
            } else if msg.is_binary() || msg.is_text() {
                if msg.to_string() == "pong" {
                    self.event_handler.as_ref().unwrap().on_pong().await;
                    continue;
                }
                self.event_handler
                    .as_ref()
                    .unwrap()
                    .on_message(msg.to_string())
                    .await;
                continue;
            }
        }

        Ok(())
    }
}