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
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Structs and functions for working with statuses and timelines.
//!
//! In this module, you can find various structs and methods to load and interact with tweets and
//! their metadata. This also includes loading a user's timeline, posting a new tweet, or liking or
//! retweeting another tweet. However, this does *not* include searching for tweets; that
//! functionality is in the [`search`][] module.
//!
//! [`search`]: ../search/index.html
//!
//! ## Types
//!
//! - `Tweet`/`TweetEntities`/`ExtendedTweetEntities`: At the bottom of it all, this is the struct
//!   that represents a single tweet. The `*Entities` structs contain information about media,
//!   links, and hashtags within their parent tweet.
//! - `DraftTweet`: This is what you use to post a new tweet. At present, not all available options
//!   are supported, but basics like marking the tweet as a reply and attaching a location
//!   coordinate are available.
//! - `Timeline`: Returned by several functions in this module, this is how you cursor through a
//!   collection of tweets. See the struct-level documentation for details.
//!
//! ## Functions
//!
//! ### User actions
//!
//! These functions perform actions on their given tweets. They require write access to the
//! authenticated user's account.
//!
//! - `delete` (for creating a tweet, see `DraftTweet`)
//! - `like`/`unlike`
//! - `retweet`/`unretweet`
//!
//! ### Metadata lookup
//!
//! These functions either perform some direct lookup of specific tweets, or provide some metadata
//! about the given tweet in a direct (non-`Timeline`) fashion.
//!
//! - `show`
//! - `lookup`/`lookup_map` (for the differences between these functions, see their respective
//!   documentations.)
//! - `retweeters_of`
//! - `retweets_of`
//!
//! ### `Timeline` cursors
//!
//! These functions return `Timeline`s and can be cursored around in the same way. See the
//! documentation for `Timeline` to learn how to navigate these return values. This correspond to a
//! user's own view of Twitter, or with feeds you might see attached to a user's profile page.
//!
//! - `home_timeline`/`mentions_timeline`/`retweets_of_me`
//! - `user_timeline`/`liked_by`

use std::borrow::Cow;
use std::convert::TryFrom;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;
use std::task::{Context, Poll};

use chrono;
use hyper::{Body, Request};
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};

use crate::common::*;
use crate::error::{Error::InvalidResponse, Result};
use crate::stream::FilterLevel;
use crate::{auth, entities, error, links, media, place, user};

mod fun;
mod raw;

pub use self::fun::*;

round_trip! { raw::RawTweet,
    ///Represents a single status update.
    ///
    ///The fields present in this struct can be mainly split up based on the context they're present
    ///for.
    ///
    ///## Base Tweet Info
    ///
    ///This information is the basic information inherent to all tweets, regardless of context.
    ///
    ///* `text`
    ///* `id`
    ///* `created_at`
    ///* `user`
    ///* `source`
    ///* `favorite_count`/`retweet_count`
    ///* `lang`, though third-party clients usually don't surface this at a user-interface level.
    ///  Twitter Web uses this to create machine-translations of the tweet.
    ///* `coordinates`/`place`
    ///* `display_text_range`
    ///* `truncated`
    ///
    ///## Perspective-based data
    ///
    ///This information depends on the authenticated user who called the data. These are left as
    ///Options because certain contexts where the information is pulled either don't have an
    ///authenticated user to compare with, or don't have to opportunity to poll the user's interactions
    ///with the tweet.
    ///
    ///* `favorited`
    ///* `retweeted`
    ///* `current_user_retweet`
    ///
    ///## Replies
    ///
    ///This information is only present when the tweet in question is marked as being a reply to
    ///another tweet, or when it's threaded into a chain from the same user.
    ///
    ///* `in_reply_to_user_id`/`in_reply_to_screen_name`
    ///* `in_reply_to_status_id`
    ///
    ///## Retweets and Quote Tweets
    ///
    ///This information is only present when the tweet in question is a native retweet or is a "quote
    ///tweet" that references another tweet by linking to it. These fields allow you to reference the
    ///parent tweet without having to make another call to `show`.
    ///
    ///* `retweeted_status`
    ///* `quoted_status`/`quoted_status_id`
    ///
    ///## Media
    ///
    ///As a tweet can attach an image, GIF, or video, these fields allow you to access information
    ///about the attached media. Note that polls are not surfaced to the Public API at the time of this
    ///writing (2016-09-01). For more information about how to use attached media, see the
    ///documentation for [`MediaEntity`][].
    ///
    ///[`MediaEntity`]: ../entities/struct.MediaEntity.html
    ///
    ///* `entities` (note that this also contains information about hyperlinks, user mentions, and
    ///  hashtags in addition to a picture/thumbnail)
    ///* `extended_entities`: This field is only present for tweets with attached media, and houses
    ///  more complete media information, in the case of a photo set, video, or GIF. For videos and
    ///  GIFs, note that `entities` will only contain a thumbnail, and the actual video links will be
    ///  in this field. For tweets with more than one photo attached, `entities` will only contain the
    ///  first photo, and this field will contain all of them.
    ///* `possibly_sensitive`
    ///* `withheld_copyright`
    ///* `withheld_in_countries`
    ///* `withheld_scope`
    #[derive(Debug, Clone)]
    pub struct Tweet {
        //If the user has contributors enabled, this will show which accounts contributed to this
        //tweet.
        //pub contributors: Option<Contributors>,
        ///If present, the location coordinate attached to the tweet, as a (latitude, longitude) pair.
        pub coordinates: Option<(f64, f64)>,
        ///UTC timestamp from when the tweet was posted.
        #[serde(with = "serde_datetime")]
        pub created_at: chrono::DateTime<chrono::Utc>,
        ///If the authenticated user has retweeted this tweet, contains the ID of the retweet.
        pub current_user_retweet: Option<u64>,
        ///If this tweet is an extended tweet with "hidden" metadata and entities, contains the byte
        ///offsets between which the "displayable" tweet text is.
        pub display_text_range: Option<(usize, usize)>,
        ///Link, hashtag, and user mention information extracted from the tweet text.
        pub entities: TweetEntities,
        ///Extended media information attached to the tweet, if media is available.
        ///
        ///If a tweet has a photo, set of photos, gif, or video attached to it, this field will be
        ///present and contain the real media information. The information available in the `media`
        ///field of `entities` will only contain the first photo of a set, or a thumbnail of a gif or
        ///video.
        pub extended_entities: Option<ExtendedTweetEntities>,
        ///"Approximately" how many times this tweet has been liked by users.
        pub favorite_count: i32,
        ///Indicates whether the authenticated user has liked this tweet.
        pub favorited: Option<bool>,
        ///Indicates the maximum `FilterLevel` parameter that can be applied to a stream and still show
        ///this tweet.
        pub filter_level: Option<FilterLevel>,
        ///Numeric ID for this tweet.
        pub id: u64,
        ///If the tweet is a reply, contains the ID of the user that was replied to.
        pub in_reply_to_user_id: Option<u64>,
        ///If the tweet is a reply, contains the screen name of the user that was replied to.
        pub in_reply_to_screen_name: Option<String>,
        ///If the tweet is a reply, contains the ID of the tweet that was replied to.
        pub in_reply_to_status_id: Option<u64>,
        ///Can contain a language ID indicating the machine-detected language of the text, or "und" if
        ///no language could be detected.
        pub lang: Option<String>,
        ///When present, the `Place` that this tweet is associated with (but not necessarily where it
        ///originated from).
        pub place: Option<place::Place>,
        ///If the tweet has a link, indicates whether the link may contain content that could be
        ///identified as sensitive.
        pub possibly_sensitive: Option<bool>,
        ///If this tweet is quoting another by link, contains the ID of the quoted tweet.
        pub quoted_status_id: Option<u64>,
        ///If this tweet is quoting another by link, contains the quoted tweet.
        pub quoted_status: Option<Box<Tweet>>,
        //"A set of key-value pairs indicating the intended contextual delivery of the containing
        //Tweet. Currently used by Twitter’s Promoted Products."
        //pub scopes: Option<Scopes>,
        ///The number of times this tweet has been retweeted (with native retweets).
        pub retweet_count: i32,
        ///Indicates whether the authenticated user has retweeted this tweet.
        pub retweeted: Option<bool>,
        ///If this tweet is a retweet, then this field contains the original status information.
        ///
        ///The separation between retweet and original is so that retweets can be recalled by deleting
        ///the retweet, and so that liking a retweet results in an additional notification to the user
        ///who retweeted the status, as well as the original poster.
        pub retweeted_status: Option<Box<Tweet>>,
        ///The application used to post the tweet.
        pub source: Option<TweetSource>,
        ///The text of the tweet. For "extended" tweets, opening reply mentions and/or attached media
        ///or quoted tweet links do not count against character count, so this could be longer than 280
        ///characters in those situations.
        pub text: String,
        ///Indicates whether this tweet is a truncated "compatibility" form of an extended tweet whose
        ///full text is longer than 280 characters.
        pub truncated: bool,
        ///The user who posted this tweet. This field will be absent on tweets included as part of a
        ///`TwitterUser`.
        pub user: Option<Box<user::TwitterUser>>,
        ///If present and `true`, indicates that this tweet has been withheld due to a DMCA complaint.
        pub withheld_copyright: bool,
        ///If present, contains two-letter country codes indicating where this tweet is being withheld.
        ///
        ///The following special codes exist:
        ///
        ///- `XX`: Withheld in all countries
        ///- `XY`: Withheld due to DMCA complaint.
        pub withheld_in_countries: Option<Vec<String>>,
        ///If present, indicates whether the content being withheld is the `status` or the `user`.
        pub withheld_scope: Option<String>,
    }
}

impl TryFrom<raw::RawTweet> for Tweet {
    type Error = error::Error;

    fn try_from(mut raw: raw::RawTweet) -> Result<Tweet> {
        let extended_full_text = raw.extended_tweet.map(|xt| xt.full_text);
        let text = raw
            .full_text
            .or(extended_full_text)
            .or(raw.text)
            .ok_or(error::Error::MissingValue("text"))?;
        let current_user_retweet = raw.current_user_retweet.map(|cur| cur.id);

        if let Some(ref mut range) = raw.display_text_range {
            codepoints_to_bytes(range, &text);
        }
        for entity in &mut raw.entities.hashtags {
            codepoints_to_bytes(&mut entity.range, &text);
        }
        for entity in &mut raw.entities.symbols {
            codepoints_to_bytes(&mut entity.range, &text);
        }
        for entity in &mut raw.entities.urls {
            codepoints_to_bytes(&mut entity.range, &text);
        }
        for entity in &mut raw.entities.user_mentions {
            codepoints_to_bytes(&mut entity.range, &text);
        }
        if let Some(ref mut media) = raw.entities.media {
            for entity in media.iter_mut() {
                codepoints_to_bytes(&mut entity.range, &text);
            }
        }
        if let Some(ref mut entities) = raw.extended_entities {
            for entity in entities.media.iter_mut() {
                codepoints_to_bytes(&mut entity.range, &text);
            }
        }

        Ok(Tweet {
            coordinates: raw.coordinates.map(|coords| coords.coordinates),
            created_at: raw.created_at,
            display_text_range: raw.display_text_range,
            entities: raw.entities,
            extended_entities: raw.extended_entities,
            favorite_count: raw.favorite_count,
            favorited: raw.favorited,
            filter_level: raw.filter_level,
            id: raw.id,
            in_reply_to_user_id: raw.in_reply_to_user_id,
            in_reply_to_screen_name: raw.in_reply_to_screen_name,
            in_reply_to_status_id: raw.in_reply_to_status_id,
            lang: raw.lang,
            place: raw.place,
            possibly_sensitive: raw.possibly_sensitive,
            quoted_status_id: raw.quoted_status_id,
            quoted_status: raw.quoted_status,
            retweet_count: raw.retweet_count,
            retweeted: raw.retweeted,
            retweeted_status: raw.retweeted_status,
            source: raw.source,
            truncated: raw.truncated,
            user: raw.user,
            withheld_copyright: raw.withheld_copyright,
            withheld_in_countries: raw.withheld_in_countries,
            withheld_scope: raw.withheld_scope,
            text,
            current_user_retweet,
        })
    }
}

///Represents the app from which a specific tweet was posted.
///
///This struct is parsed out of the HTML anchor tag that Twitter returns as part of each tweet.
///This way you can format the source link however you like without having to parse the values out
///yourself.
///
///Note that if you're going to reconstruct a link from this, the source URL has `rel="nofollow"`
///in the anchor tag.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TweetSource {
    ///The name of the app, given by its developer.
    pub name: String,
    ///The URL for the app, given by its developer.
    pub url: String,
}

impl FromStr for TweetSource {
    type Err = error::Error;

    fn from_str(full: &str) -> Result<TweetSource> {
        use lazy_static::lazy_static;
        lazy_static! {
            static ref RE_URL: Regex = Regex::new("href=\"(.*?)\"").unwrap();
            static ref RE_NAME: Regex = Regex::new(">(.*)</a>").unwrap();
        }

        if full == "web" {
            return Ok(TweetSource {
                name: "Twitter Web Client".to_string(),
                url: "https://twitter.com".to_string(),
            });
        }

        let url = RE_URL
            .captures(full)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string())
            .ok_or_else(|| {
                InvalidResponse("TweetSource had no link href", Some(full.to_string()))
            })?;

        let name = RE_NAME
            .captures(full)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string())
            .ok_or_else(|| {
                InvalidResponse("TweetSource had no link text", Some(full.to_string()))
            })?;

        Ok(TweetSource { name, url })
    }
}

fn deserialize_tweet_source<'de, D>(ser: D) -> std::result::Result<Option<TweetSource>, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(ser)?;
    Ok(TweetSource::from_str(&s).ok())
}

///Container for URL, hashtag, mention, and media information associated with a tweet.
///
///If a tweet has no hashtags, financial symbols ("cashtags"), links, or mentions, those respective
///Vecs will be empty. If there is no media attached to the tweet, that field will be `None`.
///
///Note that for media attached to a tweet, this struct will only contain the first image of a
///photo set, or a thumbnail of a video or GIF. Full media information is available in the tweet's
///`extended_entities` field.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TweetEntities {
    ///Collection of hashtags parsed from the tweet.
    pub hashtags: Vec<entities::HashtagEntity>,
    ///Collection of financial symbols, or "cashtags", parsed from the tweet.
    pub symbols: Vec<entities::HashtagEntity>,
    ///Collection of URLs parsed from the tweet.
    pub urls: Vec<entities::UrlEntity>,
    ///Collection of user mentions parsed from the tweet.
    pub user_mentions: Vec<entities::MentionEntity>,
    ///If the tweet contains any attached media, this contains a collection of media information
    ///from the tweet.
    pub media: Option<Vec<entities::MediaEntity>>,
}

///Container for extended media information for a tweet.
///
///If a tweet has a photo, set of photos, gif, or video attached to it, this field will be present
///and contain the real media information. The information available in the `media` field of
///`entities` will only contain the first photo of a set, or a thumbnail of a gif or video.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ExtendedTweetEntities {
    ///Collection of extended media information attached to the tweet.
    pub media: Vec<entities::MediaEntity>,
}

/// Helper struct to navigate collections of tweets by requesting tweets older or newer than certain
/// IDs.
///
/// Using a Timeline to navigate collections of tweets (like a user's timeline, their list of likes,
/// etc) allows you to efficiently cursor through a collection and only load in tweets you need.
///
/// To begin, call a method that returns a `Timeline`, optionally set the page size, and call
/// `start` to load the first page of results:
///
/// ```rust,no_run
/// # use egg_mode::Token;
/// # #[tokio::main]
/// # async fn main() {
/// # let token: Token = unimplemented!();
/// let timeline = egg_mode::tweet::home_timeline(&token).with_page_size(10);
///
/// let (timeline, feed) = timeline.start().await.unwrap();
/// for tweet in &*feed {
///     println!("<@{}> {}", tweet.user.as_ref().unwrap().screen_name, tweet.text);
/// }
/// # }
/// ```
///
/// If you need to load the next set of tweets, call `older`, which will automatically update the
/// tweet IDs it tracks:
///
/// ```rust,no_run
/// # use egg_mode::Token;
/// # #[tokio::main]
/// # async fn main() {
/// # let token: Token = unimplemented!();
/// # let timeline = egg_mode::tweet::home_timeline(&token);
/// # let (timeline, _) = timeline.start().await.unwrap();
/// let (timeline, feed) = timeline.older(None).await.unwrap();
/// for tweet in &*feed {
///     println!("<@{}> {}", tweet.user.as_ref().unwrap().screen_name, tweet.text);
/// }
/// # }
/// ```
///
/// ...and similarly for `newer`, which operates in a similar fashion.
///
/// If you want to start afresh and reload the newest set of tweets again, you can call `start`
/// again, which will clear the tracked tweet IDs before loading the newest set of tweets. However,
/// if you've been storing these tweets as you go, and already know the newest tweet ID you have on
/// hand, you can load only those tweets you need like this:
///
/// ```rust,no_run
/// # use egg_mode::Token;
/// # #[tokio::main]
/// # async fn main() {
/// # let token: Token = unimplemented!();
/// let timeline = egg_mode::tweet::home_timeline(&token)
///                                .with_page_size(10);
///
/// let (timeline, _feed) = timeline.start().await.unwrap();
///
/// //keep the max_id for later
/// let reload_id = timeline.max_id.unwrap();
///
/// //simulate scrolling down a little bit
/// let (timeline, _feed) = timeline.older(None).await.unwrap();
/// let (mut timeline, _feed) = timeline.older(None).await.unwrap();
///
/// //reload the timeline with only what's new
/// timeline.reset();
/// let (timeline, _new_posts) = timeline.older(Some(reload_id)).await.unwrap();
/// # }
/// ```
///
/// Here, the argument to `older` means "older than what I just returned, but newer than the given
/// ID". Since we cleared the tracked IDs with `reset`, that turns into "the newest tweets
/// available that were posted after the given ID". The earlier invocations of `older` with `None`
/// do not place a bound on the tweets it loads. `newer` operates in a similar fashion with its
/// argument, saying "newer than what I just returned, but not newer than this given ID". When
/// called like this, it's possible for these methods to return nothing, which will also clear the
/// `Timeline`'s tracked IDs.
///
/// If you want to manually pull tweets between certain IDs, the baseline `call` function can do
/// that for you. Keep in mind, though, that `call` doesn't update the `min_id` or `max_id` fields,
/// so you'll have to set those yourself if you want to follow up with `older` or `newer`.
pub struct Timeline {
    ///The URL to request tweets from.
    link: &'static str,
    ///The token to authorize requests with.
    token: auth::Token,
    ///Optional set of params to include prior to adding timeline navigation parameters.
    params_base: Option<ParamList>,
    ///The maximum number of tweets to return in a single call. Twitter doesn't guarantee returning
    ///exactly this number, as suspended or deleted content is removed after retrieving the initial
    ///collection of tweets.
    pub count: i32,
    ///The largest/most recent tweet ID returned in the last call to `start`, `older`, or `newer`.
    pub max_id: Option<u64>,
    ///The smallest/oldest tweet ID returned in the last call to `start`, `older`, or `newer`.
    pub min_id: Option<u64>,
}

impl Timeline {
    ///Clear the saved IDs on this timeline.
    pub fn reset(&mut self) {
        self.max_id = None;
        self.min_id = None;
    }

    ///Clear the saved IDs on this timeline, and return the most recent set of tweets.
    pub fn start(mut self) -> TimelineFuture {
        self.reset();

        self.older(None)
    }

    ///Return the set of tweets older than the last set pulled, optionally placing a minimum tweet
    ///ID to bound with.
    pub fn older(self, since_id: Option<u64>) -> TimelineFuture {
        let req = self.request(since_id, self.min_id.map(|id| id - 1));
        let loader = Box::pin(request_with_json_response(req));

        TimelineFuture {
            timeline: Some(self),
            loader,
        }
    }

    ///Return the set of tweets newer than the last set pulled, optionall placing a maximum tweet
    ///ID to bound with.
    pub fn newer(self, max_id: Option<u64>) -> TimelineFuture {
        let req = self.request(self.max_id, max_id);
        let loader = Box::pin(request_with_json_response(req));

        TimelineFuture {
            timeline: Some(self),
            loader,
        }
    }

    ///Return the set of tweets between the IDs given.
    ///
    ///Note that the range is not fully inclusive; the tweet ID given by `since_id` will not be
    ///returned, but the tweet ID in `max_id` will be returned.
    ///
    ///If the range of tweets given by the IDs would return more than `self.count`, the newest set
    ///of tweets will be returned.
    pub async fn call(
        &self,
        since_id: Option<u64>,
        max_id: Option<u64>,
    ) -> Result<Response<Vec<Tweet>>> {
        request_with_json_response(self.request(since_id, max_id)).await
    }

    ///Helper function to construct a `Request` from the current state.
    fn request(&self, since_id: Option<u64>, max_id: Option<u64>) -> Request<Body> {
        let params = self
            .params_base
            .as_ref()
            .cloned()
            .unwrap_or_default()
            .add_param("count", self.count.to_string())
            .add_param("tweet_mode", "extended")
            .add_param("include_ext_alt_text", "true")
            .add_opt_param("since_id", since_id.map(|v| v.to_string()))
            .add_opt_param("max_id", max_id.map(|v| v.to_string()));

        get(self.link, &self.token, Some(&params))
    }

    ///Helper builder function to set the page size.
    pub fn with_page_size(self, page_size: i32) -> Self {
        Timeline {
            count: page_size,
            ..self
        }
    }

    ///With the returned slice of Tweets, set the min_id and max_id on self.
    fn map_ids(&mut self, resp: &[Tweet]) {
        self.max_id = resp.first().map(|status| status.id);
        self.min_id = resp.last().map(|status| status.id);
    }

    ///Create an instance of `Timeline` with the given link and tokens.
    pub(crate) fn new(
        link: &'static str,
        params_base: Option<ParamList>,
        token: &auth::Token,
    ) -> Self {
        Timeline {
            link,
            token: token.clone(),
            params_base,
            count: 20,
            max_id: None,
            min_id: None,
        }
    }
}

/// `Future` which represents loading from a `Timeline`.
///
/// When this future completes, it will either return the tweets given by Twitter (after having
/// updated the IDs in the parent `Timeline`) or the error encountered when loading or parsing the
/// response.
#[must_use = "futures do nothing unless polled"]
pub struct TimelineFuture {
    timeline: Option<Timeline>,
    loader: FutureResponse<Vec<Tweet>>,
}

impl Future for TimelineFuture {
    type Output = Result<(Timeline, Response<Vec<Tweet>>)>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        match Pin::new(&mut self.loader).poll(cx) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
            Poll::Ready(Ok(resp)) => {
                if let Some(mut timeline) = self.timeline.take() {
                    timeline.map_ids(&resp.response);
                    Poll::Ready(Ok((timeline, resp)))
                } else {
                    Poll::Ready(Err(error::Error::FutureAlreadyCompleted))
                }
            }
        }
    }
}

/// Represents an in-progress tweet before it is sent.
///
/// This is your entry point to posting new tweets to Twitter. To begin, make a new `DraftTweet` by
/// calling `new` with your desired status text:
///
/// ```rust,no_run
/// use egg_mode::tweet::DraftTweet;
///
/// let draft = DraftTweet::new("This is an example status!");
/// ```
///
/// As-is, the draft won't do anything until you call `send` to post it:
///
/// ```rust,no_run
/// # use egg_mode::Token;
/// # #[tokio::main]
/// # async fn main() {
/// # let token: Token = unimplemented!();
/// # use egg_mode::tweet::DraftTweet;
/// # let draft = DraftTweet::new("This is an example status!");
///
/// draft.send(&token).await.unwrap();
/// # }
/// ```
///
/// Right now, the options for adding metadata to a post are pretty sparse. See the adaptor
/// functions below to see what metadata can be set. For example, you can use `in_reply_to` to
/// create a reply-chain like this:
///
/// ```rust,no_run
/// # use egg_mode::Token;
/// # #[tokio::main]
/// # async fn main() {
/// # let token: Token = unimplemented!();
/// use egg_mode::tweet::DraftTweet;
///
/// let draft = DraftTweet::new("I'd like to start a thread here.");
/// let tweet = draft.send(&token).await.unwrap();
///
/// let draft = DraftTweet::new("You see, I have a lot of things to say.")
///                        .in_reply_to(tweet.id);
/// let tweet = draft.send(&token).await.unwrap();
///
/// let draft = DraftTweet::new("Thank you for your time.")
///                        .in_reply_to(tweet.id);
/// let tweet = draft.send(&token).await.unwrap();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct DraftTweet {
    ///The text of the draft tweet.
    pub text: Cow<'static, str>,
    ///If present, the ID of the tweet this draft is replying to.
    pub in_reply_to: Option<u64>,
    ///If present, whether to automatically fill reply mentions from the metadata of the
    ///`in_reply_to` tweet.
    pub auto_populate_reply_metadata: Option<bool>,
    ///If present, the list of user IDs to exclude from the automatically-populated metadata pulled
    ///when `auto_populate_reply_metadata` is true.
    pub exclude_reply_user_ids: Option<Cow<'static, [u64]>>,
    ///If present, the tweet link to quote or a [DM deep link][] to include in the tweet's
    ///attachment metadata.
    ///
    ///Note that if this link is not a tweet link or a [DM deep link][], Twitter will return an
    ///error when the draft is sent.
    ///
    ///[DM deep link]: https://business.twitter.com/en/help/campaign-editing-and-optimization/public-to-private-conversation.html
    pub attachment_url: Option<CowStr>,
    ///If present, the latitude/longitude coordinates to attach to the draft.
    pub coordinates: Option<(f64, f64)>,
    ///If present (and if `coordinates` is present), indicates whether to display a pin on the
    ///exact coordinate when the eventual tweet is displayed.
    pub display_coordinates: Option<bool>,
    ///If present the Place to attach to this draft.
    pub place_id: Option<CowStr>,
    ///List of media entities associated with tweet.
    ///
    ///A tweet can have one video, one GIF, or up to four images attached to it. When attaching
    ///them to a tweet, they're represented by a media ID, given through the upload process. (See
    ///[the `media` module] for more information on how to upload media.)
    ///
    ///[the `media` module]: ../media/index.html
    ///
    ///`DraftTweet` treats zeros in this array as if the media were not present.
    pub media_ids: Vec<media::MediaId>,
    ///States whether the media attached with `media_ids` should be labeled as "possibly
    ///sensitive", to mask the media by default.
    pub possibly_sensitive: Option<bool>,
}

impl DraftTweet {
    ///Creates a new `DraftTweet` with the given status text.
    pub fn new<S: Into<Cow<'static, str>>>(text: S) -> Self {
        DraftTweet {
            text: text.into(),
            in_reply_to: None,
            auto_populate_reply_metadata: None,
            exclude_reply_user_ids: None,
            attachment_url: None,
            coordinates: None,
            display_coordinates: None,
            place_id: None,
            media_ids: Vec::new(),
            possibly_sensitive: None,
        }
    }

    ///Marks this draft tweet as replying to the given status ID.
    ///
    ///Note that this will only properly take effect if the user who posted the given status is
    ///@mentioned in the status text, or if the given status was posted by the authenticated user.
    pub fn in_reply_to(self, in_reply_to: u64) -> Self {
        DraftTweet {
            in_reply_to: Some(in_reply_to),
            ..self
        }
    }

    ///Tells Twitter whether or not to automatically fill reply mentions from the tweet linked in
    ///`in_reply_to`.
    ///
    ///This parameter will have no effect if `in_reply_to` is absent.
    ///
    ///If you set this to true, you can strip out the mentions from the beginning of the tweet text
    ///if they were also in the reply mentions of the parent tweet. To remove handles from the list
    ///of reply mentions, hand their user IDs to `exclude_reply_user_ids`.
    pub fn auto_populate_reply_metadata(self, auto_populate: bool) -> Self {
        DraftTweet {
            auto_populate_reply_metadata: Some(auto_populate),
            ..self
        }
    }

    ///Tells Twitter to exclude the given list of user IDs from the automatically-populated reply
    ///mentions.
    ///
    ///This parameter will have no effect if `auto_populate_reply_metadata` is absent or false.
    ///
    ///Note that you cannot use this parameter to remove the author of the parent tweet from the
    ///reply list. Twitter will silently ignore the author's ID in that scenario.
    pub fn exclude_reply_user_ids<V: Into<Cow<'static, [u64]>>>(self, user_ids: V) -> Self {
        DraftTweet {
            exclude_reply_user_ids: Some(user_ids.into()),
            ..self
        }
    }

    ///Attaches the given tweet URL or [DM deep link][] to the tweet draft, which lets it be used
    ///outside the 280 character text limit.
    ///
    ///Note that if this link is not a tweet URL or a DM deep link, then Twitter will return an
    ///error when this draft is sent.
    ///
    ///[DM deep link]: https://business.twitter.com/en/help/campaign-editing-and-optimization/public-to-private-conversation.html
    pub fn attachment_url<S: Into<Cow<'static, str>>>(self, url: S) -> Self {
        DraftTweet {
            attachment_url: Some(url.into()),
            ..self
        }
    }

    ///Attach a lat/lon coordinate to this tweet, and mark whether a pin should be placed on the
    ///exact coordinate when the tweet is displayed.
    ///
    ///If coordinates are given through this method and no `place_id` is attached, Twitter will
    ///effectively call `place::reverse_geocode` with the given coordinate and attach that Place to
    ///the eventual tweet.
    ///
    ///Location fields will be ignored unless the user has enabled geolocation from their profile.
    pub fn coordinates(self, latitude: f64, longitude: f64, display: bool) -> Self {
        DraftTweet {
            coordinates: Some((latitude, longitude)),
            display_coordinates: Some(display),
            ..self
        }
    }

    ///Attach a Place to this tweet. This field will take precedence over `coordinates` in terms of
    ///what location is displayed with the tweet.
    ///
    ///Location fields will be ignored unless the user has enabled geolocation from their profile.
    pub fn place_id<S: Into<CowStr>>(self, place_id: S) -> Self {
        DraftTweet {
            place_id: Some(place_id.into()),
            ..self
        }
    }

    ///Attaches the given media ID(s) to this tweet. If more than four IDs are in this slice, only
    ///the first four will be attached. Note that Twitter will only allow one GIF, one video, or up
    ///to four images to be attached to a single tweet.
    ///
    /// Note that if this is called multiple times, only the last four IDs will be kept.
    pub fn add_media(&mut self, media_id: media::MediaId) {
        if self.media_ids.len() == 4 {
            self.media_ids.remove(0);
        }
        self.media_ids.push(media_id);
    }

    ///Marks the media attached with `media_ids` as being sensitive, so it can be hidden by
    ///default.
    pub fn possibly_sensitive(self, sensitive: bool) -> Self {
        DraftTweet {
            possibly_sensitive: Some(sensitive),
            ..self
        }
    }

    ///Send the assembled tweet as the authenticated user.
    pub async fn send(&self, token: &auth::Token) -> Result<Response<Tweet>> {
        let mut params = ParamList::new()
            .add_param("status", self.text.clone())
            .add_opt_param("in_reply_to_status_id", self.in_reply_to.map_string())
            .add_opt_param(
                "auto_populate_reply_metadata",
                self.auto_populate_reply_metadata.map_string(),
            )
            .add_opt_param("attachment_url", self.attachment_url.as_ref().cloned())
            .add_opt_param("display_coordinates", self.display_coordinates.map_string())
            .add_opt_param("place_id", self.place_id.as_ref().cloned())
            .add_opt_param("possible_sensitive", self.possibly_sensitive.map_string());

        if let Some(ref exclude) = self.exclude_reply_user_ids {
            let list = exclude
                .iter()
                .map(|id| id.to_string())
                .collect::<Vec<_>>()
                .join(",");
            params.add_param_ref("exclude_reply_user_ids", list);
        }

        if let Some((lat, long)) = self.coordinates {
            params.add_param_ref("lat", lat.to_string());
            params.add_param_ref("long", long.to_string());
        }

        let media = {
            let media = self
                .media_ids
                .iter()
                .map(|x| x.0.as_str())
                .collect::<Vec<_>>();
            media.join(",")
        };

        if !media.is_empty() {
            params.add_param_ref("media_ids", media);
        }

        let req = post(links::statuses::UPDATE, token, Some(&params));
        request_with_json_response(req).await
    }
}

#[cfg(test)]
mod tests {
    use super::Tweet;
    use crate::common::tests::load_file;

    use chrono::{Datelike, Timelike, Weekday};

    fn load_tweet(path: &str) -> Tweet {
        let sample = load_file(path);
        ::serde_json::from_str(&sample).unwrap()
    }

    #[test]
    fn parse_basic() {
        let sample = load_tweet("sample_payloads/sample-extended-onepic.json");

        assert_eq!(sample.text,
                   ".@Serrayak said he’d use what-ev-er I came up with as his Halloween avatar so I’m just making sure you all know he said that https://t.co/MvgxCwDwSa");
        assert!(sample.user.is_some());
        assert_eq!(sample.user.unwrap().screen_name, "0xabad1dea");
        assert_eq!(sample.id, 782349500404862976);
        let source = sample.source.as_ref().unwrap();
        assert_eq!(source.name, "Tweetbot for iΟS"); //note that's an omicron, not an O
        assert_eq!(source.url, "http://tapbots.com/tweetbot");
        assert_eq!(sample.created_at.weekday(), Weekday::Sat);
        assert_eq!(sample.created_at.year(), 2016);
        assert_eq!(sample.created_at.month(), 10);
        assert_eq!(sample.created_at.day(), 1);
        assert_eq!(sample.created_at.hour(), 22);
        assert_eq!(sample.created_at.minute(), 40);
        assert_eq!(sample.created_at.second(), 30);
        assert_eq!(sample.favorite_count, 20);
        assert_eq!(sample.retweet_count, 0);
        assert_eq!(sample.lang, Some("en".into()));
        assert_eq!(sample.coordinates, None);
        assert!(sample.place.is_none());

        assert_eq!(sample.favorited, Some(false));
        assert_eq!(sample.retweeted, Some(false));
        assert!(sample.current_user_retweet.is_none());

        assert!(sample
            .entities
            .user_mentions
            .iter()
            .any(|m| m.screen_name == "Serrayak"));
        assert!(sample.extended_entities.is_some());
        assert_eq!(sample.extended_entities.unwrap().media.len(), 1);

        //text contains extended link, which is outside of display_text_range
        let range = sample.display_text_range.unwrap();
        assert_eq!(&sample.text[range.0..range.1],
                   ".@Serrayak said he’d use what-ev-er I came up with as his Halloween avatar so I’m just making sure you all know he said that"
        );
        assert_eq!(sample.truncated, false);
    }

    #[test]
    fn parse_samples() {
        // Just check we can parse them without error, taken from
        // https://github.com/twitterdev/tweet-updates/tree/686982b586dcc87d669151e89532ffea7e29e0d8/samples/initial
        load_tweet("sample_payloads/compatibilityplus_classic_13994.json");
        load_tweet("sample_payloads/compatibilityplus_classic_hidden_13797.json");
        load_tweet("sample_payloads/compatibilityplus_extended_13997.json");
        load_tweet("sample_payloads/extended_classic_14002.json");
        load_tweet("sample_payloads/extended_classic_hidden_13761.json");
        load_tweet("sample_payloads/extended_extended_14001.json");
        load_tweet("sample_payloads/nullable_user_mention.json");
    }

    #[test]
    fn parse_reply() {
        let sample = load_tweet("sample_payloads/sample-reply.json");

        assert_eq!(
            sample.in_reply_to_screen_name,
            Some("QuietMisdreavus".to_string())
        );
        assert_eq!(sample.in_reply_to_user_id, Some(2977334326));
        assert_eq!(sample.in_reply_to_status_id, Some(782643731665080322));
    }

    #[test]
    fn parse_quote() {
        let sample = load_tweet("sample_payloads/sample-quote.json");

        assert_eq!(sample.quoted_status_id, Some(783004145485840384));
        assert!(sample.quoted_status.is_some());
        assert_eq!(sample.quoted_status.unwrap().text,
                   "@chalkboardsband hot damn i should call up my friends in austin, i might actually be able to make one of these now :D");
    }

    #[test]
    fn parse_retweet() {
        let sample = load_tweet("sample_payloads/sample-retweet.json");

        assert!(sample.retweeted_status.is_some());
        assert_eq!(sample.retweeted_status.unwrap().text,
                   "it's working: follow @andrewhuangbot for a random lyric of mine every hour. we'll call this version 0.1.0. wanna get line breaks in there");
    }

    #[test]
    fn parse_image_alt_text() {
        let sample = load_tweet("sample_payloads/sample-image-alt-text.json");
        let extended_entities = sample.extended_entities.unwrap();

        assert_eq!(
            extended_entities.media[0].ext_alt_text,
            Some("test alt text for the image".to_string())
        );
    }

    #[test]
    fn roundtrip_deser() {
        let sample = load_file("sample_payloads/tweet_array.json");
        let tweets_src: Vec<Tweet> = serde_json::from_str(&sample).unwrap();
        let json1 = serde_json::to_value(tweets_src).unwrap();
        let tweets_roundtrip: Vec<Tweet> = serde_json::from_value(json1.clone()).unwrap();
        let json2 = serde_json::to_value(tweets_roundtrip).unwrap();

        assert_eq!(json1, json2);
    }
}