Skip to main content

twikit/
models.rs

1//! Typed models backed by raw Twitter/X JSON.
2
3use chrono::{DateTime, FixedOffset};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7use crate::client::{Client, TweetType};
8use crate::error::{Error, Result};
9use crate::media::{media_from_tweet, Media};
10use crate::result::Timeline;
11use crate::utils::{bool_field, i64_field, parse_twitter_datetime, str_field};
12
13/// Twitter/X user.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct User {
16    /// Client handle for object convenience methods.
17    #[serde(skip)]
18    pub client: Option<Client>,
19    /// User id.
20    pub id: String,
21    /// Account creation timestamp as returned by X.
22    pub created_at: Option<String>,
23    /// Display name.
24    pub name: Option<String>,
25    /// Screen name without @.
26    pub screen_name: Option<String>,
27    /// Profile image URL.
28    pub profile_image_url: Option<String>,
29    /// Profile banner URL.
30    pub profile_banner_url: Option<String>,
31    /// Profile URL.
32    pub url: Option<String>,
33    /// Location text.
34    pub location: Option<String>,
35    /// Description text.
36    pub description: Option<String>,
37    /// Blue verified flag.
38    pub is_blue_verified: bool,
39    /// Legacy verified flag.
40    pub verified: bool,
41    /// Protected account flag.
42    pub protected: bool,
43    /// Follower count.
44    pub followers_count: Option<i64>,
45    /// Following count.
46    pub following_count: Option<i64>,
47    /// Tweet/status count.
48    pub statuses_count: Option<i64>,
49    /// Raw source payload.
50    pub raw: Value,
51}
52
53impl User {
54    /// Parse a user from GraphQL user result data.
55    pub fn from_value(data: Value) -> Result<Self> {
56        Self::from_value_with_client(data, None)
57    }
58
59    /// Parse a user and attach a client for convenience methods.
60    pub fn from_value_with_client(data: Value, client: Option<Client>) -> Result<Self> {
61        let id = str_field(&data, &["rest_id"])
62            .or_else(|| str_field(&data, &["id_str"]))
63            .or_else(|| str_field(&data, &["id"]))
64            .ok_or(Error::Missing("user.rest_id"))?
65            .to_string();
66
67        Ok(Self {
68            client,
69            id,
70            created_at: str_field(&data, &["legacy", "created_at"]).map(ToOwned::to_owned),
71            name: str_field(&data, &["legacy", "name"]).map(ToOwned::to_owned),
72            screen_name: str_field(&data, &["legacy", "screen_name"]).map(ToOwned::to_owned),
73            profile_image_url: str_field(&data, &["legacy", "profile_image_url_https"])
74                .map(ToOwned::to_owned),
75            profile_banner_url: str_field(&data, &["legacy", "profile_banner_url"])
76                .map(ToOwned::to_owned),
77            url: str_field(&data, &["legacy", "url"]).map(ToOwned::to_owned),
78            location: str_field(&data, &["legacy", "location"]).map(ToOwned::to_owned),
79            description: str_field(&data, &["legacy", "description"]).map(ToOwned::to_owned),
80            is_blue_verified: bool_field(&data, &["is_blue_verified"], false),
81            verified: bool_field(&data, &["legacy", "verified"], false),
82            protected: bool_field(&data, &["legacy", "protected"], false),
83            followers_count: i64_field(&data, &["legacy", "followers_count"]),
84            following_count: i64_field(&data, &["legacy", "friends_count"]),
85            statuses_count: i64_field(&data, &["legacy", "statuses_count"]),
86            raw: data,
87        })
88    }
89
90    /// Parsed account creation datetime.
91    pub fn created_at_datetime(&self) -> Option<Result<DateTime<FixedOffset>>> {
92        self.created_at.as_deref().map(parse_twitter_datetime)
93    }
94
95    /// Follow this user.
96    pub async fn follow(&self) -> Result<Value> {
97        Ok(serde_json::to_value(
98            self.client()?.follow_user(&self.id).await?,
99        )?)
100    }
101    /// Unfollow this user.
102    pub async fn unfollow(&self) -> Result<Value> {
103        Ok(serde_json::to_value(
104            self.client()?.unfollow_user(&self.id).await?,
105        )?)
106    }
107    /// Block this user.
108    pub async fn block(&self) -> Result<Value> {
109        Ok(serde_json::to_value(
110            self.client()?.block_user(&self.id).await?,
111        )?)
112    }
113    /// Unblock this user.
114    pub async fn unblock(&self) -> Result<Value> {
115        Ok(serde_json::to_value(
116            self.client()?.unblock_user(&self.id).await?,
117        )?)
118    }
119    /// Mute this user.
120    pub async fn mute(&self) -> Result<Value> {
121        Ok(serde_json::to_value(
122            self.client()?.mute_user(&self.id).await?,
123        )?)
124    }
125    /// Unmute this user.
126    pub async fn unmute(&self) -> Result<Value> {
127        Ok(serde_json::to_value(
128            self.client()?.unmute_user(&self.id).await?,
129        )?)
130    }
131    /// User tweets.
132    pub async fn get_tweets(&self) -> Result<Value> {
133        Ok(self
134            .client()?
135            .get_user_tweets(&self.id, TweetType::Tweets, 40, None)
136            .await?
137            .raw)
138    }
139    /// User tweets as a typed timeline.
140    pub async fn get_tweets_timeline(&self) -> Result<Timeline<Tweet>> {
141        self.client()?
142            .get_user_tweets(&self.id, TweetType::Tweets, 40, None)
143            .await
144    }
145    /// Followers.
146    pub async fn get_followers(&self) -> Result<Value> {
147        Ok(self
148            .client()?
149            .get_user_followers(&self.id, 20, None)
150            .await?
151            .raw)
152    }
153    /// Followers as a typed timeline.
154    pub async fn get_followers_timeline(&self) -> Result<Timeline<User>> {
155        self.client()?.get_user_followers(&self.id, 20, None).await
156    }
157    /// Verified followers.
158    pub async fn get_verified_followers(&self) -> Result<Value> {
159        Ok(self
160            .client()?
161            .get_user_verified_followers(&self.id, 20, None)
162            .await?
163            .raw)
164    }
165    /// Verified followers as a typed timeline.
166    pub async fn get_verified_followers_timeline(&self) -> Result<Timeline<User>> {
167        self.client()?
168            .get_user_verified_followers(&self.id, 20, None)
169            .await
170    }
171    /// Followers you know.
172    pub async fn get_followers_you_know(&self) -> Result<Value> {
173        Ok(self
174            .client()?
175            .get_user_followers_you_know(&self.id, 20, None)
176            .await?
177            .raw)
178    }
179    /// Followers you know as a typed timeline.
180    pub async fn get_followers_you_know_timeline(&self) -> Result<Timeline<User>> {
181        self.client()?
182            .get_user_followers_you_know(&self.id, 20, None)
183            .await
184    }
185    /// Following.
186    pub async fn get_following(&self) -> Result<Value> {
187        Ok(self
188            .client()?
189            .get_user_following(&self.id, 20, None)
190            .await?
191            .raw)
192    }
193    /// Following as a typed timeline.
194    pub async fn get_following_timeline(&self) -> Result<Timeline<User>> {
195        self.client()?.get_user_following(&self.id, 20, None).await
196    }
197    /// Subscriptions.
198    pub async fn get_subscriptions(&self) -> Result<Value> {
199        Ok(self
200            .client()?
201            .get_user_subscriptions(&self.id, 20, None)
202            .await?
203            .raw)
204    }
205    /// Subscriptions as a typed timeline.
206    pub async fn get_subscriptions_timeline(&self) -> Result<Timeline<User>> {
207        self.client()?
208            .get_user_subscriptions(&self.id, 20, None)
209            .await
210    }
211    /// Latest followers.
212    pub async fn get_latest_followers(&self) -> Result<Value> {
213        Ok(self
214            .client()?
215            .get_latest_followers(Some(self.id.clone()), None, 200, None)
216            .await?
217            .raw)
218    }
219    /// Latest followers as a typed timeline.
220    pub async fn get_latest_followers_timeline(&self) -> Result<Timeline<User>> {
221        self.client()?
222            .get_latest_followers(Some(self.id.clone()), None, 200, None)
223            .await
224    }
225    /// Latest friends.
226    pub async fn get_latest_friends(&self) -> Result<Value> {
227        Ok(self
228            .client()?
229            .get_latest_friends(Some(self.id.clone()), None, 200, None)
230            .await?
231            .raw)
232    }
233    /// Latest friends as a typed timeline.
234    pub async fn get_latest_friends_timeline(&self) -> Result<Timeline<User>> {
235        self.client()?
236            .get_latest_friends(Some(self.id.clone()), None, 200, None)
237            .await
238    }
239    /// Send DM.
240    pub async fn send_dm(&self) -> Result<Value> {
241        let text = self
242            .raw
243            .pointer("/dm_text")
244            .and_then(Value::as_str)
245            .ok_or(Error::Missing("User.dm_text"))?;
246        self.send_dm_with_text(text, None, None).await
247    }
248    /// Send DM with explicit text.
249    pub async fn send_dm_with_text(
250        &self,
251        text: impl Into<String>,
252        media_id: Option<String>,
253        reply_to: Option<String>,
254    ) -> Result<Value> {
255        Ok(self
256            .client()?
257            .send_dm(&self.id, text, media_id, reply_to)
258            .await?
259            .raw)
260    }
261    /// DM history.
262    pub async fn get_dm_history(&self) -> Result<Value> {
263        Ok(self.client()?.get_dm_history(&self.id, None).await?.raw)
264    }
265    /// Highlights.
266    pub async fn get_highlights_tweets(&self) -> Result<Value> {
267        Ok(self
268            .client()?
269            .get_user_highlights_tweets(&self.id, 20, None)
270            .await?
271            .raw)
272    }
273    /// Highlight tweets as a typed timeline.
274    pub async fn get_highlights_tweets_timeline(&self) -> Result<Timeline<Tweet>> {
275        self.client()?
276            .get_user_highlights_tweets(&self.id, 20, None)
277            .await
278    }
279    /// Refresh user.
280    pub async fn update(&mut self) -> Result<()> {
281        let updated = self.client()?.get_user_by_id(&self.id).await?;
282        *self = updated;
283        Ok(())
284    }
285
286    fn client(&self) -> Result<Client> {
287        self.client
288            .clone()
289            .ok_or_else(|| Error::Unsupported("User has no attached Client".into()))
290    }
291}
292
293/// Tweet/post.
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct Tweet {
296    /// Client handle for object convenience methods.
297    #[serde(skip)]
298    pub client: Option<Client>,
299    /// Tweet id.
300    pub id: String,
301    /// Created timestamp as returned by X.
302    pub created_at: Option<String>,
303    /// Legacy text.
304    pub text: Option<String>,
305    /// Full text, including note tweet text when present.
306    pub full_text: Option<String>,
307    /// Language.
308    pub lang: Option<String>,
309    /// Author.
310    pub user: Option<User>,
311    /// Reply target id.
312    pub in_reply_to: Option<String>,
313    /// Whether this tweet quotes another tweet.
314    pub is_quote_status: bool,
315    /// Quoted tweet if embedded.
316    pub quote: Option<Box<Tweet>>,
317    /// Retweeted tweet if embedded.
318    pub retweeted_tweet: Option<Box<Tweet>>,
319    /// Reply count.
320    pub reply_count: Option<i64>,
321    /// Favorite/like count.
322    pub favorite_count: Option<i64>,
323    /// Retweet count.
324    pub retweet_count: Option<i64>,
325    /// Bookmark count.
326    pub bookmark_count: Option<i64>,
327    /// View count.
328    pub view_count: Option<i64>,
329    /// Hashtags without #.
330    pub hashtags: Vec<String>,
331    /// URL entities.
332    pub urls: Vec<Value>,
333    /// Media entities.
334    pub media: Vec<Media>,
335    /// Raw source payload.
336    pub raw: Value,
337}
338
339impl Tweet {
340    /// Parse a tweet from GraphQL result data.
341    pub fn from_value(data: Value) -> Result<Self> {
342        Self::from_value_with_client(data, None)
343    }
344
345    /// Parse a tweet and attach a client for convenience methods.
346    pub fn from_value_with_client(mut data: Value, client: Option<Client>) -> Result<Self> {
347        if data.get("__typename").and_then(Value::as_str) == Some("TweetTombstone") {
348            return Err(Error::Unsupported("tweet tombstone".into()));
349        }
350        if let Some(tweet) = data.get("tweet").cloned() {
351            data = tweet;
352        }
353
354        let id = str_field(&data, &["rest_id"])
355            .or_else(|| str_field(&data, &["id_str"]))
356            .or_else(|| str_field(&data, &["id"]))
357            .ok_or(Error::Missing("tweet.rest_id"))?
358            .to_string();
359
360        let user = data
361            .pointer("/core/user_results/result")
362            .cloned()
363            .and_then(|value| User::from_value_with_client(value, client.clone()).ok());
364
365        let quote = data
366            .pointer("/quoted_status_result/result")
367            .cloned()
368            .and_then(|value| Tweet::from_value_with_client(value, client.clone()).ok())
369            .map(Box::new);
370
371        let retweeted_tweet = data
372            .pointer("/legacy/retweeted_status_result/result")
373            .cloned()
374            .and_then(|value| Tweet::from_value_with_client(value, client.clone()).ok())
375            .map(Box::new);
376
377        let note_text = data
378            .pointer("/note_tweet/note_tweet_results/result/text")
379            .and_then(Value::as_str)
380            .map(ToOwned::to_owned);
381        let text = str_field(&data, &["legacy", "full_text"]).map(ToOwned::to_owned);
382        let full_text = note_text.or_else(|| text.clone());
383
384        let hashtags = hashtag_values(&data);
385        let urls = url_values(&data);
386        let media = media_from_tweet(&data);
387
388        Ok(Self {
389            id,
390            client,
391            created_at: str_field(&data, &["legacy", "created_at"]).map(ToOwned::to_owned),
392            text,
393            full_text,
394            lang: str_field(&data, &["legacy", "lang"]).map(ToOwned::to_owned),
395            user,
396            in_reply_to: str_field(&data, &["legacy", "in_reply_to_status_id_str"])
397                .map(ToOwned::to_owned),
398            is_quote_status: bool_field(&data, &["legacy", "is_quote_status"], false),
399            quote,
400            retweeted_tweet,
401            reply_count: i64_field(&data, &["legacy", "reply_count"]),
402            favorite_count: i64_field(&data, &["legacy", "favorite_count"]),
403            retweet_count: i64_field(&data, &["legacy", "retweet_count"]),
404            bookmark_count: i64_field(&data, &["legacy", "bookmark_count"]),
405            view_count: data
406                .pointer("/views/count")
407                .and_then(Value::as_str)
408                .and_then(|s| s.parse().ok())
409                .or_else(|| i64_field(&data, &["views", "count"])),
410            hashtags,
411            urls,
412            media,
413            raw: data,
414        })
415    }
416
417    /// Parsed creation datetime.
418    pub fn created_at_datetime(&self) -> Option<Result<DateTime<FixedOffset>>> {
419        self.created_at.as_deref().map(parse_twitter_datetime)
420    }
421
422    /// Python parity id accessor.
423    pub fn id(&self) -> &str {
424        &self.id
425    }
426    /// Python parity created_at accessor.
427    pub fn created_at(&self) -> Option<&str> {
428        self.created_at.as_deref()
429    }
430    /// Python parity text accessor.
431    pub fn text(&self) -> Option<&str> {
432        self.text.as_deref()
433    }
434    /// Python parity full_text accessor.
435    pub fn full_text(&self) -> Option<&str> {
436        self.full_text.as_deref()
437    }
438    /// Python parity lang accessor.
439    pub fn lang(&self) -> Option<&str> {
440        self.lang.as_deref()
441    }
442    /// Python parity in_reply_to accessor.
443    pub fn in_reply_to(&self) -> Option<&str> {
444        self.in_reply_to.as_deref()
445    }
446    /// Python parity is_quote_status accessor.
447    pub fn is_quote_status(&self) -> bool {
448        self.is_quote_status
449    }
450    /// Python parity reply_count accessor.
451    pub fn reply_count(&self) -> Option<i64> {
452        self.reply_count
453    }
454    /// Python parity favorite_count accessor.
455    pub fn favorite_count(&self) -> Option<i64> {
456        self.favorite_count
457    }
458    /// Python parity retweet_count accessor.
459    pub fn retweet_count(&self) -> Option<i64> {
460        self.retweet_count
461    }
462    /// Python parity bookmark_count accessor.
463    pub fn bookmark_count(&self) -> Option<i64> {
464        self.bookmark_count
465    }
466    /// Python parity view_count accessor.
467    pub fn view_count(&self) -> Option<i64> {
468        self.view_count
469    }
470    /// Python parity hashtags accessor.
471    pub fn hashtags(&self) -> &[String] {
472        &self.hashtags
473    }
474    /// Python parity urls accessor.
475    pub fn urls(&self) -> &[Value] {
476        &self.urls
477    }
478    /// Python parity media accessor.
479    pub fn media(&self) -> &[Media] {
480        &self.media
481    }
482    /// Python parity quote accessor.
483    pub fn quote(&self) -> Option<&Tweet> {
484        self.quote.as_deref()
485    }
486    /// Python parity retweeted_tweet accessor.
487    pub fn retweeted_tweet(&self) -> Option<&Tweet> {
488        self.retweeted_tweet.as_deref()
489    }
490    /// Raw note tweet results.
491    pub fn _note_tweet_results(&self) -> Option<&Value> {
492        self.raw.pointer("/note_tweet/note_tweet_results")
493    }
494    /// Raw place data.
495    pub fn _place_data(&self) -> Option<&Value> {
496        self.raw.pointer("/legacy/place")
497    }
498    /// Raw card binding values.
499    pub fn _binding_values(&self) -> Option<&Value> {
500        self.raw.pointer("/card/legacy/binding_values")
501    }
502    /// Possibly sensitive.
503    pub fn possibly_sensitive(&self) -> Option<bool> {
504        self.raw
505            .pointer("/legacy/possibly_sensitive")
506            .and_then(Value::as_bool)
507    }
508    /// Possibly sensitive editable.
509    pub fn possibly_sensitive_editable(&self) -> Option<bool> {
510        self.raw
511            .pointer("/legacy/possibly_sensitive_editable")
512            .and_then(Value::as_bool)
513    }
514    /// Quote count.
515    pub fn quote_count(&self) -> Option<i64> {
516        self.raw
517            .pointer("/legacy/quote_count")
518            .and_then(Value::as_i64)
519    }
520    /// Favorited.
521    pub fn favorited(&self) -> Option<bool> {
522        self.raw
523            .pointer("/legacy/favorited")
524            .and_then(Value::as_bool)
525    }
526    /// Bookmarked.
527    pub fn bookmarked(&self) -> Option<bool> {
528        self.raw
529            .pointer("/legacy/bookmarked")
530            .and_then(Value::as_bool)
531    }
532    /// Edit tweet ids.
533    pub fn edit_tweet_ids(&self) -> Vec<Value> {
534        self.raw
535            .pointer("/edit_control/edit_tweet_ids")
536            .and_then(Value::as_array)
537            .cloned()
538            .unwrap_or_default()
539    }
540    /// Editable until.
541    pub fn editable_until_msecs(&self) -> Option<i64> {
542        self.raw
543            .pointer("/edit_control/editable_until_msecs")
544            .and_then(Value::as_i64)
545    }
546    /// Is translatable.
547    pub fn is_translatable(&self) -> Option<bool> {
548        self.raw.get("is_translatable").and_then(Value::as_bool)
549    }
550    /// Is edit eligible.
551    pub fn is_edit_eligible(&self) -> Option<bool> {
552        self.raw
553            .pointer("/edit_control/is_edit_eligible")
554            .and_then(Value::as_bool)
555    }
556    /// Edits remaining.
557    pub fn edits_remaining(&self) -> Option<i64> {
558        self.raw
559            .pointer("/edit_control/edits_remaining")
560            .and_then(Value::as_i64)
561    }
562    /// View count state.
563    pub fn view_count_state(&self) -> Option<&str> {
564        self.raw.pointer("/views/state").and_then(Value::as_str)
565    }
566    /// Has community notes.
567    pub fn has_community_notes(&self) -> Option<bool> {
568        self.raw.get("has_birdwatch_notes").and_then(Value::as_bool)
569    }
570    /// Community note.
571    pub fn community_note(&self) -> Option<&Value> {
572        self.raw.get("birdwatch_pivot")
573    }
574    /// Has card.
575    pub fn has_card(&self) -> bool {
576        self.raw.get("card").is_some()
577    }
578    /// Thumbnail title.
579    pub fn thumbnail_title(&self) -> Option<&str> {
580        self.raw
581            .pointer("/card/legacy/binding_values/title/string_value")
582            .and_then(Value::as_str)
583    }
584    /// Thumbnail url.
585    pub fn thumbnail_url(&self) -> Option<&str> {
586        self.raw
587            .pointer("/card/legacy/binding_values/thumbnail_image_original/image_value/url")
588            .and_then(Value::as_str)
589    }
590    /// Poll.
591    pub fn poll(&self) -> Option<Poll> {
592        self.raw
593            .get("card")
594            .cloned()
595            .map(|value| Poll::from_value_with_client(value, self.client.clone()))
596    }
597    /// Place.
598    pub fn place(&self) -> Option<Place> {
599        self._place_data()
600            .cloned()
601            .map(|value| Place::from_value_with_client(value, self.client.clone()))
602    }
603    /// Delete tweet.
604    pub async fn delete(&self) -> Result<Value> {
605        self.client()?.delete_tweet(&self.id).await
606    }
607    /// Favorite tweet.
608    pub async fn favorite(&self) -> Result<Value> {
609        self.client()?.favorite_tweet(&self.id).await
610    }
611    /// Unfavorite tweet.
612    pub async fn unfavorite(&self) -> Result<Value> {
613        self.client()?.unfavorite_tweet(&self.id).await
614    }
615    /// Retweet.
616    pub async fn retweet(&self) -> Result<Value> {
617        self.client()?.retweet(&self.id).await
618    }
619    /// Delete retweet.
620    pub async fn delete_retweet(&self) -> Result<Value> {
621        self.client()?.delete_retweet(&self.id).await
622    }
623    /// Bookmark.
624    pub async fn bookmark(&self) -> Result<Value> {
625        self.client()?.bookmark_tweet(&self.id, None).await
626    }
627    /// Delete bookmark.
628    pub async fn delete_bookmark(&self) -> Result<Value> {
629        self.client()?.delete_bookmark(&self.id).await
630    }
631    /// Reply.
632    pub async fn reply(&self) -> Result<Value> {
633        let text = self
634            .raw
635            .pointer("/reply_text")
636            .and_then(Value::as_str)
637            .ok_or(Error::Missing("Tweet.reply_text"))?;
638        self.reply_with_text(text, &[]).await
639    }
640
641    /// Reply with explicit text and media ids.
642    pub async fn reply_with_text(
643        &self,
644        text: impl Into<String>,
645        media_ids: &[String],
646    ) -> Result<Value> {
647        Ok(serde_json::to_value(
648            self.client()?
649                .create_tweet_reply(text, &self.id, media_ids)
650                .await?,
651        )?)
652    }
653    /// Retweeters.
654    pub async fn get_retweeters(&self) -> Result<Value> {
655        Ok(self.client()?.get_retweeters(&self.id, 40, None).await?.raw)
656    }
657    /// Retweeters as a typed timeline.
658    pub async fn get_retweeters_timeline(&self) -> Result<Timeline<User>> {
659        self.client()?.get_retweeters(&self.id, 40, None).await
660    }
661    /// Favoriters.
662    pub async fn get_favoriters(&self) -> Result<Value> {
663        Ok(self.client()?.get_favoriters(&self.id, 40, None).await?.raw)
664    }
665    /// Favoriters as a typed timeline.
666    pub async fn get_favoriters_timeline(&self) -> Result<Timeline<User>> {
667        self.client()?.get_favoriters(&self.id, 40, None).await
668    }
669    /// Similar tweets.
670    pub async fn get_similar_tweets(&self) -> Result<Value> {
671        Ok(serde_json::to_value(
672            self.client()?.get_similar_tweets(&self.id).await?,
673        )?)
674    }
675    /// Similar tweets as typed tweet models.
676    pub async fn get_similar_tweets_typed(&self) -> Result<Vec<Tweet>> {
677        self.client()?.get_similar_tweets(&self.id).await
678    }
679    /// Refresh tweet.
680    pub async fn update(&mut self) -> Result<()> {
681        let updated = self.client()?.get_tweet_by_id(&self.id).await?;
682        *self = updated;
683        Ok(())
684    }
685
686    fn client(&self) -> Result<Client> {
687        self.client
688            .clone()
689            .ok_or_else(|| Error::Unsupported("Tweet has no attached Client".into()))
690    }
691}
692
693fn hashtag_values(data: &Value) -> Vec<String> {
694    let root = data
695        .pointer("/note_tweet/note_tweet_results/result/entity_set/hashtags")
696        .or_else(|| data.pointer("/legacy/entities/hashtags"));
697    root.and_then(Value::as_array)
698        .into_iter()
699        .flatten()
700        .filter_map(|item| {
701            item.get("text")
702                .and_then(Value::as_str)
703                .map(ToOwned::to_owned)
704        })
705        .collect()
706}
707
708fn url_values(data: &Value) -> Vec<Value> {
709    let root = data
710        .pointer("/note_tweet/note_tweet_results/result/entity_set/urls")
711        .or_else(|| data.pointer("/legacy/entities/urls"));
712    root.and_then(Value::as_array).cloned().unwrap_or_default()
713}
714
715macro_rules! raw_model {
716    ($(#[$meta:meta])* $name:ident) => {
717        $(#[$meta])*
718        #[derive(Debug, Clone, Serialize, Deserialize)]
719        pub struct $name {
720            /// Client handle for object convenience methods.
721            #[serde(skip)]
722            pub client: Option<Client>,
723            /// Stable id when present.
724            pub id: Option<String>,
725            /// Raw source payload.
726            pub raw: Value,
727        }
728
729        impl $name {
730            /// Build from raw JSON.
731            pub fn from_value(raw: Value) -> Self {
732                Self::from_value_with_client(raw, None)
733            }
734
735            /// Build from raw JSON and attach a client.
736            pub fn from_value_with_client(raw: Value, client: Option<Client>) -> Self {
737                let id = raw
738                    .get("rest_id")
739                    .or_else(|| raw.get("id"))
740                    .or_else(|| raw.get("id_str"))
741                    .and_then(Value::as_str)
742                    .map(ToOwned::to_owned);
743                Self { client, id, raw }
744            }
745
746            #[allow(dead_code)]
747            fn client(&self) -> Result<Client> {
748                self.client
749                    .clone()
750                    .ok_or_else(|| Error::Unsupported(format!("{} has no attached Client", stringify!($name))))
751            }
752
753            #[allow(dead_code)]
754            fn id_str(&self) -> Result<&str> {
755                self.id
756                    .as_deref()
757                    .ok_or_else(|| Error::Missing(concat!(stringify!($name), ".id")))
758            }
759
760            /// Python parity id accessor.
761            pub fn id(&self) -> Option<&str> {
762                self.id.as_deref()
763            }
764
765            /// Common raw name accessor.
766            pub fn name(&self) -> Option<&str> {
767                self.raw_str(&["/name", "/legacy/name", "/full_name"])
768            }
769
770            /// Common raw screen name accessor.
771            pub fn screen_name(&self) -> Option<&str> {
772                self.raw_str(&["/screen_name", "/legacy/screen_name"])
773            }
774
775            /// Common raw text accessor.
776            pub fn text(&self) -> Option<&str> {
777                self.raw_str(&["/text", "/message_data/text", "/legacy/full_text"])
778            }
779
780            /// Common raw created_at accessor.
781            pub fn created_at(&self) -> Option<&str> {
782                self.raw_str(&["/created_at", "/legacy/created_at"])
783            }
784
785            #[allow(dead_code)]
786            fn raw_str(&self, pointers: &[&str]) -> Option<&str> {
787                pointers
788                    .iter()
789                    .find_map(|pointer| self.raw.pointer(pointer).and_then(Value::as_str))
790            }
791
792            #[allow(dead_code)]
793            fn raw_i64(&self, pointers: &[&str]) -> Option<i64> {
794                pointers
795                    .iter()
796                    .find_map(|pointer| self.raw.pointer(pointer).and_then(Value::as_i64))
797            }
798        }
799    };
800}
801
802raw_model!(
803    /// Bookmark folder.
804    BookmarkFolder
805);
806raw_model!(
807    /// Community.
808    Community
809);
810raw_model!(
811    /// Community member.
812    CommunityMember
813);
814raw_model!(
815    /// Community note.
816    CommunityNote
817);
818raw_model!(
819    /// Direct message group.
820    Group
821);
822raw_model!(
823    /// Group direct message.
824    GroupMessage
825);
826raw_model!(
827    /// Twitter/X list.
828    List
829);
830raw_model!(
831    /// Direct message.
832    Message
833);
834raw_model!(
835    /// Notification.
836    Notification
837);
838raw_model!(
839    /// Place/geography result.
840    Place
841);
842raw_model!(
843    /// Poll card.
844    Poll
845);
846raw_model!(
847    /// Scheduled tweet.
848    ScheduledTweet
849);
850raw_model!(
851    /// Trend.
852    Trend
853);
854raw_model!(
855    /// Trend location.
856    Location
857);
858raw_model!(
859    /// Place trend.
860    PlaceTrend
861);
862raw_model!(
863    /// Place trends.
864    PlaceTrends
865);
866
867impl BookmarkFolder {
868    /// Get tweets in folder.
869    pub async fn get_tweets(&self) -> Result<Value> {
870        Ok(self
871            .client()?
872            .get_bookmarks(40, None, Some(self.id_str()?.to_owned()))
873            .await?
874            .raw)
875    }
876    /// Get tweets in folder as a typed timeline.
877    pub async fn get_tweets_timeline(&self) -> Result<Timeline<Tweet>> {
878        self.client()?
879            .get_bookmarks(40, None, Some(self.id_str()?.to_owned()))
880            .await
881    }
882    /// Edit folder.
883    pub async fn edit(&self) -> Result<Value> {
884        let name = self
885            .raw_str(&["/name", "/bookmark_collection_name"])
886            .ok_or(Error::Missing("BookmarkFolder.name"))?;
887        self.edit_with_name(name).await
888    }
889
890    /// Edit folder name.
891    pub async fn edit_with_name(&self, name: impl Into<String>) -> Result<Value> {
892        Ok(serde_json::to_value(
893            self.client()?
894                .edit_bookmark_folder(self.id_str()?, name)
895                .await?,
896        )?)
897    }
898    /// Delete folder.
899    pub async fn delete(&self) -> Result<Value> {
900        self.client()?.delete_bookmark_folder(self.id_str()?).await
901    }
902    /// Add tweet to folder.
903    pub async fn add(&self) -> Result<Value> {
904        let tweet_id = self
905            .raw_str(&["/tweet_id", "/tweet/rest_id", "/tweet/id_str"])
906            .ok_or(Error::Missing("BookmarkFolder.tweet_id"))?;
907        self.add_tweet(tweet_id).await
908    }
909
910    /// Add explicit tweet to folder.
911    pub async fn add_tweet(&self, tweet_id: impl Into<String>) -> Result<Value> {
912        self.client()?
913            .bookmark_tweet(tweet_id.into(), Some(self.id_str()?.to_owned()))
914            .await
915    }
916}
917
918impl Message {
919    /// Reply to message.
920    pub async fn reply(&self) -> Result<Value> {
921        let text = self
922            .raw_str(&["/reply_text"])
923            .ok_or(Error::Missing("Message.reply_text"))?;
924        self.reply_with_text(text, None).await
925    }
926
927    /// Reply to message with explicit text.
928    pub async fn reply_with_text(
929        &self,
930        text: impl Into<String>,
931        media_id: Option<String>,
932    ) -> Result<Value> {
933        Ok(serde_json::to_value(
934            self.client()?
935                .send_dm(
936                    self.conversation_id()?,
937                    text,
938                    media_id,
939                    Some(self.id_str()?.to_owned()),
940                )
941                .await?,
942        )?)
943    }
944    /// Add reaction.
945    pub async fn add_reaction(&self) -> Result<Value> {
946        let emoji = self
947            .raw_str(&["/reaction", "/emoji"])
948            .ok_or(Error::Missing("Message.reaction"))?;
949        self.add_reaction_with(emoji).await
950    }
951
952    /// Add explicit reaction.
953    pub async fn add_reaction_with(&self, emoji: impl Into<String>) -> Result<Value> {
954        self.client()?
955            .add_reaction_to_message(self.id_str()?, self.conversation_id()?, emoji)
956            .await
957    }
958    /// Remove reaction.
959    pub async fn remove_reaction(&self) -> Result<Value> {
960        let emoji = self
961            .raw_str(&["/reaction", "/emoji"])
962            .ok_or(Error::Missing("Message.reaction"))?;
963        self.remove_reaction_with(emoji).await
964    }
965
966    /// Remove explicit reaction.
967    pub async fn remove_reaction_with(&self, emoji: impl Into<String>) -> Result<Value> {
968        self.client()?
969            .remove_reaction_from_message(self.id_str()?, self.conversation_id()?, emoji)
970            .await
971    }
972    /// Delete message.
973    pub async fn delete(&self) -> Result<Value> {
974        self.client()?.delete_dm(self.id_str()?).await
975    }
976
977    fn conversation_id(&self) -> Result<&str> {
978        self.raw_str(&[
979            "/conversation_id",
980            "/conversation_id_str",
981            "/dm_conversation_id",
982            "/message_data/conversation_id",
983        ])
984        .ok_or(Error::Missing("Message.conversation_id"))
985    }
986}
987
988impl Group {
989    /// History.
990    pub async fn get_history(&self) -> Result<Value> {
991        Ok(self
992            .client()?
993            .get_group_dm_history(self.id_str()?, None)
994            .await?
995            .raw)
996    }
997    /// Add members.
998    pub async fn add_members(&self) -> Result<Value> {
999        let user_ids = self.raw_string_array("/user_ids")?;
1000        self.add_members_by_ids(user_ids).await
1001    }
1002
1003    /// Add explicit members.
1004    pub async fn add_members_by_ids(&self, user_ids: Vec<String>) -> Result<Value> {
1005        self.client()?
1006            .add_members_to_group(self.id_str()?, user_ids)
1007            .await
1008    }
1009    /// Change name.
1010    pub async fn change_name(&self) -> Result<Value> {
1011        let name = self
1012            .raw_str(&["/name", "/conversation_name"])
1013            .ok_or(Error::Missing("Group.name"))?;
1014        self.change_name_to(name).await
1015    }
1016
1017    /// Change group name explicitly.
1018    pub async fn change_name_to(&self, name: impl Into<String>) -> Result<Value> {
1019        self.client()?.change_group_name(self.id_str()?, name).await
1020    }
1021    /// Send message.
1022    pub async fn send_message(&self) -> Result<Value> {
1023        let text = self
1024            .raw_str(&["/text", "/message_text"])
1025            .ok_or(Error::Missing("Group.text"))?;
1026        self.send_message_with_text(text, None, None).await
1027    }
1028
1029    /// Send explicit group message.
1030    pub async fn send_message_with_text(
1031        &self,
1032        text: impl Into<String>,
1033        media_id: Option<String>,
1034        reply_to: Option<String>,
1035    ) -> Result<Value> {
1036        Ok(serde_json::to_value(
1037            self.client()?
1038                .send_dm_to_group(self.id_str()?, text, media_id, reply_to)
1039                .await?,
1040        )?)
1041    }
1042    /// Refresh group.
1043    pub async fn update(&self) -> Result<Value> {
1044        Ok(self.client()?.get_group(self.id_str()?).await?.raw)
1045    }
1046
1047    fn raw_string_array(&self, pointer: &str) -> Result<Vec<String>> {
1048        self.raw
1049            .pointer(pointer)
1050            .and_then(Value::as_array)
1051            .map(|items| {
1052                items
1053                    .iter()
1054                    .filter_map(Value::as_str)
1055                    .map(ToOwned::to_owned)
1056                    .collect::<Vec<_>>()
1057            })
1058            .filter(|items| !items.is_empty())
1059            .ok_or(Error::Missing("Group.user_ids"))
1060    }
1061}
1062
1063impl GroupMessage {
1064    /// Group.
1065    pub async fn group(&self) -> Result<Value> {
1066        Ok(self.client()?.get_group(self.conversation_id()?).await?.raw)
1067    }
1068    /// Reply.
1069    pub async fn reply(&self) -> Result<Value> {
1070        let text = self
1071            .raw_str(&["/reply_text"])
1072            .ok_or(Error::Missing("GroupMessage.reply_text"))?;
1073        self.reply_with_text(text, None).await
1074    }
1075
1076    /// Reply with explicit text.
1077    pub async fn reply_with_text(
1078        &self,
1079        text: impl Into<String>,
1080        media_id: Option<String>,
1081    ) -> Result<Value> {
1082        Ok(serde_json::to_value(
1083            self.client()?
1084                .send_dm_to_group(
1085                    self.conversation_id()?,
1086                    text,
1087                    media_id,
1088                    Some(self.id_str()?.to_owned()),
1089                )
1090                .await?,
1091        )?)
1092    }
1093    /// Add reaction.
1094    pub async fn add_reaction(&self) -> Result<Value> {
1095        let emoji = self
1096            .raw_str(&["/reaction", "/emoji"])
1097            .ok_or(Error::Missing("GroupMessage.reaction"))?;
1098        self.add_reaction_with(emoji).await
1099    }
1100
1101    /// Add explicit reaction.
1102    pub async fn add_reaction_with(&self, emoji: impl Into<String>) -> Result<Value> {
1103        self.client()?
1104            .add_reaction_to_message(self.id_str()?, self.conversation_id()?, emoji)
1105            .await
1106    }
1107    /// Remove reaction.
1108    pub async fn remove_reaction(&self) -> Result<Value> {
1109        let emoji = self
1110            .raw_str(&["/reaction", "/emoji"])
1111            .ok_or(Error::Missing("GroupMessage.reaction"))?;
1112        self.remove_reaction_with(emoji).await
1113    }
1114
1115    /// Remove explicit reaction.
1116    pub async fn remove_reaction_with(&self, emoji: impl Into<String>) -> Result<Value> {
1117        self.client()?
1118            .remove_reaction_from_message(self.id_str()?, self.conversation_id()?, emoji)
1119            .await
1120    }
1121
1122    fn conversation_id(&self) -> Result<&str> {
1123        self.raw_str(&[
1124            "/conversation_id",
1125            "/conversation_id_str",
1126            "/dm_conversation_id",
1127            "/message_data/conversation_id",
1128        ])
1129        .ok_or(Error::Missing("GroupMessage.conversation_id"))
1130    }
1131}
1132
1133impl Community {
1134    /// Tweets.
1135    pub async fn get_tweets(&self) -> Result<Value> {
1136        Ok(self
1137            .client()?
1138            .get_community_tweets(self.id_str()?, "Top", 40, None)
1139            .await?
1140            .raw)
1141    }
1142    /// Tweets as a typed timeline.
1143    pub async fn get_tweets_timeline(&self) -> Result<Timeline<Tweet>> {
1144        self.client()?
1145            .get_community_tweets(self.id_str()?, "Top", 40, None)
1146            .await
1147    }
1148    /// Join.
1149    pub async fn join(&self) -> Result<Value> {
1150        Ok(self.client()?.join_community(self.id_str()?).await?.raw)
1151    }
1152    /// Leave.
1153    pub async fn leave(&self) -> Result<Value> {
1154        Ok(self.client()?.leave_community(self.id_str()?).await?.raw)
1155    }
1156    /// Request to join.
1157    pub async fn request_to_join(&self) -> Result<Value> {
1158        Ok(self
1159            .client()?
1160            .request_to_join_community(self.id_str()?, None)
1161            .await?
1162            .raw)
1163    }
1164    /// Members.
1165    pub async fn get_members(&self) -> Result<Value> {
1166        Ok(self
1167            .client()?
1168            .get_community_members(self.id_str()?, 20, None)
1169            .await?
1170            .raw)
1171    }
1172    /// Members as a typed timeline.
1173    pub async fn get_members_timeline(&self) -> Result<Timeline<CommunityMember>> {
1174        self.client()?
1175            .get_community_members(self.id_str()?, 20, None)
1176            .await
1177    }
1178    /// Moderators.
1179    pub async fn get_moderators(&self) -> Result<Value> {
1180        Ok(self
1181            .client()?
1182            .get_community_moderators(self.id_str()?, 20, None)
1183            .await?
1184            .raw)
1185    }
1186    /// Moderators as a typed timeline.
1187    pub async fn get_moderators_timeline(&self) -> Result<Timeline<CommunityMember>> {
1188        self.client()?
1189            .get_community_moderators(self.id_str()?, 20, None)
1190            .await
1191    }
1192    /// Search tweet.
1193    pub async fn search_tweet(&self) -> Result<Value> {
1194        let query = self
1195            .raw_str(&["/query", "/search_query"])
1196            .ok_or(Error::Missing("Community.query"))?;
1197        self.search_tweet_with_query(query).await
1198    }
1199
1200    /// Search community tweets with explicit query.
1201    pub async fn search_tweet_with_query(&self, query: impl Into<String>) -> Result<Value> {
1202        Ok(self
1203            .client()?
1204            .search_community_tweet(self.id_str()?, query, 20, None)
1205            .await?
1206            .raw)
1207    }
1208    /// Search community tweets with an explicit query as a typed timeline.
1209    pub async fn search_tweet_timeline_with_query(
1210        &self,
1211        query: impl Into<String>,
1212    ) -> Result<Timeline<Tweet>> {
1213        self.client()?
1214            .search_community_tweet(self.id_str()?, query, 20, None)
1215            .await
1216    }
1217    /// Refresh.
1218    pub async fn update(&self) -> Result<Value> {
1219        Ok(self.client()?.get_community(self.id_str()?).await?.raw)
1220    }
1221}
1222
1223impl List {
1224    /// Created-at datetime.
1225    pub fn created_at_datetime(&self) -> Option<Result<DateTime<FixedOffset>>> {
1226        self.raw
1227            .get("created_at")
1228            .and_then(Value::as_str)
1229            .map(parse_twitter_datetime)
1230    }
1231    /// Edit banner.
1232    pub async fn edit_banner(&self) -> Result<Value> {
1233        let media_id = self
1234            .raw_str(&["/media_id", "/banner_media_id"])
1235            .ok_or(Error::Missing("List.media_id"))?;
1236        self.edit_banner_with_media_id(media_id).await
1237    }
1238
1239    /// Edit banner with explicit media id.
1240    pub async fn edit_banner_with_media_id(&self, media_id: impl Into<String>) -> Result<Value> {
1241        self.client()?
1242            .edit_list_banner(self.id_str()?, media_id)
1243            .await
1244    }
1245    /// Delete banner.
1246    pub async fn delete_banner(&self) -> Result<Value> {
1247        self.client()?.delete_list_banner(self.id_str()?).await
1248    }
1249    /// Edit list.
1250    pub async fn edit(&self) -> Result<Value> {
1251        Ok(serde_json::to_value(
1252            self.client()?
1253                .edit_list(
1254                    self.id_str()?,
1255                    self.raw_str(&["/name", "/legacy/name"])
1256                        .map(ToOwned::to_owned),
1257                    self.raw_str(&["/description", "/legacy/description"])
1258                        .map(ToOwned::to_owned),
1259                    None,
1260                )
1261                .await?,
1262        )?)
1263    }
1264    /// Add member.
1265    pub async fn add_member(&self) -> Result<Value> {
1266        let user_id = self
1267            .raw_str(&["/user_id", "/member_id"])
1268            .ok_or(Error::Missing("List.user_id"))?;
1269        self.add_member_by_id(user_id).await
1270    }
1271
1272    /// Add explicit list member.
1273    pub async fn add_member_by_id(&self, user_id: impl Into<String>) -> Result<Value> {
1274        Ok(serde_json::to_value(
1275            self.client()?
1276                .add_list_member(self.id_str()?, user_id)
1277                .await?,
1278        )?)
1279    }
1280    /// Remove member.
1281    pub async fn remove_member(&self) -> Result<Value> {
1282        let user_id = self
1283            .raw_str(&["/user_id", "/member_id"])
1284            .ok_or(Error::Missing("List.user_id"))?;
1285        self.remove_member_by_id(user_id).await
1286    }
1287
1288    /// Remove explicit list member.
1289    pub async fn remove_member_by_id(&self, user_id: impl Into<String>) -> Result<Value> {
1290        Ok(serde_json::to_value(
1291            self.client()?
1292                .remove_list_member(self.id_str()?, user_id)
1293                .await?,
1294        )?)
1295    }
1296    /// Tweets.
1297    pub async fn get_tweets(&self) -> Result<Value> {
1298        Ok(self
1299            .client()?
1300            .get_list_tweets(self.id_str()?, 40, None)
1301            .await?
1302            .raw)
1303    }
1304    /// Tweets as a typed timeline.
1305    pub async fn get_tweets_timeline(&self) -> Result<Timeline<Tweet>> {
1306        self.client()?
1307            .get_list_tweets(self.id_str()?, 40, None)
1308            .await
1309    }
1310    /// Members.
1311    pub async fn get_members(&self) -> Result<Value> {
1312        Ok(self
1313            .client()?
1314            .get_list_members(self.id_str()?, 20, None)
1315            .await?
1316            .raw)
1317    }
1318    /// Members as a typed timeline.
1319    pub async fn get_members_timeline(&self) -> Result<Timeline<User>> {
1320        self.client()?
1321            .get_list_members(self.id_str()?, 20, None)
1322            .await
1323    }
1324    /// Subscribers.
1325    pub async fn get_subscribers(&self) -> Result<Value> {
1326        Ok(self
1327            .client()?
1328            .get_list_subscribers(self.id_str()?, 20, None)
1329            .await?
1330            .raw)
1331    }
1332    /// Subscribers as a typed timeline.
1333    pub async fn get_subscribers_timeline(&self) -> Result<Timeline<User>> {
1334        self.client()?
1335            .get_list_subscribers(self.id_str()?, 20, None)
1336            .await
1337    }
1338    /// Refresh.
1339    pub async fn update(&self) -> Result<Value> {
1340        Ok(self.client()?.get_list(self.id_str()?).await?.raw)
1341    }
1342}
1343
1344impl ScheduledTweet {
1345    /// Delete scheduled tweet.
1346    pub async fn delete(&self) -> Result<Value> {
1347        self.client()?.delete_scheduled_tweet(self.id_str()?).await
1348    }
1349}
1350
1351impl Poll {
1352    /// Vote.
1353    pub async fn vote(&self) -> Result<Value> {
1354        let selected_choice = self.raw_str(&["/selected_choice"]).unwrap_or("1");
1355        let card_uri = self
1356            .raw_str(&["/card_uri", "/binding_values/card_url/string_value"])
1357            .ok_or(Error::Missing("Poll.card_uri"))?;
1358        let tweet_id = self
1359            .raw_str(&["/tweet_id", "/original_tweet_id"])
1360            .ok_or(Error::Missing("Poll.tweet_id"))?;
1361        let card_name = self
1362            .raw_str(&["/name", "/card_name"])
1363            .ok_or(Error::Missing("Poll.card_name"))?;
1364        self.vote_with(selected_choice, card_uri, tweet_id, card_name)
1365            .await
1366    }
1367
1368    /// Vote with explicit poll values.
1369    pub async fn vote_with(
1370        &self,
1371        selected_choice: impl Into<String>,
1372        card_uri: impl Into<String>,
1373        tweet_id: impl Into<String>,
1374        card_name: impl Into<String>,
1375    ) -> Result<Value> {
1376        Ok(serde_json::to_value(
1377            self.client()?
1378                .vote(selected_choice, card_uri, tweet_id, card_name)
1379                .await?,
1380        )?)
1381    }
1382}
1383
1384impl CommunityNote {
1385    /// Refresh.
1386    pub async fn update(&self) -> Result<Value> {
1387        Ok(self.client()?.get_community_note(self.id_str()?).await?.raw)
1388    }
1389}
1390
1391impl Place {
1392    /// Refresh.
1393    pub async fn update(&self) -> Result<Value> {
1394        Ok(self.client()?.get_place(self.id_str()?).await?.raw)
1395    }
1396}
1397
1398impl Location {
1399    /// Get trends for this location.
1400    pub async fn get_trends(&self) -> Result<Value> {
1401        Ok(self
1402            .client()?
1403            .get_place_trends(
1404                self.raw_i64(&["/woeid", "/id"])
1405                    .ok_or(Error::Missing("Location.woeid"))?,
1406            )
1407            .await?
1408            .raw)
1409    }
1410}