agent_twitter_client/
profile.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::api::requests::request_api;
use crate::auth::user_auth::TwitterAuth;
use crate::error::{Result, TwitterError};
use crate::models::Profile;
use chrono::{DateTime, Utc};
use lazy_static::lazy_static;
use reqwest::header::HeaderMap;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::sync::Mutex;
use reqwest::Client;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserProfile {
    pub id: String,
    pub id_str: String,
    pub name: String,
    pub screen_name: String,
    pub location: Option<String>,
    pub description: Option<String>,
    pub url: Option<String>,
    pub protected: bool,
    pub followers_count: i32,
    pub friends_count: i32,
    pub listed_count: i32,
    pub created_at: String,
    pub favourites_count: i32,
    pub verified: bool,
    pub statuses_count: i32,
    pub profile_image_url_https: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacyUserRaw {
    pub created_at: Option<String>,
    pub description: Option<String>,
    pub entities: Option<UserEntitiesRaw>,
    pub favourites_count: Option<i32>,
    pub followers_count: Option<i32>,
    pub friends_count: Option<i32>,
    pub media_count: Option<i32>,
    pub statuses_count: Option<i32>,
    pub id_str: Option<String>,
    pub listed_count: Option<i32>,
    pub name: Option<String>,
    pub location: String,
    pub geo_enabled: Option<bool>,
    pub pinned_tweet_ids_str: Option<Vec<String>>,
    pub profile_background_color: Option<String>,
    pub profile_banner_url: Option<String>,
    pub profile_image_url_https: Option<String>,
    pub protected: Option<bool>,
    pub screen_name: Option<String>,
    pub verified: Option<bool>,
    pub has_custom_timelines: Option<bool>,
    pub has_extended_profile: Option<bool>,
    pub url: Option<String>,
    pub can_dm: Option<bool>,
    #[serde(rename = "userId")]
    pub user_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserEntitiesRaw {
    pub url: Option<UserUrlEntity>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserUrlEntity {
    pub urls: Option<Vec<ExpandedUrl>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpandedUrl {
    pub expanded_url: Option<String>,
}

lazy_static! {
    static ref ID_CACHE: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
}

pub fn parse_profile(user: &LegacyUserRaw, is_blue_verified: Option<bool>) -> Profile {
    let mut profile = Profile {
        id: user.user_id.clone().unwrap_or_default(),
        username: user.screen_name.clone().unwrap_or_default(),
        name: user.name.clone().unwrap_or_default(),
        description: user.description.clone(),
        location: Some(user.location.clone()),
        url: user.url.clone(),
        protected: user.protected.unwrap_or(false),
        verified: user.verified.unwrap_or(false),
        followers_count: user.followers_count.unwrap_or(0),
        following_count: user.friends_count.unwrap_or(0),
        tweets_count: user.statuses_count.unwrap_or(0),
        listed_count: user.listed_count.unwrap_or(0),
        is_blue_verified: Some(is_blue_verified.unwrap_or(false)),
        created_at: user
            .created_at
            .as_ref()
            .and_then(|date_str| {
                DateTime::parse_from_str(date_str, "%a %b %d %H:%M:%S %z %Y")
                    .ok()
                    .map(|dt| dt.with_timezone(&Utc))
            })
            .unwrap_or_else(Utc::now),
        profile_image_url: user
            .profile_image_url_https
            .as_ref()
            .map(|url| url.replace("_normal", "")),
        profile_banner_url: user.profile_banner_url.clone(),
        pinned_tweet_id: user
            .pinned_tweet_ids_str
            .as_ref()
            .and_then(|ids| ids.first().cloned()),
    };

    // Set website URL from entities using functional chaining
    user.entities
        .as_ref()
        .and_then(|entities| entities.url.as_ref())
        .and_then(|url_entity| url_entity.urls.as_ref())
        .and_then(|urls| urls.first())
        .and_then(|first_url| first_url.expanded_url.as_ref())
        .map(|expanded_url| profile.url = Some(expanded_url.clone()));

    profile
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserResults {
    pub result: UserResult,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "__typename")]
pub enum UserResult {
    User(UserData),
    UserUnavailable(UserUnavailable),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserData {
    pub id: String,
    pub rest_id: String,
    pub affiliates_highlighted_label: Option<serde_json::Value>,
    pub has_graduated_access: bool,
    pub is_blue_verified: bool,
    pub profile_image_shape: String,
    pub legacy: LegacyUserRaw,
    pub smart_blocked_by: bool,
    pub smart_blocking: bool,
    pub legacy_extended_profile: Option<serde_json::Value>,
    pub is_profile_translatable: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserUnavailable {
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRaw {
    pub data: UserRawData,
    pub errors: Option<Vec<TwitterApiErrorRaw>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRawData {
    pub user: UserRawUser,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRawUser {
    pub result: UserRawResult,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRawResult {
    pub rest_id: Option<String>,
    pub is_blue_verified: Option<bool>,
    pub legacy: LegacyUserRaw,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TwitterApiErrorRaw {
    pub message: String,
    pub code: i32,
}

pub async fn get_profile(client: &Client, auth: &dyn TwitterAuth,screen_name: &str) -> Result<Profile> {
    let mut headers = HeaderMap::new();
    auth.install_headers(&mut headers).await?;

    let variables = json!({
        "screen_name": screen_name,
        "withSafetyModeUserFields": true
    });

    let features = json!({
        "hidden_profile_likes_enabled": false,
        "hidden_profile_subscriptions_enabled": false,
        "responsive_web_graphql_exclude_directive_enabled": true,
        "verified_phone_label_enabled": false,
        "subscriptions_verification_info_is_identity_verified_enabled": false,
        "subscriptions_verification_info_verified_since_enabled": true,
        "highlights_tweets_tab_ui_enabled": true,
        "creator_subscriptions_tweet_preview_api_enabled": true,
        "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
        "responsive_web_graphql_timeline_navigation_enabled": true
    });

    let field_toggles = json!({
        "withAuxiliaryUserLabels": false
    });

    let (response, _) = request_api::<UserRaw>(
        client,
        "https://twitter.com/i/api/graphql/G3KGOASz96M-Qu0nwmGXNg/UserByScreenName",
        headers,
        Method::GET,
        Some(json!({
            "variables": variables,
            "features": features,
            "fieldToggles": field_toggles
        })),
    )
    .await?;

    if let Some(errors) = response.errors {
        if !errors.is_empty() {
            return Err(TwitterError::Api(errors[0].message.clone()));
        }
    }
    let user_raw_result = &response.data.user.result;
    let mut legacy = user_raw_result.legacy.clone();
    let rest_id = user_raw_result.rest_id.clone();
    let is_blue_verified = user_raw_result.is_blue_verified;
    legacy.user_id = rest_id;
    if legacy.screen_name.is_none() || legacy.screen_name.as_ref().unwrap().is_empty() {
        return Err(TwitterError::Api(format!(
            "Either {} does not exist or is private.",
            screen_name
        )));
    }
    Ok(parse_profile(&legacy, is_blue_verified))
}

pub async fn get_screen_name_by_user_id(client: &Client, auth: &dyn TwitterAuth,user_id: &str) -> Result<String> {
    let mut headers = HeaderMap::new();
    auth.install_headers(&mut headers).await?;

    let variables = json!({
        "userId": user_id,
        "withSafetyModeUserFields": true
    });

    let features = json!({
        "hidden_profile_subscriptions_enabled": true,
        "rweb_tipjar_consumption_enabled": true,
        "responsive_web_graphql_exclude_directive_enabled": true,
        "verified_phone_label_enabled": false,
        "highlights_tweets_tab_ui_enabled": true,
        "responsive_web_twitter_article_notes_tab_enabled": true,
        "subscriptions_feature_can_gift_premium": false,
        "creator_subscriptions_tweet_preview_api_enabled": true,
        "responsive_web_graphql_skip_user_profile_image_extensions_enabled": false,
        "responsive_web_graphql_timeline_navigation_enabled": true
    });

    let (response, _) = request_api::<UserRaw>(
        client,
        "https://twitter.com/i/api/graphql/xf3jd90KKBCUxdlI_tNHZw/UserByRestId",
        headers,
        Method::GET,
        Some(json!({
            "variables": variables,
            "features": features
        })),
    )
    .await?;

    if let Some(errors) = response.errors {
        if !errors.is_empty() {
            return Err(TwitterError::Api(errors[0].message.clone()));
        }
    }

    if let Some(user) = response.data.user.result.legacy.screen_name {
        Ok(user)
    } else {
        Err(TwitterError::Api(format!(
            "Either user with ID {} does not exist or is private.",
            user_id
        )))
    }
}

pub async fn get_user_id_by_screen_name(
    client: &Client,
    auth: &dyn TwitterAuth,
    screen_name: &str,
) -> Result<String> {
    if let Some(cached_id) = ID_CACHE.lock().unwrap().get(screen_name) {
        return Ok(cached_id.clone());
    }

    let profile = get_profile(client, auth, screen_name).await?;
    if let Some(user_id) = Some(profile.id) {
        ID_CACHE
            .lock()
            .unwrap()
            .insert(screen_name.to_string(), user_id.clone());
        Ok(user_id)
    } else {
        Err(TwitterError::Api("User ID is undefined".into()))
    }
}