libtwitch_rs/kraken/
users.rs

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
// This file was ((taken|adapted)|contains (data|code)) from twitch_api,
// Copyright 2017 Matt Shanker
// It's licensed under the Apache License, Version 2.0.
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// (Modifications|Other (data|code)|Everything else) Copyright 2019 the
// libtwitch-rs authors.  See copying.md for further legal info.

use chrono::prelude::*;

use super::{
    channels::Channel,
    chat::EmotesBySet,
};

use crate::{
    response::{
        ApiError,
        TwitchResult,
    },
    TwitchClient,
};

use serde::Deserialize;

use serde_json::Value;
use std::{
    self,
    collections::HashMap,
    io::Write,
};

/// Gets a user object based on the OAuth token provided
///
/// #### Authentication: `user_read`
pub fn get(c: &TwitchClient) -> TwitchResult<User> {
    let r = c.get::<User>("/user")?;
    Ok(r)
}

/// Gets a specified user object
///
/// #### Authentication: `None`
pub fn get_by_id(
    c: &TwitchClient,
    user_id: &str,
) -> TwitchResult<User>
{
    let r = c.get::<User>(&format!("/users/{}", user_id))?;
    Ok(r)
}

/// Gets a list of the emojis and emoticons that the specified user can use in
/// chat
///
/// These are both the globally available ones and
/// the channel-specific ones (which can be accessed
/// by any user subscribed to the channel).
///
/// #### Authentication: `user_subscriptions`
pub fn emotes(
    c: &TwitchClient,
    user_id: &str,
) -> TwitchResult<EmotesBySet>
{
    let r = c.get::<EmotesBySet>(&format!("/users/{}/emotes", user_id))?;
    Ok(r)
}

/// Checks if a specified user is subscribed to a specified channel
///
/// #### Authentication: `user_subscription`
pub fn subscription(
    c: &TwitchClient,
    user_id: &str,
    channel_id: &str,
) -> TwitchResult<UserSubFollow>
{
    let r = c.get::<UserSubFollow>(&format!(
        "/users/{}/subscriptions/{}",
        user_id, channel_id
    ))?;
    Ok(r)
}

/// Gets a list of all channels followed by a specified
/// user, sorted by the date when they started following each channel
///
/// #### Authentication: `None`
pub fn following<'c>(
    c: &'c TwitchClient,
    user_id: &str,
) -> TwitchResult<UserFollowIterator<'c>>
{
    let iter = UserFollowIterator {
        client: c,
        user_id: String::from(user_id),
        cur: None,
        offset: 0,
    };
    Ok(iter)
}

/// Checks if a specified user follows a specified channel
///
/// If the user is following the channel, a follow object is returned.
///
/// #### Authentication: `None`
pub fn is_following(
    c: &TwitchClient,
    user_id: &str,
    channel_id: &str,
) -> TwitchResult<Option<UserSubFollow>>
{
    let r = c.get::<UserSubFollow>(&format!(
        "/users/{}/follows/channels/{}",
        user_id, channel_id
    ));
    match r {
        Ok(r) => Ok(Some(r)),
        Err(e) => match e {
            ApiError::TwitchError(te) => {
                if te.status == 404 {
                    Ok(None)
                }
                else {
                    Err(ApiError::from(te))
                }
            }
            _ => Err(e),
        },
    }
}

/// Adds a specified user to the followers of a specified channel
///
/// #### Authentication: `user_follows_edit`
pub fn follow(
    c: &TwitchClient,
    user_id: &str,
    chan_id: &str,
    notifications: bool,
) -> TwitchResult<UserSubFollow>
{
    let mut data: HashMap<String, bool> = HashMap::new();
    data.insert("notifications".to_owned(), notifications);
    let r = c.put::<HashMap<String, bool>, UserSubFollow>(
        &format!("/users/{}/follows/channels/{}", user_id, chan_id),
        &data,
    )?;
    Ok(r)
}

/// Deletes a specified user from the followers of a specified channel
///
/// #### Authentication: `user_follows_edit`
pub fn unfollow(
    c: &TwitchClient,
    user_id: &str,
    chan_id: &str,
) -> TwitchResult<()>
{
    let r = c.delete::<()>(&format!(
        "/users/{}/follows/channels/{}",
        user_id, chan_id
    ));
    match r {
        Ok(_) => unreachable!(), // this should never happen
        Err(r) => match r {
            ApiError::EmptyResponse(_) => Ok(()),
            _ => Err(r),
        },
    }
}

/// Gets a user’s block list. List sorted by recency, newest first
///
/// #### Authentication: `user_blocks_read`
pub fn blocking<'c>(
    c: &'c TwitchClient,
    user_id: &str,
) -> TwitchResult<UserBlockIterator<'c>>
{
    let iter = UserBlockIterator {
        client: c,
        user_id: String::from(user_id),
        cur: None,
        offset: 0,
    };
    Ok(iter)
}

/// Blocks a user; that is, adds a specified target user
/// to the blocks list of a specified source user
///
/// #### Authentication: `user_blocks_edit`
pub fn block(
    c: &TwitchClient,
    src_user_id: &str,
    tgt_user_id: &str,
) -> TwitchResult<UserBlock>
{
    let r = c.put::<Value, UserBlock>(
        &format!("/users/{}/blocks/{}", src_user_id, tgt_user_id),
        &Value::Null,
    )?;
    Ok(r)
}

/// Unblocks a user; that is, deletes a specified target
/// user from the blocks list of a specified source user
///
/// There is an error if the target user is not on the
/// source user’s block list (404 Not Found) or the
/// delete failed (422 Unprocessable Entity).
///
/// #### Authentication: `user_blocks_edit`
pub fn unblock(
    c: &TwitchClient,
    src_user_id: &str,
    tgt_user_id: &str,
) -> TwitchResult<()>
{
    let r = c.delete::<()>(&format!(
        "/users/{}/blocks/{}",
        src_user_id, tgt_user_id
    ));
    match r {
        Ok(_) => unreachable!(), // this should never happen
        Err(r) => match r {
            ApiError::EmptyResponse(_) => Ok(()),
            _ => Err(r),
        },
    }
}

///////////////////////////////////////
// User
///////////////////////////////////////
#[derive(Deserialize, Debug)]
pub struct User {
    #[serde(rename = "_id")]
    pub id: i64,
    pub bio: String,
    pub created_at: DateTime<Utc>,
    pub display_name: String,
    pub email: Option<String>,
    pub email_verified: Option<bool>,
    pub logo: String,
    pub name: String,
    pub notifications: Option<UserNotifications>,
    #[serde(rename = "type")]
    pub _type: String,
    updated_at: DateTime<Utc>,
}

#[derive(Deserialize, Debug)]
pub struct UserSubFollow {
    pub channel: Channel,
    pub created_at: DateTime<Utc>,
    pub notifications: bool,
}

#[derive(Deserialize, Debug)]
pub struct UserNotifications {
    pub email: bool,
    pub push: bool,
}

#[derive(Deserialize, Debug)]
pub struct UserBlock {
    pub user: User,
}

///////////////////////////////////////
// User Iterators
///////////////////////////////////////
pub struct UserFollowIterator<'c> {
    client: &'c TwitchClient,
    user_id: String,
    cur: Option<SerdeUserFollows>,
    offset: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeUserFollows {
    pub follows: Vec<UserSubFollow>,
}

impl<'c> Iterator for UserFollowIterator<'c> {
    type Item = UserSubFollow;

    fn next(&mut self) -> Option<UserSubFollow> {
        let url = &format!(
            "/users/{}/follows/channels?limit=100&offset={}",
            &self.user_id, self.offset
        );
        next_result!(self, &url, SerdeUserFollows, follows)
    }
}

pub struct UserBlockIterator<'c> {
    client: &'c TwitchClient,
    user_id: String,
    cur: Option<SerdeUserBlocks>,
    offset: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeUserBlocks {
    pub blocks: Vec<UserBlock>,
}

impl<'c> Iterator for UserBlockIterator<'c> {
    type Item = UserBlock;

    fn next(&mut self) -> Option<UserBlock> {
        let url = &format!(
            "/users/{}/blocks?limit=100&offset={}",
            &self.user_id, self.offset
        );
        next_result!(self, &url, SerdeUserBlocks, blocks)
    }
}

///////////////////////////////////////
// TESTS
///////////////////////////////////////

#[cfg(test)]
mod tests {
    use crate::{
        new,
        response::ApiError,
        tests::{
            CLIENTID,
            TESTCH,
            TOKEN,
        },
    };

    #[test]
    fn user() {
        let mut c = new(String::from(CLIENTID));
        c.set_oauth_token(TOKEN);

        if let Some(user) = match super::get(&c) {
            Ok(r) => {
                assert!(r.email.is_some());
                Some(r)
            }
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
                None
            }
        } {
            let user_id = user.id.to_string();

            match super::get_by_id(&c, &user_id) {
                Ok(r) => assert_eq!(r.name, user.name),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::emotes(&c, &user_id) {
                Ok(r) => assert!(r.emoticon_sets.len() > 0),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::subscription(&c, &user_id, "1") {
                Ok(_r) => (),
                Err(r) => match r {
                    ApiError::TwitchError(e) => assert_eq!(e.status, 422),
                    _ => {
                        println!("{:?}", r);
                        assert!(false);
                    }
                },
            }
            // follow
            match super::follow(&c, &user_id, &TESTCH.to_string(), false) {
                Ok(r) => assert_eq!(r.channel.id, TESTCH),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::following(&c, &user_id) {
                Ok(mut r) => assert_eq!(r.next().unwrap().channel.id, TESTCH),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::is_following(&c, &user_id, &TESTCH.to_string()) {
                Ok(_r) => (),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::unfollow(&c, &user_id, &TESTCH.to_string()) {
                Ok(_r) => (),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::is_following(&c, &user_id, &TESTCH.to_string()) {
                Ok(r) => assert!(r.is_none()),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            // block
            match super::block(&c, &user_id, "1") {
                Ok(r) => assert_eq!(r.user.id, 1),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::blocking(&c, &user_id) {
                Ok(mut r) => assert_eq!(r.next().unwrap().user.id, 1),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::unblock(&c, &user_id, "1") {
                Ok(_r) => (),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
            match super::blocking(&c, &user_id) {
                Ok(mut r) => assert!(r.next().is_none()),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
        }
    }
}