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
#![doc(alias = "points")]
#![doc(alias = "channel-points-channel-v1")]
//! PubSub messages for channel points
use crate::{pubsub, types};
use serde_derive::{Deserialize, Serialize};

/// A user redeems an reward using channel points.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(into = "String", try_from = "String")]
pub struct ChannelPointsChannelV1 {
    /// The channel_id to watch. Can be fetched with the [Get Users](crate::helix::users::get_users) endpoint
    pub channel_id: u32,
}

impl_de_ser!(
    ChannelPointsChannelV1,
    "channel-points-channel-v1",
    channel_id // FIXME: add trailing comma
);

impl pubsub::Topic for ChannelPointsChannelV1 {
    #[cfg(feature = "twitch_oauth2")]
    const SCOPE: twitch_oauth2::Validator = twitch_oauth2::validator![];

    fn into_topic(self) -> pubsub::Topics { super::Topics::ChannelPointsChannelV1(self) }
}

/// A redemption users can "buy" with channel points to trigger rewards
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct Redemption {
    /// ID of channel where the redemption was triggered
    pub channel_id: types::UserId,
    /// ID of the redemption. Also returned in twitch IRC
    pub id: types::RedemptionId,
    /// Timestamp in which a reward was redeemed
    pub redeemed_at: types::Timestamp,
    /// Data about the reward that was redeemed
    pub reward: Reward,
    /// reward redemption status, will be FULFILLED if a user skips the reward queue, UNFULFILLED otherwise. ACTION_TAKEN is for `redemption-status-update`
    pub status: RedemptionStatus,
    /// User that triggered the reward
    pub user: types::User,
    /// A string that the user entered if the reward requires input
    pub user_input: Option<String>,
    /// A cursor for something
    pub cursor: Option<String>,
}

/// Status for redemption
///
/// # Note
///
/// It is currently not possible to see if a unfullfilled redemption has been fullfilled.
/// Currently only [`ACTION_TAKEN`](RedemptionStatus::ActionTaken) is given on queue changes
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum RedemptionStatus {
    /// Redemption was fullfilled, e.g it skipped reward queue
    Fulfilled,
    /// Redemption is not fullfilled, e.g is in reward queue.
    Unfulfilled,
    // FIXME: https://github.com/twitchdev/issues/issues/111
    /// Redemption was updated. Rejected or completed
    #[serde(rename = "ACTION_TAKEN")]
    ActionTaken,
}

/// Reward data
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct Reward {
    /// Color of background in rewards & challenges screen on client
    pub background_color: String,
    /// ID of channel where the redemption was triggered
    pub channel_id: types::UserId,
    /// Cooldown will expire after this timestamp
    pub cooldown_expires_at: Option<types::Timestamp>,
    /// Cost of reward.
    pub cost: u32,
    /// Default image of reward in rewards & challenges screen on client
    pub default_image: Option<types::Image>,
    /// Information about global cooldown
    pub global_cooldown: types::GlobalCooldown,
    /// ID of reward.
    pub id: types::RewardId,
    /// Set image of reward in rewards & challenges screen on client. If none, see [`Reward::default_image`]
    pub image: Option<types::Image>,
    /// Reward is enabled or not.
    pub is_enabled: bool,
    /// Reward is in stock
    pub is_in_stock: bool,
    /// Reward is paused
    pub is_paused: bool,
    /// Reward is sub only
    pub is_sub_only: bool,
    /// Reward requires input from user on rewards & challenges screen on client
    pub is_user_input_required: bool,
    /// Maximum redemptions per stream
    pub max_per_stream: types::Max,
    /// Maximum redemptions per user per stream
    pub max_per_user_per_stream: types::Max,
    /// Prompt shown when clicking reward on rewards & challenges screen on client
    pub prompt: String,
    // TODO: Is this fullfilled redemptions or is it x + 1 ? where 1 is this reward redemption
    /// Amount of times this has been redeemed this stream.
    pub redemptions_redeemed_current_stream: Option<u32>,
    /// Does redemption skip queue?
    pub should_redemptions_skip_request_queue: bool,
    /// Template ID
    pub template_id: Option<String>,
    /// Title or Name of reward
    pub title: String,
    /// Unknown
    pub updated_for_indicator_at: Option<types::Timestamp>,
}

/// `update-redemption-statuses-finished``progress
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub struct Progress {
    /// ID of channel user
    pub channel_id: types::UserId,
    /// BASE64 representation of reward
    pub id: String,
    /// Method by which redemptions were set to new status
    // FIXME: BY_CHANNEL etc, need to enumify
    pub method: String,
    /// New status of redemptions
    pub new_status: RedemptionStatus,
    /// Total amount of redemptions changed
    pub processed: i64,
    /// Total redemptions
    // FIXME: What is this?
    pub total: i64,
}

/// Reply from [ChannelPointsChannelV1]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", content = "data")]
#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
#[non_exhaustive]
pub enum ChannelPointsChannelV1Reply {
    /// A reward was redeemed
    #[serde(rename = "reward-redeemed")]
    RewardRedeemed {
        /// Time the pubsub message was sent
        timestamp: String,
        /// Data about the redemption, includes unique id and user that redeemed it
        redemption: Redemption,
    },
    /// A custom reward was updated
    #[serde(rename = "custom-reward-updated")]
    CustomRewardUpdated {
        /// Time the pubsub message was sent
        timestamp: String,
        /// Data about the reward that was updated
        updated_reward: Reward,
    },
    /// Status of a redemption was changed
    #[serde(rename = "redemption-status-update")]
    RedemptionStatusUpdate {
        /// Time the pubsub message was sent
        timestamp: String,
        /// Data about the reward that had status updated
        redemption: Redemption,
    },
    /// Status of multiple redemptions were changed
    // TODO: This seems to only be on complete all / reject all
    #[serde(rename = "update-redemption-statuses-finished")]
    UpdateRedemptionStatusesFinished {
        /// Time the pubsub message was sent
        timestamp: String,
        /// Data about the reward that had status updated
        progress: Progress,
    },
    /// Status of multiple redemptions were changed
    // FIXME: No idea what this is, might be same as UpdateRedemptionStatusesFinished
    #[serde(rename = "update-redemption-statuses-progress")]
    UpdateRedemptionStatusProgress {
        /// Time the pubsub message was sent
        timestamp: String,
        /// Data about the reward that had status updated
        progress: Progress,
    },
}

#[cfg(test)]
mod tests {
    use super::super::{Response, TopicData};
    use super::*;
    #[test]
    fn channel_point_redeem() {
        let message = r##"
{
    "type": "reward-redeemed",
    "data": {
        "timestamp": "2020-10-10T19:13:30.536153182Z",
        "redemption": {
            "id": "b021f290-bedb-49c2-b90f-e6ceb1c0d4ab",
            "user": {
                "id": "27620241",
                "login": "emilgardis",
                "display_name": "emilgardis"
            },
            "channel_id": "27620241",
            "redeemed_at": "2020-10-10T19:13:30.536153182Z",
            "reward": {
                "id": "252e209d-4f16-4886-a0d1-97f458ad5698",
                "channel_id": "27620241",
                "title": "Hydration",
                "prompt": "Make Emilgardis drink water",
                "cost": 2000,
                "is_user_input_required": true,
                "is_sub_only": false,
                "image": null,
                "default_image": {
                    "url_1x": "https://static-cdn.jtvnw.net/custom-reward-images/default-1.png",
                    "url_2x": "https://static-cdn.jtvnw.net/custom-reward-images/default-2.png",
                    "url_4x": "https://static-cdn.jtvnw.net/custom-reward-images/default-4.png"
                },
                "background_color": "#81AEFF",
                "is_enabled": true,
                "is_paused": false,
                "is_in_stock": true,
                "max_per_stream": {
                    "is_enabled": false,
                    "max_per_stream": 10
                },
                "should_redemptions_skip_request_queue": false,
                "template_id": null,
                "updated_for_indicator_at": "2020-02-06T17:29:19.737311439Z",
                "max_per_user_per_stream": {
                    "is_enabled": false,
                    "max_per_user_per_stream": 0
                },
                "global_cooldown": {
                    "is_enabled": false,
                    "global_cooldown_seconds": 0
                },
                "redemptions_redeemed_current_stream": 0,
                "cooldown_expires_at": null
            },
            "user_input": "bap",
            "status": "UNFULFILLED"
        }
    }
}
"##;

        let source = format!(
            r#"{{"type": "MESSAGE","data": {{ "topic": "channel-points-channel-v1.27620241", "message": {message:?} }}}}"#
        );
        let actual = dbg!(Response::parse(&source).unwrap());
        assert!(matches!(
            actual,
            Response::Message {
                data: TopicData::ChannelPointsChannelV1 { .. },
            }
        ));
    }

    #[test]
    fn channel_reward_updated() {
        let message = r##"
{
    "type": "custom-reward-updated",
    "data": {
        "timestamp": "2020-10-19T19:40:19.637568468Z",
        "updated_reward": {
            "id": "071397fb-cd09-420d-8d64-f9fd35f5cdfa",
            "channel_id": "27620241",
            "title": "Up the difficulty ",
            "prompt": "stuff.",
            "cost": 20000,
            "is_user_input_required": true,
            "is_sub_only": false,
            "image": null,
            "default_image": {
                "url_1x": "https://static-cdn.jtvnw.net/custom-reward-images/default-1.png",
                "url_2x": "https://static-cdn.jtvnw.net/custom-reward-images/default-2.png",
                "url_4x": "https://static-cdn.jtvnw.net/custom-reward-images/default-4.png"
            },
            "background_color": "#FF6C00",
            "is_enabled": true,
            "is_paused": true,
            "is_in_stock": true,
            "max_per_stream": {
                "is_enabled": true,
                "max_per_stream": 6
            },
            "should_redemptions_skip_request_queue": false,
            "template_id": null,
            "updated_for_indicator_at": "2020-06-09T16:02:06.943429808Z",
            "max_per_user_per_stream": {
                "is_enabled": false,
                "max_per_user_per_stream": 0
            },
            "global_cooldown": {
                "is_enabled": false,
                "global_cooldown_seconds": 0
            },
            "redemptions_redeemed_current_stream": 0,
            "cooldown_expires_at": null
        }
    }
}
        "##;

        let source = format!(
            r#"{{"type": "MESSAGE","data": {{ "topic": "channel-points-channel-v1.27620241", "message": {message:?} }}}}"#
        );
        let actual = dbg!(Response::parse(&source).unwrap());
        assert!(matches!(
            actual,
            Response::Message {
                data: TopicData::ChannelPointsChannelV1 { .. },
            }
        ));
    }

    #[test]
    fn redemption_status_update() {
        let message = r##"
{
    "type": "redemption-status-update",
    "data": {
        "timestamp": "2020-10-19T19:41:00.590084358Z",
        "redemption": {
            "id": "844fff0c-6185-44c7-8c30-3d68a565fe1b",
            "user": {
                "id": "27620241",
                "login": "emilgardis",
                "display_name": "emilgardis"
            },
            "channel_id": "27620241",
            "redeemed_at": "2020-10-19T15:01:18.453334233Z",
            "reward": {
                "id": "252e209d-4f16-4886-a0d1-97f458ad5698",
                "channel_id": "27620241",
                "title": "Hydration",
                "prompt": "Make Emilgardis drink water",
                "cost": 2000,
                "is_user_input_required": false,
                "is_sub_only": false,
                "image": null,
                "default_image": null,
                "background_color": "#81AEFF",
                "is_enabled": false,
                "is_paused": false,
                "is_in_stock": false,
                "max_per_stream": {
                    "is_enabled": false,
                    "max_per_stream": 0
                },
                "should_redemptions_skip_request_queue": false,
                "template_id": null,
                "updated_for_indicator_at": null,
                "max_per_user_per_stream": {
                    "is_enabled": false,
                    "max_per_user_per_stream": 0
                },
                "global_cooldown": {
                    "is_enabled": false,
                    "global_cooldown_seconds": 0
                },
                "redemptions_redeemed_current_stream": null,
                "cooldown_expires_at": null
            },
            "user_input": "a",
            "status": "ACTION_TAKEN",
            "cursor": "ODQ0ZmZmMGMtNjE4NS00NGM3LThjMzAtM2Q2OGE1NjVmZTFiX18yMDIwLTEwLTE5VDE1OjAxOjE4LjQ1MzMzNDIzM1o="
        }
    }
}
        "##;

        let source = format!(
            r#"{{"type": "MESSAGE","data": {{ "topic": "channel-points-channel-v1.27620241", "message": {message:?} }}}}"#
        );
        let actual = dbg!(Response::parse(&source).unwrap());
        assert!(matches!(
            actual,
            Response::Message {
                data: TopicData::ChannelPointsChannelV1 { .. },
            }
        ));
    }

    #[test]
    fn update_redemption_statuses_finished() {
        let message = r##"
{
    "type": "update-redemption-statuses-finished",
    "data": {
        "timestamp": "2021-02-15T00:36:55.938819818Z",
        "progress": {
            "id": "Y29wb0J1bGtFZGl0UmVkZW1wdGlvblN0YXR1c1Byb2dyZXNzOjEzMzc6QlVMS19FRElUX1JFREVNUFRJT05fU1RBVFVTX01FVEhPRF9CWV9DSEFOTkVMOg==",
            "channel_id": "1337",
            "method": "BY_CHANNEL",
            "new_status": "FULFILLED",
            "processed": 2,
            "total": 2
        }
    }
}
        "##;

        let source = format!(
            r#"{{"type": "MESSAGE","data": {{ "topic": "channel-points-channel-v1.27620241", "message": {message:?} }}}}"#
        );
        let actual = dbg!(Response::parse(&source).unwrap());
        assert!(matches!(
            actual,
            Response::Message {
                data: TopicData::ChannelPointsChannelV1 { .. },
            }
        ));
    }

    #[test]
    fn update_redemption_statuses_progress() {
        let message = r##"
{
    "type": "update-redemption-statuses-progress",
    "data": {
        "timestamp": "2021-02-15T00:36:55.916689548Z",
        "progress": {
            "id": "Y29wb0J1bGtFZGl0UmVkZW1wdGlvblN0YXR1c1Byb2dyZXNzOjEzMzc6QlVMS19FRElUX1JFREVNUFRJT05fU1RBVFVTX01FVEhPRF9CWV9DSEFOTkVMOg==",
            "channel_id": "1337",
            "method": "BY_CHANNEL",
            "new_status": "FULFILLED",
            "processed": 1,
            "total": 2
        }
    }
}
        "##;

        let source = format!(
            r#"{{"type": "MESSAGE","data": {{ "topic": "channel-points-channel-v1.27620241", "message": {message:?} }}}}"#
        );
        let actual = dbg!(Response::parse(&source).unwrap());
        assert!(matches!(
            actual,
            Response::Message {
                data: TopicData::ChannelPointsChannelV1 { .. },
            }
        ));
    }

    #[test]
    fn check_deser() {
        use std::convert::TryInto as _;
        let s = "channel-points-channel-v1.1234";
        assert_eq!(
            ChannelPointsChannelV1 { channel_id: 1234 },
            s.to_string().try_into().unwrap()
        );
    }

    #[test]
    fn check_ser() {
        let s = "channel-points-channel-v1.1234";
        let right: String = ChannelPointsChannelV1 { channel_id: 1234 }.into();
        assert_eq!(s.to_string(), right);
    }
}