use reqwest::{
Client as HttpClient,
header::{ACCEPT, ACCEPT_LANGUAGE, AUTHORIZATION, HeaderMap, HeaderValue},
};
use serde_json::{Value, json};
use std::sync::Arc;
use tokio::sync::RwLock;
use crate::auth::{Auth, CookieData};
use crate::endpoints::{self, BEARER_TOKEN};
use crate::error::{Error, Result};
use crate::features;
use crate::operations::Operations;
use crate::types::*;
const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
pub struct X {
http: HttpClient,
auth: Arc<RwLock<Auth>>,
operations: Operations,
}
pub struct XBuilder {
cookies: Option<CookieData>,
user_agent: Option<String>,
}
impl X {
pub fn builder() -> XBuilder {
XBuilder {
cookies: None,
user_agent: None,
}
}
fn headers() -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(ACCEPT, HeaderValue::from_static("*/*"));
h.insert(ACCEPT_LANGUAGE, HeaderValue::from_static("en-US,en;q=0.9"));
h.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", BEARER_TOKEN)).unwrap(),
);
h
}
async fn ensure_auth(&self) -> Result<()> {
let needs_guest = {
let auth = self.auth.read().await;
matches!(*auth, Auth::None)
};
if needs_guest {
let resp = self
.http
.post(endpoints::rest::GUEST_ACTIVATE)
.send()
.await?;
let json: Value = resp.json().await?;
let token = json
.get("guest_token")
.and_then(|v| v.as_str())
.map(Into::into)
.ok_or(Error::GuestTokenFailed)?;
let mut auth = self.auth.write().await;
*auth = Auth::Guest { token };
}
Ok(())
}
async fn graphql_request(
&self,
operation: &str,
variables: Value,
features: Value,
) -> Result<Value> {
self.ensure_auth().await?;
let op = self.operations.get(operation).await?;
let url = endpoints::graphql_url(&op.query_id, operation);
let auth = self.auth.read().await;
let params = format!(
"variables={}&features={}",
urlencoding::encode(&variables.to_string()),
urlencoding::encode(&features.to_string())
);
let mut req = self.http.get(format!("{}?{}", url, params));
match &*auth {
Auth::Guest { token } => {
req = req.header("x-guest-token", token);
}
Auth::Cookies(cookies) => {
req = req
.header("x-csrf-token", &cookies.ct0)
.header("cookie", cookies.to_cookie_string());
}
Auth::None => {}
}
let resp = req.send().await?;
let status = resp.status();
if status == 429 {
let retry = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok());
return Err(Error::RateLimited(retry));
}
if status == 401 || status == 403 {
return Err(Error::AuthRequired);
}
let text = resp.text().await?;
if text.is_empty() {
return Err(Error::Api(format!("empty response (status {})", status)));
}
let json: Value = serde_json::from_str(&text)
.map_err(|e| Error::Api(format!("json parse error: {}", e)))?;
if let Some(errors) = json.get("errors").and_then(|e| e.as_array()) {
if let Some(first) = errors.first() {
let msg = first
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("unknown error");
return Err(Error::Api(msg.into()));
}
}
Ok(json)
}
pub async fn user(&self, username: &str) -> Result<User> {
let variables = json!({
"screen_name": username,
"withSafetyModeUserFields": true,
"withSuperFollowsUserFields": true
});
let json = self
.graphql_request("UserByScreenName", variables, features::user_features())
.await?;
let user_result = json
.pointer("/data/user/result")
.ok_or_else(|| Error::UserNotFound(username.into()))?;
parse_user(user_result)
}
pub async fn user_by_id(&self, user_id: &str) -> Result<User> {
let variables = json!({
"userId": user_id,
"withSafetyModeUserFields": true,
"withSuperFollowsUserFields": true
});
let json = self
.graphql_request("UserByRestId", variables, features::user_features())
.await?;
let user_result = json
.pointer("/data/user/result")
.ok_or_else(|| Error::UserNotFound(user_id.into()))?;
parse_user(user_result)
}
pub async fn tweet(&self, tweet_id: &str) -> Result<Tweet> {
let variables = json!({
"tweetId": tweet_id,
"withCommunity": false,
"includePromotedContent": false,
"withVoice": false
});
let json = self
.graphql_request("TweetResultByRestId", variables, features::tweet_features())
.await?;
let tweet_result = json
.pointer("/data/tweetResult/result")
.ok_or_else(|| Error::TweetNotFound(tweet_id.into()))?;
parse_tweet(tweet_result)
}
pub async fn tweet_detail(&self, tweet_id: &str) -> Result<TweetDetail> {
let variables = json!({
"focalTweetId": tweet_id,
"with_rux_injections": false,
"rankingMode": "Relevance",
"includePromotedContent": true,
"withCommunity": true,
"withQuickPromoteEligibilityTweetFields": true,
"withBirdwatchNotes": true,
"withVoice": true
});
let json = self
.graphql_request("TweetDetail", variables, features::tweet_features())
.await?;
parse_tweet_detail(&json, tweet_id)
}
}
impl XBuilder {
pub fn cookies(mut self, cookies: CookieData) -> Self {
self.cookies = Some(cookies);
self
}
pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
self.user_agent = Some(ua.into());
self
}
pub async fn build(self) -> Result<X> {
let ua = self.user_agent.as_deref().unwrap_or(DEFAULT_USER_AGENT);
let http = HttpClient::builder()
.default_headers(X::headers())
.user_agent(ua)
.cookie_store(true)
.gzip(true)
.brotli(true)
.build()?;
let operations = Operations::new()?;
let auth = match self.cookies {
Some(cookies) => Auth::Cookies(cookies),
None => Auth::None,
};
Ok(X {
http,
auth: Arc::new(RwLock::new(auth)),
operations,
})
}
}
fn extract_str(v: &Value, key: &str) -> String {
v.get(key)
.and_then(|v| v.as_str())
.unwrap_or_default()
.into()
}
fn parse_user(v: &Value) -> Result<User> {
let legacy = v.get("legacy").unwrap_or(v);
let core = v.get("core");
let username = core
.and_then(|c| c.get("screen_name"))
.or_else(|| legacy.get("screen_name"))
.and_then(|v| v.as_str())
.unwrap_or_default()
.into();
let name = core
.and_then(|c| c.get("name"))
.or_else(|| legacy.get("name"))
.and_then(|v| v.as_str())
.map(Into::into);
let created_at = core
.and_then(|c| c.get("created_at"))
.or_else(|| legacy.get("created_at"))
.and_then(|v| v.as_str())
.map(Into::into);
let profile_image_url = v
.pointer("/avatar/image_url")
.or_else(|| legacy.get("profile_image_url_https"))
.and_then(|v| v.as_str())
.map(Into::into);
let location = v
.pointer("/location/location")
.or_else(|| legacy.get("location"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(Into::into);
let is_private = v
.pointer("/privacy/protected")
.or_else(|| legacy.get("protected"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
let is_verified = v
.pointer("/verification/verified")
.or_else(|| legacy.get("verified"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
Ok(User {
id: v
.get("rest_id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.into(),
username,
name,
description: legacy
.get("description")
.or_else(|| v.pointer("/profile_bio/description"))
.and_then(|v| v.as_str())
.map(Into::into),
profile_image_url,
profile_banner_url: legacy
.get("profile_banner_url")
.and_then(|v| v.as_str())
.map(Into::into),
is_private,
is_verified,
is_blue_verified: v
.get("is_blue_verified")
.and_then(|v| v.as_bool())
.unwrap_or(false),
follower_count: legacy
.get("followers_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
following_count: legacy
.get("friends_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
tweet_count: legacy
.get("statuses_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
listed_count: legacy
.get("listed_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
created_at,
location,
url: legacy
.pointer("/entities/url/urls/0/expanded_url")
.and_then(|v| v.as_str())
.map(Into::into),
pinned_tweet_id: legacy
.pointer("/pinned_tweet_ids_str/0")
.and_then(|v| v.as_str())
.map(Into::into),
})
}
fn parse_tweet(v: &Value) -> Result<Tweet> {
let typename = v.get("__typename").and_then(|t| t.as_str()).unwrap_or("");
let tweet_data = if typename == "TweetWithVisibilityResults" {
v.get("tweet").unwrap_or(v)
} else {
v
};
let legacy = tweet_data.get("legacy").unwrap_or(tweet_data);
let core = tweet_data.get("core");
let author = core
.and_then(|c| c.pointer("/user_results/result"))
.map(|u| {
let u_legacy = u.get("legacy").unwrap_or(u);
let u_core = u.get("core");
TweetAuthor {
id: u
.get("rest_id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.into(),
username: u_core
.and_then(|c| c.get("screen_name"))
.or_else(|| u_legacy.get("screen_name"))
.and_then(|v| v.as_str())
.unwrap_or_default()
.into(),
name: u_core
.and_then(|c| c.get("name"))
.or_else(|| u_legacy.get("name"))
.and_then(|v| v.as_str())
.map(Into::into),
profile_image_url: u
.pointer("/avatar/image_url")
.or_else(|| u_legacy.get("profile_image_url_https"))
.and_then(|v| v.as_str())
.map(Into::into),
is_verified: u
.pointer("/verification/verified")
.or_else(|| u_legacy.get("verified"))
.and_then(|v| v.as_bool())
.unwrap_or(false),
is_blue_verified: u
.get("is_blue_verified")
.and_then(|v| v.as_bool())
.unwrap_or(false),
}
});
let media = legacy
.pointer("/extended_entities/media")
.and_then(|m| m.as_array())
.map(|arr| {
arr.iter()
.map(|m| {
let media_type = match m.get("type").and_then(|t| t.as_str()) {
Some("video") => MediaType::Video,
Some("animated_gif") => MediaType::Gif,
_ => MediaType::Photo,
};
let video_url = m
.pointer("/video_info/variants")
.and_then(|v| v.as_array())
.and_then(|arr| {
arr.iter()
.filter(|v| {
v.get("content_type")
.and_then(|c| c.as_str())
.map(|c| c.contains("mp4"))
.unwrap_or(false)
})
.max_by_key(|v| {
v.get("bitrate").and_then(|b| b.as_u64()).unwrap_or(0)
})
.and_then(|v| v.get("url").and_then(|u| u.as_str()))
})
.map(Into::into);
Media {
id: extract_str(m, "id_str"),
media_type,
url: video_url.or_else(|| {
m.get("media_url_https")
.and_then(|u| u.as_str())
.map(Into::into)
}),
preview_url: m
.get("media_url_https")
.and_then(|u| u.as_str())
.map(Into::into),
width: m
.pointer("/original_info/width")
.and_then(|w| w.as_u64())
.map(|w| w as u32),
height: m
.pointer("/original_info/height")
.and_then(|h| h.as_u64())
.map(|h| h as u32),
duration_ms: m
.pointer("/video_info/duration_millis")
.and_then(|d| d.as_u64()),
alt_text: m
.get("ext_alt_text")
.and_then(|a| a.as_str())
.map(Into::into),
}
})
.collect()
})
.unwrap_or_default();
let urls = legacy
.pointer("/entities/urls")
.and_then(|u| u.as_array())
.map(|arr| {
arr.iter()
.map(|u| TweetUrl {
url: extract_str(u, "url"),
expanded_url: extract_str(u, "expanded_url"),
display_url: extract_str(u, "display_url"),
})
.collect()
})
.unwrap_or_default();
let hashtags = legacy
.pointer("/entities/hashtags")
.and_then(|h| h.as_array())
.map(|arr| {
arr.iter()
.filter_map(|h| h.get("text").and_then(|t| t.as_str()).map(Into::into))
.collect()
})
.unwrap_or_default();
let mentions = legacy
.pointer("/entities/user_mentions")
.and_then(|m| m.as_array())
.map(|arr| {
arr.iter()
.map(|m| TweetMention {
id: extract_str(m, "id_str"),
username: extract_str(m, "screen_name"),
})
.collect()
})
.unwrap_or_default();
Ok(Tweet {
id: tweet_data
.get("rest_id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.into(),
text: extract_str(legacy, "full_text"),
author_id: extract_str(legacy, "user_id_str"),
author,
created_at: legacy
.get("created_at")
.and_then(|v| v.as_str())
.map(Into::into),
conversation_id: legacy
.get("conversation_id_str")
.and_then(|v| v.as_str())
.map(Into::into),
lang: legacy.get("lang").and_then(|v| v.as_str()).map(Into::into),
like_count: legacy
.get("favorite_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
retweet_count: legacy
.get("retweet_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
reply_count: legacy
.get("reply_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
quote_count: legacy
.get("quote_count")
.and_then(|v| v.as_u64())
.unwrap_or(0),
view_count: tweet_data
.pointer("/views/count")
.and_then(|v| v.as_str())
.and_then(|s| s.parse().ok()),
bookmark_count: legacy.get("bookmark_count").and_then(|v| v.as_u64()),
is_retweet: legacy.get("retweeted_status_result").is_some(),
is_quote: tweet_data.get("quoted_status_result").is_some(),
is_reply: legacy.get("in_reply_to_status_id_str").is_some(),
in_reply_to_user_id: legacy
.get("in_reply_to_user_id_str")
.and_then(|v| v.as_str())
.map(Into::into),
in_reply_to_tweet_id: legacy
.get("in_reply_to_status_id_str")
.and_then(|v| v.as_str())
.map(Into::into),
quoted_tweet: tweet_data
.pointer("/quoted_status_result/result")
.and_then(|q| parse_tweet(q).ok())
.map(Box::new),
retweeted_tweet: legacy
.pointer("/retweeted_status_result/result")
.and_then(|r| parse_tweet(r).ok())
.map(Box::new),
media,
urls,
hashtags,
mentions,
})
}
fn parse_tweet_detail(json: &Value, focal_id: &str) -> Result<TweetDetail> {
let instructions = json
.pointer("/data/tweetResult/result/timeline_response/timeline/instructions")
.or_else(|| json.pointer("/data/threaded_conversation_with_injections_v2/instructions"))
.and_then(|i| i.as_array());
let mut focal_tweet: Option<Tweet> = None;
let mut thread = Vec::new();
if let Some(instructions) = instructions {
for instruction in instructions {
if let Some(entries) = instruction.get("entries").and_then(|e| e.as_array()) {
for entry in entries {
let entry_id = entry.get("entryId").and_then(|e| e.as_str()).unwrap_or("");
if entry_id.starts_with("tweet-") {
if let Some(tweet_result) =
entry.pointer("/content/itemContent/tweet_results/result")
{
if let Ok(tweet) = parse_tweet(tweet_result) {
if tweet.id == focal_id {
focal_tweet = Some(tweet);
}
}
}
}
if entry_id.starts_with("conversationthread-") {
if let Some(items) =
entry.pointer("/content/items").and_then(|i| i.as_array())
{
for item in items {
if let Some(tweet_result) =
item.pointer("/item/itemContent/tweet_results/result")
{
if let Ok(tweet) = parse_tweet(tweet_result) {
if tweet.id == focal_id {
focal_tweet = Some(tweet);
} else {
thread.push(tweet);
}
}
}
}
}
}
}
}
}
}
let tweet = focal_tweet.ok_or_else(|| Error::TweetNotFound(focal_id.into()))?;
Ok(TweetDetail { tweet, thread })
}