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
// 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.

extern crate chrono;
extern crate serde_json;

use self::chrono::prelude::*;

use super::response::TwitchResult;
use super::users::User;
use super::TwitchClient;

use serde_json::Value;
use std;
use std::collections::HashMap;
use std::io::Write;

/// Gets a specified post from a specified channel feed
///
/// If authentication is provided, the user_ids
/// array in the response body contains the
/// requesting user’s ID, if they have reacted to a post.
///
/// #### Authentication: *Optional scope: any scope*
///
pub fn get_post(c: &TwitchClient, chan_id: &str, post_id: &str) -> TwitchResult<FeedPost> {
    let r = r#try!(c.get::<FeedPost>(&format!("/feed/{}/posts/{}", chan_id, post_id)));
    Ok(r)
}

/// Gets posts from a specified channel feed
///
/// If authentication is provided, the user_ids
/// array in the response body contains the
/// requesting user’s ID, if they have reacted to a post.
///
/// #### Authentication: *Optional scope: any scope*
///
pub fn get_posts<'c>(c: &'c TwitchClient, chan_id: &str) -> TwitchResult<FeedPosts<'c>> {
    let iter = FeedPosts {
        client: c,
        chan_id: String::from(chan_id),
        cur: None,
        cursor: None,
    };
    Ok(iter)
}

/// Creates a post in a specified channel feed
///
/// # Arguments
///
/// * `data` - Text of the post
///
/// #### Authentication: `channel_feed_edit`
///
pub fn new_post(c: &TwitchClient, chan_id: &str, data: &str) -> TwitchResult<NewFeedPostResponse> {
    let r = r#try!(c.post::<NewContent, NewFeedPostResponse>(
        &format!("/feed/{}/posts", chan_id),
        &NewContent { content: data },
    ));
    Ok(r)
}

/// Deletes a specified post in a specified channel feed
///
/// #### Authentication: `channel_feed_edit`
///
pub fn delete_post(c: &TwitchClient, chan_id: &str, post_id: &str) -> TwitchResult<FeedPost> {
    let r = r#try!(c.delete::<FeedPost>(&format!("/feed/{}/posts/{}", chan_id, post_id)));
    Ok(r)
}

/// Creates a reaction to a specified post in a specified channel feed
///
/// The reaction is specified by an emote value, which is
/// either an ID (for example, “25” is Kappa) or the string
/// “endorse” (which corresponds to a default face emote).
///
/// #### Authentication: `channel_feed_edit`
///
pub fn new_post_reaction(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    emote_id: &str,
) -> TwitchResult<NewReactionResponse> {
    let r = r#try!(c.post::<Value, NewReactionResponse>(
        &format!(
            "/feed/{}/posts/{}/reactions?emote_id={}",
            chan_id, post_id, emote_id
        ),
        &Value::Null
    ));
    Ok(r)
}

/// Deletes a specified reaction to a specified post in a specified channel feed
///
/// The reaction is specified by an emote ID (for example,
/// “25” is Kappa) or the string “endorse” (which corresponds
/// to a default face emote).
///
/// #### Authentication: `channel_feed_edit`
///
pub fn delete_post_reaction(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    emote_id: &str,
) -> TwitchResult<DelReactionResponse> {
    let r = r#try!(c.delete::<DelReactionResponse>(&format!(
        "/feed/{}/posts/{}/reactions?emote_id={}",
        chan_id, post_id, emote_id
    )));
    Ok(r)
}

/// Gets all comments on a specified post in a specified channel feed
///
/// If authentication is provided, the permissions for
/// the comment are returned in the response; otherwise,
/// no permissions are returned.
///
/// #### Authentication: *Optional scope: any scope*
///
pub fn get_comments<'c>(
    c: &'c TwitchClient,
    chan_id: &str,
    post_id: &str,
) -> TwitchResult<FeedPostCommentIterator<'c>> {
    let iter = FeedPostCommentIterator {
        client: c,
        chan_id: String::from(chan_id),
        post_id: String::from(post_id),
        cur: None,
        cursor: None,
    };
    Ok(iter)
}

/// Creates a comment to a specified post in a specified channel feed
///
/// # Arguments
///
/// * `data` - Text of the comment
///
/// #### Authentication: `channel_feed_edit`
///
pub fn new_comment(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    data: &str,
) -> TwitchResult<FeedPostComment> {
    let r = r#try!(c.post::<NewContent, FeedPostComment>(
        &format!("/feed/{}/posts/{}/comments", chan_id, post_id),
        &NewContent { content: data }
    ));
    Ok(r)
}

/// Deletes a specified comment on a specified post in a specified channel feed
///
/// #### Authentication: `channel_feed_edit`
///
pub fn delete_comment(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    comment_id: &str,
) -> TwitchResult<FeedPostComment> {
    let r = r#try!(c.delete::<FeedPostComment>(&format!(
        "/feed/{}/posts/{}/comments/{}",
        chan_id, post_id, comment_id
    )));
    Ok(r)
}

/// Creates a reaction to a specified comment on a specified post in a specified channel feed
///
/// The reaction is specified by an emote value, which
/// is either an ID (for example, “25” is Kappa) or the
/// string “endorse” (which corresponds to a default
/// face emote).
///
/// #### Authentication: `channel_feed_edit`
///
pub fn new_comment_reaction(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    comment_id: &str,
) -> TwitchResult<NewReactionResponse> {
    let r = r#try!(c.post::<Value, NewReactionResponse>(
        &format!(
            "/feed/{}/posts/{}/comments/{}/reactions?emote_id=endorse",
            chan_id, post_id, comment_id
        ),
        &Value::Null
    ));
    Ok(r)
}

/// Deletes a reaction to a specified comment on a specified post in a specified channel feed
///
/// The reaction is specified by an emote value, which
/// is either an ID (for example, “25” is Kappa) or the
/// string “endorse” (which corresponds to a default
/// face emote).
///
/// #### Authentication: `channel_feed_edit`
///
pub fn delete_comment_reaction(
    c: &TwitchClient,
    chan_id: &str,
    post_id: &str,
    comment_id: &str,
) -> TwitchResult<DelReactionResponse> {
    let r = r#try!(c.delete::<DelReactionResponse>(&format!(
        "/feed/{}/posts/{}/comments/{}/reactions?emote_id=endorse",
        chan_id, post_id, comment_id
    )));
    Ok(r)
}

///////////////////////////////////////
// FeedPost definitions
///////////////////////////////////////
#[derive(Deserialize, Debug)]
pub struct FeedPost {
    pub body: String,
    pub comments: Option<SerdeFeedPostComments>,
    pub created_at: DateTime<UTC>,
    pub deleted: Option<bool>,
    pub embeds: Option<Vec<Value>>,
    pub emotes: Option<Vec<Value>>,
    pub id: String,
    pub permissions: Option<FeedPostPermissions>,
    pub reactions: Option<HashMap<String, Value>>,
    pub user: Option<User>,
}

#[derive(Deserialize, Debug)]
pub struct FeedPostPermissions {
    pub can_delete: bool,
    pub can_moderate: bool,
    pub can_reply: bool,
}

#[derive(Deserialize, Debug)]
pub struct FeedPostCommentPermissions {
    pub can_delete: bool,
}

#[derive(Deserialize, Debug)]
pub struct FeedPostEmotes {
    pub start: i32,
    pub end: i32,
    pub id: i64,
    pub set: i64,
}

#[derive(Serialize, Debug)]
pub struct NewContent<'a> {
    pub content: &'a str,
}

#[derive(Deserialize, Debug)]
pub struct NewFeedPostResponse {
    pub post: FeedPost,
    pub tweet: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct NewReactionResponse {
    pub created_at: DateTime<UTC>,
    pub emote_id: String,
    pub id: String,
    pub user: Option<User>,
}

#[derive(Deserialize, Debug)]
pub struct DelReactionResponse {
    pub deleted: bool,
}

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

impl<'c> Iterator for FeedPosts<'c> {
    type Item = FeedPost;

    fn next(&mut self) -> Option<FeedPost> {
        let url = format!("/feed/{}/posts?", &self.chan_id);
        next_result_cursor!(self, &url, SerdeFeedPosts, posts)
    }
}

#[derive(Deserialize, Debug)]
struct SerdeFeedPosts {
    pub posts: Vec<FeedPost>,
    pub _cursor: Option<String>,
}

///////////////////////////////////////
// FeedPostComments
///////////////////////////////////////
#[derive(Debug)]
pub struct FeedPostCommentIterator<'c> {
    client: &'c TwitchClient,
    chan_id: String,
    post_id: String,
    cur: Option<SerdeFeedPostComments>,
    cursor: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct FeedPostComment {
    pub body: String,
    pub created_at: DateTime<UTC>,
    pub deleted: bool,
    pub emotes: Vec<FeedPostEmotes>,
    pub id: String,
    pub permissions: Option<FeedPostCommentPermissions>,
    pub reactions: HashMap<String, Value>,
    pub user: User,
}

#[derive(Deserialize, Debug)]
pub struct SerdeFeedPostComments {
    pub _total: i32,
    pub _cursor: Option<String>,
    pub comments: Vec<FeedPostComment>,
}

impl<'c> Iterator for FeedPostCommentIterator<'c> {
    type Item = FeedPostComment;

    fn next(&mut self) -> Option<FeedPostComment> {
        let url = format!("/feed/{}/posts/{}/comments?", &self.chan_id, &self.post_id);
        next_result_cursor!(self, &url, SerdeFeedPostComments, comments)
    }
}

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

#[cfg(test)]
mod tests {
    use super::super::new;

    use super::super::tests::{CHANID, CLIENTID, TOKEN};

    use super::*;

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

        // create post
        match new_post(&c, CHANID, "channel_feed::tests::FeedPost") {
            Ok(r) => assert_eq!(r.post.body, "channel_feed::tests::FeedPost"),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        };

        // count posts
        match get_posts(&c, CHANID) {
            Ok(r) => assert!(r.count() > 0),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        }

        // create post reactions
        for post in get_posts(&c, CHANID).unwrap() {
            match new_post_reaction(&c, CHANID, &post.id, "25") {
                Ok(_r) => (),
                Err(_r) => assert!(false),
            }
        }

        // read and delete post reactions
        for post in get_posts(&c, CHANID).unwrap() {
            match post.reactions.expect("no reactions for post").get("25") {
                Some(_r) => (),
                None => assert!(false),
            }

            match delete_post_reaction(&c, CHANID, &post.id, "25") {
                Ok(r) => assert!(r.deleted),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
        }

        // count post reactions
        for post in get_posts(&c, CHANID).unwrap() {
            // count reactions
            assert!(
                post.reactions
                    .expect("no reactions for post")
                    .keys()
                    .count()
                    == 0
            );
        }

        // delete posts
        for post in get_posts(&c, CHANID).unwrap() {
            match delete_post(&c, CHANID, &post.id) {
                Ok(r) => assert!(r.id == post.id && r.deleted.unwrap() == true),
                Err(r) => {
                    println!("{:?}", r);
                    assert!(false);
                }
            }
        }

        // count posts
        match get_posts(&c, CHANID) {
            Ok(r) => assert!(r.count() == 0),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        }
    }

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

        // create post
        if let Ok(r) = new_post(&c, CHANID, "channel_feed::tests::FeedPostComment") {
            let post = r.post;

            // create comment
            if let Ok(comment) = new_comment(
                &c,
                CHANID,
                &post.id,
                "channel_feed::tests::FeedPostComment comment",
            ) {
                // create comment reaction
                match new_comment_reaction(&c, CHANID, &post.id, &comment.id) {
                    Ok(_r) => (),
                    Err(r) => {
                        println!("{:?}", r);
                        assert!(false);
                    }
                };

                // delete comment reaction
                match delete_comment_reaction(&c, CHANID, &post.id, &comment.id) {
                    Ok(r) => assert_eq!(r.deleted, true),
                    Err(r) => {
                        println!("{:?}", r);
                        assert!(false);
                    }
                }

                // delete comment
                match delete_comment(&c, CHANID, &post.id, &comment.id) {
                    Ok(r) => assert_eq!(r.deleted, true),
                    Err(r) => {
                        println!("{:?}", r);
                        assert!(false);
                    }
                }
            } else {
                assert!(false);
            }

            // delete post
            for post in get_posts(&c, CHANID).unwrap() {
                match delete_post(&c, CHANID, &post.id) {
                    Ok(_r) => (),
                    Err(r) => {
                        println!("{:?}", r);
                        assert!(false);
                    }
                }
            }
        } else {
            assert!(false);
        }
    }
}