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
295
296
297
use anyhow::bail;
use anyhow::Result;
use futures::Future;
use futures::Sink;
use futures::StreamExt;

use serde::Deserialize;

use futures::Stream;

use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

#[derive(Debug, Deserialize)]
pub struct MessageMetadata {
    pub message_id: String,
    pub message_timestamp: String,
    pub message_type: String,
    pub subscription_type: Option<String>,
    pub subscription_version: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Message {
    pub metadata: MessageMetadata,
    pub payload: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub struct SessionWelcomeSession {
    pub id: String,
    pub connected_at: String,
    pub status: String,
    pub reconnect_url: Option<String>,
    pub keepalive_timeout_seconds: i64,
}

#[derive(Debug, Deserialize)]
pub struct SessionWelcome {
    pub session: SessionWelcomeSession,
}

#[derive(Debug, Deserialize)]
pub struct Notification {
    pub subscription: serde_json::Value,
    pub event: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub struct ChannelUpdate {
    pub broadcaster_user_id: String,
    pub broadcaster_user_login: String,
    pub broadcaster_user_name: String,
    pub title: String,
    pub language: String,
    pub category_id: String,
    pub category_name: String,
    pub content_classification_labels: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct CustomRewardRedemptionAddReward {
    pub id: String,
}

#[derive(Debug, Deserialize)]
pub struct CustomRewardRedemptionAdd {
    pub id: String,
    pub user_login: String,
    pub user_input: String,
    pub reward: CustomRewardRedemptionAddReward,
}

#[derive(Debug, Deserialize)]
pub struct StreamOnline {
    pub id: String,
    pub broadcaster_user_id: String,
    pub broadcaster_user_login: String,
    pub broadcaster_user_name: String,
    pub r#type: String,
    pub started_at: String,
}

#[derive(Debug, Deserialize)]
pub struct StreamOffline {
    pub broadcaster_user_id: String,
    pub broadcaster_user_login: String,
    pub broadcaster_user_name: String,
}

#[derive(Debug, Deserialize)]
pub enum NotificationType {
    ChannelUpdate(ChannelUpdate),
    CustomRewardRedemptionAdd(CustomRewardRedemptionAdd),
    StreamOnline(StreamOnline),
    StreamOffline(StreamOffline),
}

pub struct Client {
    inner_stream: Pin<
        Box<
            tokio_tungstenite::WebSocketStream<
                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
            >,
        >,
    >,
    ping_sleep: Pin<Box<tokio::time::Sleep>>,
}

impl Stream for Client {
    type Item = NotificationType;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        let mut inner_stream = this.inner_stream.as_mut();

        match this.ping_sleep.as_mut().poll(cx) {
            Poll::Pending => {}
            Poll::Ready(..) => {
                this.ping_sleep
                    .as_mut()
                    .reset(tokio::time::Instant::now() + tokio::time::Duration::from_secs(30));

                match inner_stream.as_mut().start_send(
                    tokio_tungstenite::tungstenite::protocol::Message::Ping(vec![]),
                ) {
                    Err(..) => return Poll::Ready(None),
                    _ => {}
                };
            }
        };

        loop {
            match inner_stream.as_mut().poll_next(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(v) => match v {
                    Some(Ok(tokio_tungstenite::tungstenite::protocol::Message::Ping(..))) => {
                        match inner_stream.as_mut().start_send(
                            tokio_tungstenite::tungstenite::protocol::Message::Pong(vec![]),
                        ) {
                            Ok(()) => continue,
                            Err(..) => break,
                        };
                    }
                    Some(Ok(tokio_tungstenite::tungstenite::protocol::Message::Text(text))) => {
                        let message: Message = match serde_json::from_str(&text) {
                            Ok(v) => v,
                            Err(..) => break,
                        };

                        match message.metadata.message_type.as_str() {
                            "notification" => {
                                let subtype = match &message.metadata.subscription_type {
                                    Some(v) => v,
                                    None => break,
                                };

                                let notification: Notification =
                                    match serde_json::from_value(message.payload.clone()) {
                                        Ok(v) => v,
                                        Err(..) => break,
                                    };

                                match subtype.as_str() {
                                    "channel.update" => {
                                        let event: ChannelUpdate =
                                            match serde_json::from_value(notification.event) {
                                                Ok(v) => v,
                                                Err(..) => break,
                                            };

                                        return Poll::Ready(Some(NotificationType::ChannelUpdate(
                                            event,
                                        )));
                                    }
                                    "channel.channel_points_custom_reward_redemption.add" => {
                                        let event: CustomRewardRedemptionAdd =
                                            match serde_json::from_value(notification.event) {
                                                Ok(v) => v,
                                                Err(..) => break,
                                            };

                                        return Poll::Ready(Some(
                                            NotificationType::CustomRewardRedemptionAdd(event),
                                        ));
                                    }
                                    "stream.online" => {
                                        let event: StreamOnline =
                                            match serde_json::from_value(notification.event) {
                                                Ok(v) => v,
                                                Err(..) => break,
                                            };

                                        return Poll::Ready(Some(NotificationType::StreamOnline(
                                            event,
                                        )));
                                    }
                                    "stream.offline" => {
                                        let event: StreamOffline =
                                            match serde_json::from_value(notification.event) {
                                                Ok(v) => v,
                                                Err(..) => break,
                                            };

                                        return Poll::Ready(Some(NotificationType::StreamOffline(
                                            event,
                                        )));
                                    }
                                    _ => return Poll::Pending,
                                }
                            }
                            _ => continue,
                        }
                    }
                    Some(..) => continue,
                    None => break,
                },
            }
        }

        Poll::Ready(None)
    }
}

impl<T: crate::auth::TokenStorage> crate::helix::Client<T> {
    pub async fn connect_eventsub(&mut self, topics: Vec<(String, String)>) -> Result<Client> {
        let (mut ws_stream, _) =
            match tokio_tungstenite::connect_async("wss://eventsub.wss.twitch.tv/ws").await {
                Ok(v) => v,
                Err(e) => return Err(e.into()),
            };

        let welcome = loop {
            let msg = ws_stream.next().await;
            match msg {
                Some(Ok(tokio_tungstenite::tungstenite::protocol::Message::Text(text))) => {
                    let message: Message = match serde_json::from_str(&text) {
                        Ok(v) => v,
                        Err(e) => return Err(e.into()),
                    };

                    if message.metadata.message_type.as_str() != "session_welcome" {
                        bail!("No session welcome");
                    }

                    let welcome: SessionWelcome =
                        match serde_json::from_value(message.payload.clone()) {
                            Ok(v) => v,
                            Err(e) => return Err(e.into()),
                        };

                    break welcome;
                }
                Some(Err(e)) => return Err(e.into()),
                Some(..) => {}
                None => bail!("WebSocket dropped"),
            }
        };

        let broadcaster_id = match self.get_token_user_id().await {
            Ok(v) => v,
            Err(..) => bail!("No token user id"),
        };
        for (subtype, version) in topics.into_iter() {
            match self
                .create_eventsub_subscription(&crate::helix::EventSubCreate {
                    r#type: subtype,
                    version: version,
                    condition: crate::helix::EventSubCondition {
                        broadcaster_id: Some(broadcaster_id.clone()),
                        broadcaster_user_id: Some(broadcaster_id.clone()),
                        moderator_user_id: Some(broadcaster_id.clone()),
                        user_id: Some(broadcaster_id.clone()),
                        ..Default::default()
                    },
                    transport: crate::helix::EventSubTransport {
                        method: "websocket".to_string(),
                        session_id: Some(welcome.session.id.clone()),
                        ..Default::default()
                    },
                })
                .await
            {
                Ok(..) => {}
                Err(..) => {
                    bail!("create_eventsub_subscription failed")
                }
            };
        }

        Ok(Client {
            inner_stream: Pin::new(Box::new(ws_stream)),
            ping_sleep: Box::pin(tokio::time::sleep(tokio::time::Duration::from_secs(30))),
        })
    }
}