twitch_api 0.7.2

Library for talking with the new Twitch API aka. "Helix", EventSub and more!
Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#![allow(deprecated)]
//! Holds serializable pubsub stuff
//!
//! Use [`listen_command()`] to send subscription listen and parse the responses with [`Response::parse`]
//!
//! # Undocumented features
//!
//! This crate has some pubsub topics that are not documented by twitch. These may stop working at any time. To enable these, use feature
//! <span
//!   class="module-item stab portability"
//!   style="display: inline; border-radius: 3px; padding: 2px; font-size: 80%; line-height: 1.2;"><code>unsupported</code>
//! </span>
//! to use them. Note that this crate doesn't try to keep changes to these pubsub topics semver compatible.

static ERROR_TRYFROM: &str = "no match";

/// Implement `From<$type> for String` for serializing and `TryFrom<String> for $type` for deserializing.
macro_rules! impl_de_ser {
    (@field $e:expr) => {".{}"};
    ($type:ident, $fmt:literal, $($field:ident),* $(,)? $(?$opt_field:ident),* $(,)?) => {
        impl From<$type> for String {
            fn from(t: $type) -> Self { format!(concat!($fmt, $(impl_de_ser!(@field $field),)+ $(impl_de_ser!(@field $opt_field),)*), $(t.$field,)*$(t.$opt_field.map(|f| f.to_string()).unwrap_or_default(),)*).trim_end_matches(".").to_owned() }
        }
        impl<'a> From<&'a $type> for String {
            fn from(t: &'a $type) -> Self { format!(concat!($fmt, $(impl_de_ser!(@field $field),)+ $(impl_de_ser!(@field $opt_field),)*), $(t.$field,)*$(t.$opt_field.map(|f| f.to_string()).unwrap_or_default(),)*).trim_end_matches(".").to_owned() }
        }

        impl From<$type> for super::Topics {
            fn from(t: $type) -> Self {
                use super::Topic as _;
                t.into_topic()
            }
        }

        impl ::std::fmt::Display for $type {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                let s: String = ::std::convert::TryInto::try_into(self).map_err(|_| ::std::fmt::Error)?;
                f.write_str(&s)
            }
        }

        impl ::std::convert::TryFrom<String> for $type {
            type Error = &'static str;

            fn try_from(s: String) -> ::std::result::Result<Self, Self::Error> {
                if s.starts_with($fmt) {
                    let sub_s = s.strip_prefix($fmt).ok_or("could not strip str, this should never be hit")?;
                    match sub_s.split('.').collect::<Vec<_>>().as_slice() {
                        ["", $($field,)* $($opt_field,)*] => {
                            Ok($type {
                                $(
                                    $field: $field.parse()
                                            .map_err(|_| concat!("could not parse field <", stringify!($field), ">"))?,
                                )*
                                $(
                                    $opt_field: Some($opt_field.parse()
                                            .map_err(|_| concat!("could not parse field <", stringify!($opt_field), ">"))?),
                                )*
                            } )
                        }
                        #[allow(unreachable_patterns)]
                        ["", $($field,)*] => {
                            Ok($type {
                                $(
                                    $field: $field.parse()
                                            .map_err(|_| concat!("could not parse field <", stringify!($field), ">"))?,
                                )*
                                $(
                                    $opt_field: None,
                                )*
                            } )
                        }
                        _ => Err(crate::pubsub::ERROR_TRYFROM)
                    }
                } else {
                    Err(crate::pubsub::ERROR_TRYFROM)
                }
            }
        }
    };
}

use serde::Deserializer;
use serde_derive::{Deserialize, Serialize};

pub mod automod_queue;
pub mod channel_bits;
pub mod channel_bits_badge;
#[cfg(feature = "unsupported")]
pub mod channel_cheer;
pub mod channel_points;
#[cfg(feature = "unsupported")]
pub mod channel_sub_gifts;
pub mod channel_subscriptions;
#[cfg(feature = "unsupported")]
pub mod community_points;
#[cfg(feature = "unsupported")]
pub mod following;
#[cfg(feature = "unsupported")]
pub mod hypetrain;
pub mod moderation;
#[cfg(feature = "unsupported")]
pub mod raid;
pub mod user_moderation_notifications;
#[cfg(feature = "unsupported")]
pub mod video_playback;

use crate::parse_json;

/// A logical partition of messages that clients may subscribe to, to get messages.
///
/// also known as event
pub trait Topic: serde::Serialize + Into<String> {
    /// Scopes needed by this topic
    #[cfg(feature = "twitch_oauth2")]
    #[cfg_attr(nightly, doc(cfg(feature = "twitch_oauth2")))]
    const SCOPE: twitch_oauth2::Validator;

    /// Convert this into a [`Topics`]
    fn into_topic(self) -> Topics;
}

/// All possible topics
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Hash)]
#[serde(untagged)]
#[non_exhaustive]
pub enum Topics {
    /// AutoMod flags a message as potentially inappropriate, and when a moderator takes action on a message.
    AutoModQueue(automod_queue::AutoModQueue),
    /// A user redeems an reward using channel points.
    #[cfg(feature = "unsupported")]
    CommunityPointsChannelV1(community_points::CommunityPointsChannelV1),
    /// Anyone cheers in a specified channel.
    ChannelBitsEventsV2(channel_bits::ChannelBitsEventsV2),
    /// Anyone shares a bit badge in a specified channel.
    ChannelBitsBadgeUnlocks(channel_bits_badge::ChannelBitsBadgeUnlocks),
    /// A user redeems a cheer with shared rewards.
    #[cfg(feature = "unsupported")]
    ChannelCheerEventsPublicV1(channel_cheer::ChannelCheerEventsPublicV1),
    /// A user gifts subs.
    #[cfg(feature = "unsupported")]
    ChannelSubGiftsV1(channel_sub_gifts::ChannelSubGiftsV1),
    /// A moderator performs an action in the channel.
    ChatModeratorActions(moderation::ChatModeratorActions),
    /// A user redeems an reward using channel points.
    ChannelPointsChannelV1(channel_points::ChannelPointsChannelV1),
    /// A subscription event happens in channel
    ChannelSubscribeEventsV1(channel_subscriptions::ChannelSubscribeEventsV1),
    /// Statistics about stream
    #[cfg(feature = "unsupported")]
    VideoPlayback(video_playback::VideoPlayback),
    /// Statistics about stream
    #[cfg(feature = "unsupported")]
    VideoPlaybackById(video_playback::VideoPlaybackById),
    /// A user redeems an reward using channel points.
    #[cfg(feature = "unsupported")]
    HypeTrainEventsV1(hypetrain::HypeTrainEventsV1),
    /// A user redeems an reward using channel points.
    #[cfg(feature = "unsupported")]
    HypeTrainEventsV1Rewards(hypetrain::HypeTrainEventsV1Rewards),
    /// A user follows the channel
    #[cfg(feature = "unsupported")]
    Following(following::Following),
    /// A user raids the channel
    #[cfg(feature = "unsupported")]
    Raid(raid::Raid),
    /// A user’s message held by AutoMod has been approved or denied.
    UserModerationNotifications(user_moderation_notifications::UserModerationNotifications),
}

impl std::fmt::Display for Topics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use self::Topics::*;
        let s = match self {
            AutoModQueue(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            CommunityPointsChannelV1(t) => t.to_string(),
            ChannelBitsEventsV2(t) => t.to_string(),
            ChannelBitsBadgeUnlocks(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            ChannelCheerEventsPublicV1(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            ChannelSubGiftsV1(t) => t.to_string(),
            ChatModeratorActions(t) => t.to_string(),
            ChannelPointsChannelV1(t) => t.to_string(),
            ChannelSubscribeEventsV1(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            VideoPlayback(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            VideoPlaybackById(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            HypeTrainEventsV1(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            HypeTrainEventsV1Rewards(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            Following(t) => t.to_string(),
            #[cfg(feature = "unsupported")]
            Raid(t) => t.to_string(),
            UserModerationNotifications(t) => t.to_string(),
        };
        f.write_str(&s)
    }
}

#[derive(Serialize)]
struct ITopicSubscribeData<'a> {
    topics: &'a [String],
    #[serde(skip_serializing_if = "Option::is_none")]
    auth_token: Option<&'a str>,
}
#[derive(Serialize)]
struct ITopicSubscribe<'a> {
    #[serde(rename = "type")]
    _type: &'static str,
    nonce: Option<&'a str>,
    data: ITopicSubscribeData<'a>,
}

/// Create a listen command.
///
/// # Examples
///
/// Create a listen message for moderator actions
///
/// ```rust
/// # use twitch_api::pubsub::{self, Topic as _};
/// // We want to subscribe to moderator actions on channel with id 1234
/// // as if we were a user with id 4321 that is moderator on the channel.
/// let chat_mod_actions = pubsub::moderation::ChatModeratorActions {
///     user_id: 4321,
///     channel_id: 1234,
/// }
/// .into_topic();
///
/// // Listen to follows as well
/// let follows =
///     pubsub::following::Following { channel_id: 1234 }.into_topic();
/// // Create the topic command to send to twitch
/// let command = pubsub::listen_command(
///     &[chat_mod_actions, follows],
///     "authtoken",
///     "super se3re7 random string",
/// )
/// .expect("serializing failed");
/// // Send the message with your favorite websocket client
/// send_command(command).unwrap();
/// // To parse the websocket messages, use pubsub::Response::parse
/// # fn send_command(command: String) -> Result<(),()> {Ok(())}
/// ```
pub fn listen_command<'t, T, N>(
    topics: &'t [Topics],
    auth_token: T,
    nonce: N,
) -> Result<String, serde_json::Error>
where
    T: Into<Option<&'t str>>,
    N: Into<Option<&'t str>>,
{
    let topics = topics.iter().map(|t| t.to_string()).collect::<Vec<_>>();
    serde_json::to_string(&ITopicSubscribe {
        _type: "LISTEN",
        nonce: nonce.into(),
        data: ITopicSubscribeData {
            topics: &topics,
            auth_token: auth_token.into(),
        },
    })
}

/// Create a unlisten command.
///
/// # Examples
///
/// Unlisten from moderator actions and follows
///
/// ```rust
/// # use twitch_api::pubsub::{self, Topic as _};
/// // These are the exact same topics as for the `listen_command`.
/// let chat_mod_actions = pubsub::moderation::ChatModeratorActions {
///     user_id: 4321,
///     channel_id: 1234,
/// }
/// .into_topic();
///
/// let follows =
///     pubsub::following::Following { channel_id: 1234 }.into_topic();
/// // Create the command to send to twitch
/// let command = pubsub::unlisten_command(
///     &[chat_mod_actions, follows],
///     // This does not need to be the same nonce that was sent for listening.
///     // The nonce is only there to identify the payload and the response.
///     "super se3re7 random string",
/// )
/// .expect("serializing failed");
/// // Send the message with your favorite websocket client
/// send_command(command).unwrap();
/// // To parse the websocket messages, use pubsub::Response::parse
/// # fn send_command(command: String) -> Result<(),()> {Ok(())}
/// ```
pub fn unlisten_command<'t, O>(
    topics: &'t [Topics],
    nonce: O,
) -> Result<String, serde_json::Error>
where
    O: Into<Option<&'t str>>,
{
    let topics = topics.iter().map(|t| t.to_string()).collect::<Vec<_>>();
    serde_json::to_string(&ITopicSubscribe {
        _type: "UNLISTEN",
        nonce: nonce.into(),
        data: ITopicSubscribeData {
            topics: &topics,
            auth_token: None,
        },
    })
}

/// Response from twitch PubSub
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct TwitchResponse {
    /// The nonce that was passed in the request, if one was provided there
    pub nonce: Option<String>,
    /// The error message associated with the request, or an empty string if there is no error
    pub error: Option<String>,
}

impl TwitchResponse {
    /// Whether response indicates success or not
    pub fn is_successful(&self) -> bool { self.error.as_ref().map_or(true, |s| s.is_empty()) }
}

// FIXME: Add example
/// Message response from twitch PubSub.
///
/// See [TwitchResponse]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub enum TopicData {
    /// Response from the [automod_queue::AutoModQueue] topic.
    AutoModQueue {
        /// Topic message
        topic: automod_queue::AutoModQueue,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<automod_queue::AutoModQueueReply>,
    },
    /// Response from the [channel_bits::ChannelBitsEventsV2] topic.
    ChannelBitsEventsV2 {
        /// Topic message
        topic: channel_bits::ChannelBitsEventsV2,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_bits::ChannelBitsEventsV2Reply>,
    },
    /// Response from the [channel_bits_badge::ChannelBitsBadgeUnlocks] topic.
    ChannelBitsBadgeUnlocks {
        /// Topic message
        topic: channel_bits_badge::ChannelBitsBadgeUnlocks,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_bits_badge::ChannelBitsBadgeUnlocksReply>,
    },
    /// Response from the [moderation::ChatModeratorActions] topic.
    ChatModeratorActions {
        /// Topic message
        topic: moderation::ChatModeratorActions,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<moderation::ChatModeratorActionsReply>,
    },
    /// Response from the [channel_points::ChannelPointsChannelV1] topic.
    ChannelPointsChannelV1 {
        /// Topic message
        topic: channel_points::ChannelPointsChannelV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_points::ChannelPointsChannelV1Reply>,
    },
    /// Response from the [channel_subscriptions::ChannelSubscribeEventsV1] topic.
    ChannelSubscribeEventsV1 {
        /// Topic message
        topic: channel_subscriptions::ChannelSubscribeEventsV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_subscriptions::ChannelSubscribeEventsV1Reply>, // FIXME: :)
    },
    /// Response from the [community_points::CommunityPointsChannelV1] topic.
    #[cfg(feature = "unsupported")]
    CommunityPointsChannelV1 {
        /// Topic message
        topic: community_points::CommunityPointsChannelV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_points::ChannelPointsChannelV1Reply>,
    },
    /// Response from the [channel_cheer::ChannelCheerEventsPublicV1] topic.
    #[cfg(feature = "unsupported")]
    ChannelCheerEventsPublicV1 {
        /// Topic message
        topic: channel_cheer::ChannelCheerEventsPublicV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_cheer::ChannelCheerEventsPublicV1Reply>,
    },
    /// Response from the [channel_sub_gifts::ChannelSubGiftsV1] topic.
    #[cfg(feature = "unsupported")]
    ChannelSubGiftsV1 {
        /// Topic message
        topic: channel_sub_gifts::ChannelSubGiftsV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<channel_sub_gifts::ChannelSubGiftsV1Reply>,
    },

    /// Response from the [video_playback::VideoPlayback] topic.
    #[cfg(feature = "unsupported")]
    VideoPlayback {
        /// Topic message
        topic: video_playback::VideoPlayback,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<video_playback::VideoPlaybackReply>,
    },
    /// Response from the [video_playback::VideoPlaybackById] topic.
    #[cfg(feature = "unsupported")]
    VideoPlaybackById {
        /// Topic message
        topic: video_playback::VideoPlaybackById,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<video_playback::VideoPlaybackReply>,
    },
    /// Response from the [hypetrain::HypeTrainEventsV1] topic.
    #[cfg(feature = "unsupported")]
    HypeTrainEventsV1 {
        /// Topic message
        topic: hypetrain::HypeTrainEventsV1,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<hypetrain::HypeTrainEventsV1Reply>, // FIXME: May not be correct
    },
    /// Response from the [hypetrain::HypeTrainEventsV1Rewards] topic.
    #[cfg(feature = "unsupported")]
    HypeTrainEventsV1Rewards {
        /// Topic message
        topic: hypetrain::HypeTrainEventsV1Rewards,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<hypetrain::HypeTrainEventsV1Reply>,
    },
    /// Response from the [following::Following] topic.
    #[cfg(feature = "unsupported")]
    Following {
        /// Topic message
        topic: following::Following,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<following::FollowingReply>,
    },
    /// Response from the [raid::Raid] topic.
    #[cfg(feature = "unsupported")]
    Raid {
        /// Topic message
        topic: raid::Raid,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<raid::RaidReply>,
    },
    /// A user’s message held by AutoMod has been approved or denied.
    UserModerationNotifications {
        /// Topic message
        topic: user_moderation_notifications::UserModerationNotifications,
        /// Message reply from topic subscription
        #[serde(rename = "message")]
        reply: Box<user_moderation_notifications::UserModerationNotificationsReply>,
    },
}

// This impl is here because otherwise we hide the errors from deser
impl<'de> serde::Deserialize<'de> for TopicData {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // FIXME: make into macro or actually upstream into serde..., untagged_force = "field"

        #[derive(Deserialize, Debug)]
        struct ITopicData {
            topic: Topics,
            message: String,
        }
        let reply = ITopicData::deserialize(deserializer).map_err(|e| {
            serde::de::Error::custom(format!("could not deserialize topic reply: {e}"))
        })?;
        Ok(match reply.topic {
            Topics::AutoModQueue(topic) => Self::AutoModQueue {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::CommunityPointsChannelV1(topic) => Self::CommunityPointsChannelV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::ChannelBitsEventsV2(topic) => Self::ChannelBitsEventsV2 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::ChannelBitsBadgeUnlocks(topic) => Self::ChannelBitsBadgeUnlocks {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::ChannelSubGiftsV1(topic) => Self::ChannelSubGiftsV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::ChannelCheerEventsPublicV1(topic) => Self::ChannelCheerEventsPublicV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::ChatModeratorActions(topic) => Self::ChatModeratorActions {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::ChannelPointsChannelV1(topic) => Self::ChannelPointsChannelV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::ChannelSubscribeEventsV1(topic) => Self::ChannelSubscribeEventsV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::VideoPlayback(topic) => Self::VideoPlayback {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::VideoPlaybackById(topic) => Self::VideoPlaybackById {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::HypeTrainEventsV1(topic) => Self::HypeTrainEventsV1 {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::HypeTrainEventsV1Rewards(topic) => Self::HypeTrainEventsV1Rewards {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::Following(topic) => Self::Following {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            #[cfg(feature = "unsupported")]
            Topics::Raid(topic) => Self::Raid {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
            Topics::UserModerationNotifications(topic) => Self::UserModerationNotifications {
                topic,
                reply: parse_json(&reply.message, true).map_err(serde::de::Error::custom)?,
            },
        })
    }
}

/// Response from twitchs PubSub server.
/// Either a response indicating status of something or a message from a topic
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum Response {
    /// Response from a subscription/unsubscription
    #[serde(rename = "RESPONSE")]
    Response(TwitchResponse),
    /// Message received containing all applicable data
    #[serde(rename = "MESSAGE")]
    Message {
        /// Data corresponding to [topic](Topic) message
        data: TopicData,
    },
    /// Response from a ping
    #[serde(rename = "PONG")]
    Pong,
    /// Request for the client to reconnect
    #[serde(rename = "RECONNECT")]
    Reconnect,
}

impl Response {
    // FIXME: Add example
    /// Parse string slice as a response.
    pub fn parse(source: &str) -> Result<Self, crate::DeserError> { parse_json(source, true) }
}

/// Deserialize 'null' as <T as Default>::Default
fn deserialize_default_from_null<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: serde::Deserialize<'de> + Default, {
    use serde::Deserialize;

    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
}

/// Deserialize "" as <T as Default>::Default
fn deserialize_none_from_empty_string<'de, D, S>(deserializer: D) -> Result<Option<S>, D::Error>
where
    D: serde::Deserializer<'de>,
    S: serde::Deserialize<'de>, {
    use serde::de::IntoDeserializer;
    struct Inner<S>(std::marker::PhantomData<S>);
    impl<'de, S> serde::de::Visitor<'de> for Inner<S>
    where S: serde::Deserialize<'de>
    {
        type Value = Option<S>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("any string")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where E: serde::de::Error {
            match value {
                "" => Ok(None),
                v => S::deserialize(v.into_deserializer()).map(Some),
            }
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where E: serde::de::Error {
            match &*value {
                "" => Ok(None),
                v => S::deserialize(v.into_deserializer()).map(Some),
            }
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where E: serde::de::Error {
            Ok(None)
        }
    }

    deserializer.deserialize_any(Inner(std::marker::PhantomData))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn error() {
        let source = r#"
{
    "type": "RESPONSE",
    "nonce": "44h1k13746815ab1r2",
    "error": ""
}
"#;
        let expected = Response::Response(TwitchResponse {
            nonce: Some(String::from("44h1k13746815ab1r2")),
            error: Some(String::new()),
        });
        let actual = Response::parse(source).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn listen() {
        let topic =
            Topics::ChannelBitsEventsV2(channel_bits::ChannelBitsEventsV2 { channel_id: 12345 });
        let expected = r#"{"type":"LISTEN","nonce":"my nonce","data":{"topics":["channel-bits-events-v2.12345"],"auth_token":"my token"}}"#;
        let actual = listen_command(&[topic], "my token", "my nonce").expect("should serialize");
        assert_eq!(expected, actual);
    }

    #[test]
    fn unlisten() {
        let topic =
            Topics::ChannelBitsEventsV2(channel_bits::ChannelBitsEventsV2 { channel_id: 12345 });
        let expected = r#"{"type":"UNLISTEN","nonce":"my nonce","data":{"topics":["channel-bits-events-v2.12345"]}}"#;
        let actual = unlisten_command(&[topic], "my nonce").expect("should serialize");
        assert_eq!(expected, actual);
    }
}