libtwitch_rs/kraken/
communities.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
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
// 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 super::users::User;

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

use serde::Deserialize;

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

/// Gets a specified community
///
/// The name of the community is specified in
/// a required query-string parameter. It must
/// be 3-25 characters.
///
/// #### Authentication: `None`
pub fn get_by_name(
    c: &TwitchClient,
    name: &str,
) -> TwitchResult<Community>
{
    let r = c.get::<Community>(&format!("/communities?name={}", name))?;
    Ok(r)
}

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

/// Updates a specified community
///
/// #### Authentication: `communities_edit`
pub fn update<'a>(
    c: &TwitchClient,
    community_id: &str,
    data: &'a UpdateSettings,
) -> TwitchResult<Community>
{
    let mut settings: HashMap<String, &str> = HashMap::new();
    if let Some(summary) = data.summary {
        settings.insert("summary".to_owned(), summary);
    }
    if let Some(description) = data.description {
        settings.insert("description".to_owned(), description);
    }
    if let Some(rules) = data.rules {
        settings.insert("rules".to_owned(), rules);
    }
    if let Some(email) = data.email {
        settings.insert("email".to_owned(), email);
    }
    let r = c.put::<HashMap<String, &str>, Community>(
        &format!("/communities/{}", community_id),
        &settings,
    )?;
    Ok(r)
}

/// Gets a list of banned users for a specified community
///
/// #### Authentication: `communities_moderate`
pub fn bans<'c>(
    c: &'c TwitchClient,
    community_id: &str,
) -> TwitchResult<CommunityBanIterator<'c>>
{
    let iter = CommunityBanIterator {
        client: c,
        community_id: String::from(community_id),
        cur: None,
        cursor: None,
    };
    Ok(iter)
}

/// Adds a specified user to the ban list of a specified community
///
/// #### Authentication: `communities_moderate`
pub fn ban(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
) -> TwitchResult<Value>
{
    let r = c.put::<Value, Value>(
        &format!("/communities/{}/bans/{}", community_id, user_id),
        &Value::Null,
    )?;
    Ok(r)
}

/// Deletes a specified user from the ban list of a specified community
///
/// #### Authentication: `communities_moderate`
pub fn unban(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
) -> TwitchResult<Value>
{
    let r = c.delete::<Value>(&format!(
        "/communities/{}/bans/{}",
        community_id, user_id
    ))?;
    Ok(r)
}

/// Adds a specified image as the avatar of a specified community
///
/// #### Authentication: `communities_edit`
pub fn set_avatar_image(
    c: &TwitchClient,
    community_id: &str,
    avatar_img: &str,
) -> TwitchResult<Value>
{
    let mut data: HashMap<String, &str> = HashMap::new();
    data.insert("avatar_image".to_owned(), avatar_img);
    let r = c.post::<HashMap<String, &str>, Value>(
        &format!("/communities/{}/images/avatar", community_id),
        &data,
    )?;
    Ok(r)
}

/// Deletes the avatar image of a specified community
///
/// #### Authentication: `communities_edit`
pub fn delete_avatar_image(
    c: &TwitchClient,
    community_id: &str,
) -> TwitchResult<Value>
{
    let r = c.delete::<Value>(&format!(
        "/communities/{}/images/avatar",
        community_id
    ))?;
    Ok(r)
}

/// Adds a specified image as the cover image of a specified community
///
/// #### Authentication: `communities_edit`
pub fn set_cover_image(
    c: &TwitchClient,
    community_id: &str,
    cover_img: &str,
) -> TwitchResult<Value>
{
    let mut data: HashMap<String, &str> = HashMap::new();
    data.insert("cover_image".to_owned(), cover_img);
    let r = c.post::<HashMap<String, &str>, Value>(
        &format!("/communities/{}/images/cover", community_id),
        &data,
    )?;
    Ok(r)
}

/// Deletes the cover image of a specified community
///
/// #### Authentication: `communities_edit`
pub fn delete_cover_image(
    c: &TwitchClient,
    community_id: &str,
) -> TwitchResult<Value>
{
    let r = c.delete::<Value>(&format!(
        "/communities/{}/images/cover",
        community_id
    ))?;
    Ok(r)
}

/// Gets a list of moderators of a specified community
///
/// #### Authentication: `communities_edit`
pub fn moderators(
    c: &TwitchClient,
    community_id: &str,
) -> TwitchResult<Moderators>
{
    let r = c.get::<Moderators>(&format!(
        "/communities/{}/moderators",
        community_id
    ))?;
    Ok(r)
}

/// Adds a specified user to the list of moderators of a specified community
///
/// #### Authentication: `communities_edit`
pub fn new_moderator(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
) -> TwitchResult<Value>
{
    let r = c.put::<Value, Value>(
        &format!("/communities/{}/moderators/{}", community_id, user_id),
        &Value::Null,
    )?;
    Ok(r)
}

/// Deletes a specified user from the list of moderators of a specified
/// community
///
/// #### Authentication: `communities_edit`
pub fn delete_moderator(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
) -> TwitchResult<Value>
{
    let r = c.delete::<Value>(&format!(
        "/communities/{}/moderators/{}",
        community_id, user_id
    ))?;
    Ok(r)
}

/// Gets a list of actions users can perform in a specified community
///
/// #### Authentication: `Any`
pub fn permissions(
    c: &TwitchClient,
    community_id: &str,
) -> TwitchResult<HashMap<String, bool>>
{
    let r = c.get::<HashMap<String, bool>>(&format!(
        "/communities/{}/permissions",
        community_id
    ))?;
    Ok(r)
}

/// Reports a specified channel for violating the rules of a specified community
///
/// #### Authentication: `None`
pub fn report_channel(
    c: &TwitchClient,
    community_id: &str,
    channel_id: &str,
) -> TwitchResult<Value>
{
    let mut data: HashMap<String, &str> = HashMap::new();
    data.insert("channel_id".to_owned(), channel_id);
    let r = c.post::<HashMap<String, &str>, Value>(
        &format!("/communities/{}/report_channel", community_id),
        &data,
    )?;
    Ok(r)
}

/// Gets a list of users who are timed out in a specified community
///
/// #### Authentication: `communities_moderate`
pub fn timeouts<'c>(
    c: &'c TwitchClient,
    community_id: &str,
) -> TwitchResult<TimeoutIterator<'c>>
{
    let iter = TimeoutIterator {
        client: c,
        community_id: String::from(community_id),
        cur: None,
        cursor: None,
    };
    Ok(iter)
}

/// Adds a specified user to the timeout list of a specified community
///
/// #### Authentication: `communities_moderate`
pub fn timeout(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
    duration: i32,
    reason: Option<String>,
) -> TwitchResult<Value>
{
    let mut data: HashMap<String, String> = HashMap::new();
    data.insert("duration".to_owned(), duration.to_string());
    if let Some(reason) = reason {
        data.insert("reason".to_owned(), reason);
    }
    let r = c.put::<HashMap<String, String>, Value>(
        &format!("/communities/{}/timeouts/{}", community_id, user_id),
        &data,
    )?;
    Ok(r)
}

/// Deletes a specified user from the timeout list of a specified community
///
/// #### Authentication: `communities_moderate`
pub fn delete_timeout(
    c: &TwitchClient,
    community_id: &str,
    user_id: &str,
) -> TwitchResult<Value>
{
    let r = c.delete::<Value>(&format!(
        "/communities/{}/timeouts/{}",
        community_id, user_id
    ))?;
    Ok(r)
}

/// Gets the top communities by viewer count
///
/// #### Authentication: `None`
pub fn top(c: &TwitchClient) -> TwitchResult<TopCommunities> {
    let iter = TopCommunities {
        client: c,
        cur: None,
        cursor: None,
    };
    Ok(iter)
}

///////////////////////////////////////
// Community
///////////////////////////////////////
#[derive(Deserialize, Debug)]
pub struct Community {
    #[serde(rename = "_id")]
    pub id: String,
    pub avatar_image_url: String,
    pub cover_image_url: String,
    pub description: String,
    pub description_html: String,
    pub language: String,
    pub name: String,
    pub owner_id: String,
    pub rules: String,
    pub rules_html: String,
    pub summary: String,
}

pub struct UpdateSettings<'a> {
    pub summary: Option<&'a str>,
    pub description: Option<&'a str>,
    pub rules: Option<&'a str>,
    pub email: Option<&'a str>,
}

#[derive(Deserialize, Debug)]
pub struct Moderators {
    pub moderators: Vec<User>,
}

///////////////////////////////////////
// TopCommunities
///////////////////////////////////////
#[derive(Debug)]
pub struct TopCommunities<'c> {
    client: &'c TwitchClient,
    cur: Option<SerdeTopCommunities>,
    cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct TopCommunity {
    #[serde(rename = "_id")]
    pub id: String,
    pub avatar_image_url: String,
    pub channels: i32,
    pub name: String,
    pub viewers: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeTopCommunities {
    pub communities: Vec<TopCommunity>,
    pub _cursor: Option<String>,
}

impl<'c> Iterator for TopCommunities<'c> {
    type Item = TopCommunity;

    fn next(&mut self) -> Option<TopCommunity> {
        let url = "/communities/top?".to_string();
        next_result_cursor!(self, &url, SerdeTopCommunities, communities)
    }
}

///////////////////////////////////////
// Community Bans
///////////////////////////////////////
pub struct CommunityBanIterator<'c> {
    client: &'c TwitchClient,
    community_id: String,
    cur: Option<SerdeCommunityBan>,
    cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
struct SerdeCommunityBan {
    pub banned_users: Vec<CommunityBan>,
    pub _cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct CommunityBan {
    pub user_id: String,
    pub display_name: String,
    pub name: String,
    pub bio: Option<String>,
    pub avatar_image_url: Option<String>,
    pub start_timestamp: i64,
}

impl<'c> Iterator for CommunityBanIterator<'c> {
    type Item = CommunityBan;

    fn next(&mut self) -> Option<CommunityBan> {
        let url = format!("/communities/{}/bans?", &self.community_id);
        next_result_cursor!(self, &url, SerdeCommunityBan, banned_users)
    }
}

///////////////////////////////////////
// Community Timeouts
///////////////////////////////////////
pub struct TimeoutIterator<'c> {
    client: &'c TwitchClient,
    community_id: String,
    cur: Option<SerdeTimeout>,
    cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
struct SerdeTimeout {
    pub timed_out_users: Vec<TimeoutUser>,
    pub _cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct TimeoutUser {
    pub user_id: String,
    pub display_name: String,
    pub name: String,
    pub bio: Option<String>,
    pub avatar_image_url: Option<String>,
    pub start_timestamp: i64,
    pub end_timestamp: i64,
}

impl<'c> Iterator for TimeoutIterator<'c> {
    type Item = TimeoutUser;

    fn next(&mut self) -> Option<TimeoutUser> {
        let url = format!("/communities/{}/timeouts?", &self.community_id);
        next_result_cursor!(self, &url, SerdeTimeout, timed_out_users)
    }
}