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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
pub mod handlers;
pub mod wheel;

use crate::{
    io,
    proto::{self, CommandKind, Event, EventKind, Rpc},
    types::ErrorPayloadStack,
    Error,
};
use crossbeam_channel as cc;

/// An event or error sent from Discord
#[derive(Debug)]
pub enum DiscordMsg {
    Event(Event),
    Error(Error),
}

#[async_trait::async_trait]
pub trait DiscordHandler: Send + Sync {
    /// Method called when an [`Event`] or [`Error`] is received from Discord
    async fn on_message(&self, msg: DiscordMsg);
}

/// Creates a task which receives raw frame buffers and deserializes them, and either
/// notifying the awaiting oneshot for a command response, or in the case of events,
/// broadcasting the event to
pub(crate) fn handler_task(
    handler: Box<dyn DiscordHandler>,
    subscriptions: crate::Subscriptions,
    stx: cc::Sender<Option<Vec<u8>>>,
    mut rrx: tokio::sync::mpsc::Receiver<io::IoMsg>,
    state: crate::State,
) -> tokio::task::JoinHandle<()> {
    tokio::task::spawn(async move {
        tracing::debug!("starting handler loop");

        let pop_nonce = |nonce: usize| -> Option<crate::NotifyItem> {
            let mut lock = state.notify_queue.lock();

            lock.iter()
                .position(|item| item.nonce == nonce)
                .map(|position| lock.swap_remove(position))
        };

        // Shunt the user handler to a separate task so that we don't care about it blocking
        // when handling events
        let (user_tx, mut user_rx) = tokio::sync::mpsc::unbounded_channel();
        let user_task = tokio::task::spawn(async move {
            while let Some(msg) = user_rx.recv().await {
                handler.on_message(msg).await;
            }
        });

        macro_rules! user_send {
            ($msg:expr) => {
                if user_tx.send($msg).is_err() {
                    tracing::warn!("user handler task has been dropped");
                }
            };
        }

        while let Some(io_msg) = rrx.recv().await {
            let msg = match io_msg {
                io::IoMsg::Disconnected(err) => {
                    user_send!(DiscordMsg::Event(Event::Disconnected { reason: err }));
                    continue;
                }
                io::IoMsg::Frame(frame) => process_frame(frame),
            };

            match msg {
                Msg::Event(event) => {
                    if let Event::Ready { .. } = &event {
                        // Spawn a task that subscribes to all of the events
                        // that the caller was interested in when we've finished
                        // the handshake with Discord
                        subscribe_task(subscriptions, stx.clone());
                    }

                    user_send!(DiscordMsg::Event(event));
                }
                Msg::Command { command, kind } => {
                    use crate::proto::Command;
                    // Some commands can also be turned into events for consistency
                    match &command.inner {
                        Command::Subscribe { evt } => {
                            tracing::debug!(event = ?evt, "subscription succeeded");
                            continue;
                        }
                        Command::CreateLobby(lobby) => {
                            user_send!(DiscordMsg::Event(Event::LobbyCreate(lobby.clone())));
                        }
                        Command::ConnectToLobby(lobby) => {
                            user_send!(DiscordMsg::Event(Event::LobbyConnect(lobby.clone())));
                        }
                        _ => {}
                    }

                    match pop_nonce(command.nonce) {
                        Some(ni) => {
                            if ni
                                .tx
                                .send(if ni.cmd == kind {
                                    Ok(command.inner)
                                } else {
                                    Err(Error::Discord(crate::DiscordErr::MismatchedResponse {
                                        expected: ni.cmd,
                                        actual: kind,
                                        nonce: command.nonce,
                                    }))
                                })
                                .is_err()
                            {
                                tracing::warn!(
                                    cmd = ?kind,
                                    nonce = command.nonce,
                                    "command response dropped as receiver was closed",
                                );
                            }
                        }
                        None => {
                            tracing::warn!(
                                cmd = ?command.inner,
                                nonce = command.nonce,
                                "received a command response with an unknown nonce",
                            );
                        }
                    }
                }
                Msg::Error { nonce, error, .. } => match nonce {
                    Some(nonce) => match pop_nonce(nonce) {
                        Some(ni) => {
                            if let Err(err) = ni.tx.send(Err(error)) {
                                tracing::warn!(
                                    error = ?err,
                                    nonce = nonce,
                                    "error result dropped as receiver was closed",
                                );
                            }
                        }
                        None => {
                            user_send!(DiscordMsg::Error(error));
                        }
                    },
                    None => {
                        user_send!(DiscordMsg::Error(error));
                    }
                },
            }
        }

        drop(user_tx);
        let _ = user_task.await;
    })
}

#[derive(Debug)]
pub(crate) enum Msg {
    Command {
        command: proto::command::CommandFrame,
        kind: CommandKind,
    },
    Event(Event),
    Error {
        nonce: Option<usize>,
        error: Error,
    },
}

fn process_frame(data_buf: Vec<u8>) -> Msg {
    // Discord echoes back our requests with the same nonce they were sent
    // with, however for those echoes, the "evt" field is not set, other than
    // for the "ERROR" RPC type, so we attempt to deserialize those two
    // cases first so we can just ignore the echoes and move on to avoid
    // further complicating the deserialization of the RPCs we actually
    // care about

    #[derive(serde::Deserialize)]
    struct RawMsg {
        cmd: Option<CommandKind>,
        evt: Option<EventKind>,
        #[serde(deserialize_with = "crate::util::string::deserialize_opt")]
        nonce: Option<usize>,
    }

    let rm: RawMsg = match serde_json::from_slice(&data_buf) {
        Ok(f) => f,
        Err(e) => {
            tracing::warn!(
                "Failed to deserialize message: {} {}",
                e,
                std::str::from_utf8(&data_buf).unwrap(),
            );

            return Msg::Error {
                nonce: None,
                error: Error::Json(e),
            };
        }
    };

    match rm.evt {
        Some(EventKind::Error) => {
            #[derive(serde::Deserialize)]
            struct ErrorMsg<'stack> {
                #[serde(borrow)]
                data: Option<ErrorPayloadStack<'stack>>,
            }

            match serde_json::from_slice::<ErrorMsg<'_>>(&data_buf) {
                Ok(em) => Msg::Error {
                    nonce: rm.nonce,
                    error: Error::Discord(crate::DiscordErr::Api(em.data.into())),
                },
                Err(e) => Msg::Error {
                    nonce: rm.nonce,
                    error: Error::Discord(crate::DiscordErr::Api(crate::DiscordApiErr::Generic {
                        code: None,
                        message: Some(format!("failed to deserialize error: {}", e)),
                    })),
                },
            }
        }
        Some(_) => match serde_json::from_slice::<proto::event::EventFrame>(&data_buf) {
            Ok(event_frame) => Msg::Event(event_frame.inner),
            Err(e) => {
                tracing::warn!(
                    "failed to deserialize event: {:?}",
                    std::str::from_utf8(&data_buf)
                );
                Msg::Error {
                    nonce: rm.nonce,
                    error: Error::Json(e),
                }
            }
        },
        None => match serde_json::from_slice(&data_buf) {
            Ok(cmd_frame) => Msg::Command {
                command: cmd_frame,
                kind: rm
                    .cmd
                    .expect("successfully deserialized command with 'cmd' field"),
            },
            Err(e) => {
                tracing::warn!(
                    "failed to deserialize command: {:?}",
                    std::str::from_utf8(&data_buf)
                );

                Msg::Error {
                    nonce: rm.nonce,
                    error: Error::Json(e),
                }
            }
        },
    }
}

fn subscribe_task(subs: crate::Subscriptions, stx: cc::Sender<Option<Vec<u8>>>) {
    tokio::task::spawn(async move {
        // Assume a max of 64KiB write size and just write all of the
        // subscriptions into a single buffer rather than n
        let mut buffer = Vec::with_capacity(1024);
        let mut nonce = 1usize;

        let mut push = |kind: EventKind| {
            #[cfg(target_pointer_width = "32")]
            let nunce = 0x10000000 | nonce;
            #[cfg(target_pointer_width = "64")]
            let nunce = 0x1000000000000000 | nonce;

            let _ = io::serialize_message(
                io::OpCode::Frame,
                &Rpc::<()> {
                    cmd: CommandKind::Subscribe,
                    evt: Some(kind),
                    nonce: nunce.to_string(),
                    args: None,
                },
                &mut buffer,
            );

            nonce += 1;
        };

        let activity = if subs.contains(crate::Subscriptions::ACTIVITY) {
            [
                EventKind::ActivityInvite,
                EventKind::ActivityJoin,
                EventKind::ActivityJoinRequest,
                EventKind::ActivitySpectate,
            ]
            .iter()
        } else {
            [].iter()
        };

        let lobby = if subs.contains(crate::Subscriptions::LOBBY) {
            [
                EventKind::LobbyDelete,
                EventKind::LobbyMemberConnect,
                EventKind::LobbyMemberDisconnect,
                EventKind::LobbyMemberUpdate,
                EventKind::LobbyMessage,
                EventKind::LobbyUpdate,
                EventKind::SpeakingStart,
                EventKind::SpeakingStop,
            ]
            .iter()
        } else {
            [].iter()
        };

        let user = if subs.contains(crate::Subscriptions::USER) {
            [EventKind::CurrentUserUpdate].iter()
        } else {
            [].iter()
        };

        let relations = if subs.contains(crate::Subscriptions::RELATIONSHIPS) {
            [EventKind::RelationshipUpdate].iter()
        } else {
            [].iter()
        };

        let voice = if subs.contains(crate::Subscriptions::VOICE) {
            [EventKind::VoiceSettingsUpdate].iter()
        } else {
            [].iter()
        };

        activity
            .chain(lobby)
            .chain(user)
            .chain(relations)
            .chain(voice)
            .for_each(|kind| {
                push(*kind);
            });

        // Unlike EVERY other event, subscribing to OVERLAY_UPDATE requires
        // an argument... :facepalm:
        if subs.contains(crate::Subscriptions::OVERLAY) {
            #[cfg(target_pointer_width = "32")]
            let nunce = 0x10000000 | nonce;
            #[cfg(target_pointer_width = "64")]
            let nunce = 0x1000000000000000 | nonce;

            let _ = io::serialize_message(
                io::OpCode::Frame,
                &Rpc {
                    cmd: CommandKind::Subscribe,
                    evt: Some(EventKind::OverlayUpdate),
                    nonce: nunce.to_string(),
                    args: Some(crate::overlay::OverlayPidArgs::new()),
                },
                &mut buffer,
            );

            //nonce += 1;
        }

        if stx.send(Some(buffer)).is_err() {
            tracing::warn!("unable to send subscription RPCs to I/O task");
        }
    });
}