Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(x): add X account analytics via session cookie auth

spacesdrive9c18d3149982
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd45ad8..98538ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,20 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
+**X (Twitter) integration**
+- `POST /api/accounts/x` - add X account by username, auth_token, and ct0 session cookies
+- `GET /api/accounts/:id/x-analytics` - full analytics: profile, tweet stats, engagement rate, impressions, posting time patterns, monthly breakdown, virality and consistency scores; cached in Redis at `x:{userId}:{accountId}`
+- `GET /api/accounts/:id/x-tweets` - tweet list with likes, retweets, replies, quotes, bookmarks, impressions per tweet
+- `backend/services/x.js` - X GraphQL API client (`xFetch`), `fetchXProfile`, `fetchXTweets`, `computeXAnalytics`, `safeXAccount`
+- `frontend/src/features/analytics/x/XAnalytics.jsx` - detailed analytics page with follower stats, KPI cards, impressions timeline, tweet type breakdown pie, posting time charts, engagement breakdown, top tweets table
+- `frontend/src/features/analytics/x/XTweets.jsx` - filterable/sortable tweet explorer with type filter (original/retweet/reply/quote), text search, sort by likes/retweets/impressions/date
+- X tab in Account Manager dialog (username + auth_token + ct0 with DevTools instructions)
+- X accounts section in Account Manager accounts list with follower/following/tweet metrics
+- X accounts in Sidebar quick navigation (routes to `/x/:id`) with blue avatar
+- "X Tweets" nav item in Analytics sidebar section
+- Routes `/x/:id` and `/x-tweets/:id` in App.jsx
+- X normalization in `formatters.js` normalizeAccount()
+
**Reddit Analytics improvements**
- Karma separated into its own dedicated card in `RedditAnalytics.jsx` (total, post, comment, awardee karma); previously karma was mixed into the profile header
- KPI cards: Posts Fetched, Total Score, Total Comments, Awards Received - replacing the previous generic set
diff --git a/DECISIONS.md b/DECISIONS.md
index 0edd2a7..6067d90 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -376,3 +376,29 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- All Reddit account post lists are fetched in parallel on page mount, which may trigger more API calls than a single-account view; mitigated by Redis cache on each individual account endpoint
+
+---
+
+## ADR-017: X (Twitter) integration uses cookie-based auth via internal GraphQL API
+
+**Date:** 2026-07-11
+**Status:** Accepted
+
+**Decision:** X accounts are added using `auth_token` and `ct0` session cookies from a logged-in x.com browser session. Analytics are fetched from X's internal GraphQL API (`api.x.com/graphql/{queryId}/UserByScreenName` and `UserTweets`). The X web client's bearer token is used alongside the cookies for authentication.
+
+**Alternatives considered:**
+- X API v2 (OAuth 2.0): requires a developer account, app approval from X, and paid API tier for analytics endpoints beyond basic read. Rate limits are tier-based and cost money at volume.
+- X API v1.1 (OAuth 1.0a): legacy, partially deprecated, same developer account requirement.
+- Syndication API (`syndication.twitter.com`): public embed API with no auth required, but returns no engagement metrics (likes, retweets, impressions).
+
+**Reasoning:**
+- Cookie-based auth matches X's own web client and gives access to all data visible to the logged-in user, including impressions on own tweets
+- No developer account, app approval, or monthly cost required for a self-hosted personal deployment
+- Follows the same pattern as Reddit cookie-based auth already established in this project
+- `auth_token` + `ct0` are the two cookies X uses for all GraphQL calls; storing both matches the documented approach used by multiple open-source tools
+
+**Trade-offs:**
+- GraphQL query IDs (`queryId`) in the URL rotate when X deploys frontend changes. Update `X_QUERY_IDS` in `backend/services/x.js` when endpoints return HTTP 400. Error messages clearly identify this case.
+- X's internal GraphQL contract is undocumented. Response shapes may change without notice.
+- Session cookies expire or are revoked when the user logs out, changes their password, or X detects automation patterns. Users must re-add the account with fresh cookies.
+- Cloudflare Worker IP ranges may be rate-limited or blocked by X more aggressively than residential IPs. Users experiencing consistent failures should verify with a personal IP.
diff --git a/backend/lib/cache.js b/backend/lib/cache.js
index d9ec138..c968c15 100644
--- a/backend/lib/cache.js
+++ b/backend/lib/cache.js
@@ -47,6 +47,21 @@ export async function deleteRedditCache(redis, userId, accountId) {
try { await redis.del(`reddit:${userId}:${accountId}`); } catch { /* non-fatal */ }
}
+export async function getXCache(redis, userId, accountId) {
+ if (!redis) return null;
+ try { return (await redis.get(`x:${userId}:${accountId}`)) || null; } catch { return null; }
+}
+
+export async function setXCache(redis, userId, accountId, data) {
+ if (!redis) return;
+ try { await redis.set(`x:${userId}:${accountId}`, data); } catch { /* non-fatal */ }
+}
+
+export async function deleteXCache(redis, userId, accountId) {
+ if (!redis) return;
+ try { await redis.del(`x:${userId}:${accountId}`); } catch { /* non-fatal */ }
+}
+
// ---- OAuth state via HMAC (no Redis required) --------------------------------
// State format: base64url(userId:timestamp) . base64url(HMAC-SHA256 signature)
// Expires after 10 minutes. Secret is INSTAGRAM_APP_SECRET.
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.js
index ffe803d..16f4765 100644
--- a/backend/routes/accounts.js
+++ b/backend/routes/accounts.js
@@ -2,20 +2,23 @@ import { Hono } from 'hono';
import {
getAccounts, getAccountById, createAccount, updateAccount, deleteAccount,
} from '../lib/db.js';
-import { deleteVideosCache, deleteIGCache, deleteRedditCache } from '../lib/cache.js';
+import { deleteVideosCache, deleteIGCache, deleteRedditCache, deleteXCache } from '../lib/cache.js';
import { fetchInstagramProfile, exchangeForLongLivedToken, refreshLongLivedToken } from '../services/instagram.js';
import { resolveChannelId, fetchChannelData } from '../services/youtube.js';
import { fetchRedditProfile, safeRedditAccount } from '../services/reddit.js';
+import { fetchXProfile, safeXAccount } from '../services/x.js';
const app = new Hono();
function safeAccount(account) {
const copy = { ...account };
- copy.hasCookie = !!copy.cookie;
+ copy.hasCookie = !!copy.cookie || !!(copy.authToken && copy.ct0);
delete copy.accessToken;
delete copy.cookie;
delete copy.encryptedPassword;
delete copy.encryptedTotpSecret;
+ delete copy.authToken;
+ delete copy.ct0;
return copy;
}
@@ -126,6 +129,51 @@ app.post('/accounts/reddit', async (c) => {
}
});
+app.post('/accounts/x', async (c) => {
+ try {
+ const { username, authToken, ct0 } = await c.req.json();
+ if (!username) return c.json({ success: false, message: 'Username is required' }, 400);
+ if (!authToken) return c.json({ success: false, message: 'auth_token cookie is required - open x.com in your browser, go to DevTools (F12) > Application > Cookies > https://x.com, copy the auth_token value' }, 400);
+ if (!ct0) return c.json({ success: false, message: 'ct0 cookie is required - copy the ct0 value from the same DevTools Cookies panel' }, 400);
+
+ const supabase = c.get('supabase');
+ const userId = c.get('userId');
+ const cleanUsername = username.replace(/^@/, '').trim();
+
+ const profile = await fetchXProfile(cleanUsername, authToken, ct0);
+
+ const accounts = await getAccounts(supabase, userId);
+ if (accounts.find(a => a.platform === 'x' && a.username?.toLowerCase() === profile.username.toLowerCase())) {
+ return c.json({ success: false, message: 'This X account is already added' }, 400);
+ }
+
+ const newAccount = {
+ id: Date.now().toString() + Math.random().toString(36).substring(2, 6),
+ platform: 'x',
+ username: profile.username,
+ title: `@${profile.username}`,
+ displayName: profile.displayName,
+ description: profile.description,
+ followersCount: profile.followersCount,
+ followingCount: profile.followingCount,
+ tweetCount: profile.tweetCount,
+ profileImageUrl: profile.profileImageUrl,
+ verifiedType: profile.verifiedType,
+ location: profile.location,
+ website: profile.website,
+ authToken,
+ ct0,
+ addedAt: new Date().toISOString(),
+ lastUpdated: new Date().toISOString(),
+ };
+
+ await createAccount(supabase, newAccount, userId);
+ return c.json({ success: true, account: safeXAccount(newAccount) });
+ } catch (err) {
+ return c.json({ success: false, message: err.message }, 400);
+ }
+});
+
app.post('/accounts/instagram', async (c) => {
try {
const { accessToken } = await c.req.json();
@@ -214,6 +262,19 @@ app.post('/accounts/refresh-all', async (c) => {
commentKarma: profile.commentKarma,
iconUrl: profile.iconUrl,
};
+ } else if (account.platform === 'x') {
+ if (!account.authToken || !account.ct0) throw new Error('Session cookies not stored - re-add this account with auth_token and ct0 from x.com DevTools');
+ const profile = await fetchXProfile(account.username, account.authToken, account.ct0);
+ updates = {
+ ...updates,
+ followersCount: profile.followersCount,
+ followingCount: profile.followingCount,
+ tweetCount: profile.tweetCount,
+ displayName: profile.displayName,
+ profileImageUrl: profile.profileImageUrl,
+ description: profile.description,
+ verifiedType: profile.verifiedType,
+ };
} else {
if (!apiKey) throw new Error('No YouTube API key');
const channelData = await fetchChannelData(account.channelId, apiKey);
@@ -301,6 +362,19 @@ app.post('/accounts/:id/refresh', async (c) => {
commentKarma: profile.commentKarma,
iconUrl: profile.iconUrl,
};
+ } else if (account.platform === 'x') {
+ if (!account.authToken || !account.ct0) return c.json({ success: false, message: 'Session cookies not stored - re-add this account with auth_token and ct0 from x.com DevTools' }, 400);
+ const profile = await fetchXProfile(account.username, account.authToken, account.ct0);
+ updates = {
+ ...updates,
+ followersCount: profile.followersCount,
+ followingCount: profile.followingCount,
+ tweetCount: profile.tweetCount,
+ displayName: profile.displayName,
+ profileImageUrl: profile.profileImageUrl,
+ description: profile.description,
+ verifiedType: profile.verifiedType,
+ };
} else {
const apiKey = c.env.YOUTUBE_API_KEY;
if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);
@@ -340,6 +414,7 @@ app.delete('/accounts/:id', async (c) => {
deleteVideosCache(redis, userId, id),
deleteIGCache(redis, userId, id),
deleteRedditCache(redis, userId, id),
+ deleteXCache(redis, userId, id),
]);
return c.json({ success: true });
} catch (err) {
diff --git a/backend/routes/x.js b/backend/routes/x.js
new file mode 100644
index 0000000..9430aa3
--- /dev/null
+++ b/backend/routes/x.js
@@ -0,0 +1,57 @@
+import { Hono } from 'hono';
+import { getAccountById } from '../lib/db.js';
+import { getXCache, setXCache } from '../lib/cache.js';
+import { fetchXProfile, fetchXTweets, computeXAnalytics } from '../services/x.js';
+
+const router = new Hono();
+
+router.get('/accounts/:id/x-analytics', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ const redis = c.get('redis');
+ try {
+ const account = await getAccountById(supabase, id, userId);
+ if (!account || account.platform !== 'x') return c.json({ error: 'X account not found' }, 404);
+ if (!account.authToken || !account.ct0) return c.json({ error: 'Session cookies not stored - re-add this account with auth_token and ct0 from x.com DevTools' }, 400);
+
+ const cached = await getXCache(redis, userId, id);
+ if (cached) return c.json(cached);
+
+ const [profile, tweets] = await Promise.all([
+ fetchXProfile(account.username, account.authToken, account.ct0),
+ fetchXTweets(account.username, account.authToken, account.ct0, 200),
+ ]);
+ const analytics = computeXAnalytics(profile, tweets);
+ const result = { profile, analytics, tweets };
+
+ await setXCache(redis, userId, id, result);
+ return c.json(result);
+ } catch (err) {
+ console.error(`GET /accounts/${id}/x-analytics:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+router.get('/accounts/:id/x-tweets', async (c) => {
+ const id = c.req.param('id');
+ const userId = c.get('userId');
+ const supabase = c.get('supabase');
+ const redis = c.get('redis');
+ try {
+ const account = await getAccountById(supabase, id, userId);
+ if (!account || account.platform !== 'x') return c.json({ error: 'X account not found' }, 404);
+ if (!account.authToken || !account.ct0) return c.json({ error: 'Session cookies not stored - re-add this account with auth_token and ct0 from x.com DevTools' }, 400);
+
+ const cached = await getXCache(redis, userId, id);
+ if (cached?.tweets) return c.json(cached.tweets);
+
+ const tweets = await fetchXTweets(account.username, account.authToken, account.ct0, 200);
+ return c.json(tweets);
+ } catch (err) {
+ console.error(`GET /accounts/${id}/x-tweets:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+export default router;
diff --git a/backend/server.js b/backend/server.js
index bce511e..821881c 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -10,6 +10,7 @@ import publishingRouter from './routes/publishing.js';
import scheduledPostsRouter from './routes/scheduledPosts.js';
import settingsRouter from './routes/settings.js';
import redditRouter from './routes/reddit.js';
+import xRouter from './routes/x.js';
import { urlHandler, callbackHandler } from './routes/instagramAuth.js';
import { processScheduledPosts } from './utils/scheduler.js';
import { autoRefreshInstagramTokens } from './services/instagram.js';
@@ -54,6 +55,7 @@ api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
api.route('/', redditRouter);
+api.route('/', xRouter);
// Instagram OAuth URL generator - protected (needs userId to create state token)
api.get('/auth/instagram/url', urlHandler);
diff --git a/backend/services/x.js b/backend/services/x.js
new file mode 100644
index 0000000..9dbc7ac
--- /dev/null
+++ b/backend/services/x.js
@@ -0,0 +1,356 @@
+// X (Twitter) internal GraphQL API access via session cookies.
+// Requires auth_token + ct0 from a logged-in x.com browser session.
+// The bearer token below is X's own web client token and has been stable for years.
+// Query IDs rotate when X deploys frontend changes - update X_QUERY_IDS when that happens.
+
+const X_BEARER = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I6BeUge4%2Brkgmgd4%2FRwvXXGPvJQ8bGVNHSqcLRGrC%2FoLqEQ%3D';
+
+// GraphQL query IDs change when X rotates its web client. Update here if requests return 400.
+const X_QUERY_IDS = {
+ UserByScreenName: 'qW5u-DAuXpMEG0zaGVs2dA',
+ UserTweets: 'V7H0Ap3_Hh2FyS75OCDO3Q',
+};
+
+// Minimal feature flags - required by X's GraphQL alongside variables.
+const PROFILE_FEATURES = JSON.stringify({
+ hidden_profile_likes_enabled: true,
+ hidden_profile_subscriptions_enabled: true,
+ rweb_tipjar_consumption_enabled: true,
+ responsive_web_graphql_exclude_directive_enabled: true,
+ verified_phone_label_enabled: false,
+ subscriptions_verification_info_is_identity_verified_enabled: true,
+ subscriptions_verification_info_verified_since_enabled: true,
+ highlights_tweets_tab_ui_enabled: true,
+ responsive_web_twitter_article_notes_tab_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,
+});
+
+const TWEETS_FEATURES = JSON.stringify({
+ rweb_tipjar_consumption_enabled: true,
+ responsive_web_graphql_exclude_directive_enabled: true,
+ verified_phone_label_enabled: false,
+ creator_subscriptions_tweet_preview_api_enabled: true,
+ responsive_web_graphql_timeline_navigation_enabled: true,
+ responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
+ communities_web_enable_tweet_community_results_fetch: true,
+ c9s_tweet_anatomy_moderator_badge_enabled: true,
+ articles_preview_enabled: true,
+ responsive_web_edit_tweet_api_enabled: true,
+ graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
+ view_counts_everywhere_api_enabled: true,
+ longform_notetweets_consumption_enabled: true,
+ responsive_web_twitter_article_tweet_consumption_enabled: true,
+ tweet_awards_web_tipping_enabled: false,
+ creator_subscriptions_quote_tweet_preview_enabled: false,
+ freedom_of_speech_not_reach_fetch_enabled: true,
+ standardized_nudges_misinfo: true,
+ tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
+ rweb_video_timestamps_enabled: true,
+ longform_notetweets_rich_text_read_enabled: true,
+ longform_notetweets_inline_media_enabled: true,
+ responsive_web_enhance_cards_enabled: false,
+});
+
+function xHeaders(authToken, ct0) {
+ return {
+ 'Authorization': `Bearer ${decodeURIComponent(X_BEARER)}`,
+ 'x-csrf-token': ct0,
+ 'Cookie': `auth_token=${authToken}; ct0=${ct0}`,
+ 'Content-Type': 'application/json',
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
+ 'x-twitter-client-language': 'en',
+ 'x-twitter-active-user': 'yes',
+ 'x-twitter-auth-type': 'OAuth2Session',
+ };
+}
+
+async function xFetch(url, authToken, ct0) {
+ const res = await fetch(url, { headers: xHeaders(authToken, ct0) });
+
+ if (res.status === 400) throw new Error('X API query ID is outdated - update X_QUERY_IDS in backend/services/x.js');
+ if (res.status === 401) throw new Error('X session cookies are invalid or expired - open x.com in your browser, get fresh auth_token and ct0 values from DevTools, and re-add this account');
+ if (res.status === 403) throw new Error('X rejected the request - your auth_token may be expired or your account may be suspended');
+ if (res.status === 429) throw new Error('X rate limit reached - wait a few minutes and try again');
+ if (!res.ok) throw new Error(`X API ${res.status}: ${res.statusText}`);
+
+ const json = await res.json();
+ if (json.errors?.length) throw new Error(json.errors[0].message || 'X API error');
+ return json;
+}
+
+export async function fetchXProfile(username, authToken, ct0) {
+ const variables = JSON.stringify({
+ screen_name: username,
+ withSafetyModeUserFields: true,
+ });
+ const url = `https://api.x.com/graphql/${X_QUERY_IDS.UserByScreenName}/UserByScreenName?variables=${encodeURIComponent(variables)}&features=${encodeURIComponent(PROFILE_FEATURES)}`;
+ const data = await xFetch(url, authToken, ct0);
+
+ const u = (
+ data?.data?.user_result_by_screen_name?.result?.legacy ||
+ data?.data?.user?.result?.legacy
+ );
+ const core = (
+ data?.data?.user_result_by_screen_name?.result ||
+ data?.data?.user?.result
+ );
+
+ if (!u) throw new Error('X user not found - check the username');
+ if (u.protected && !authToken) throw new Error('This X account is protected - a session cookie from the account owner is required');
+
+ return {
+ username: u.screen_name,
+ displayName: u.name || u.screen_name,
+ description: u.description || '',
+ location: u.location || '',
+ website: u.entities?.url?.urls?.[0]?.expanded_url || u.url || '',
+ followersCount: u.followers_count ?? 0,
+ followingCount: u.friends_count ?? 0,
+ tweetCount: u.statuses_count ?? 0,
+ listedCount: u.listed_count ?? 0,
+ profileImageUrl: (u.profile_image_url_https || '').replace('_normal', '_400x400'),
+ bannerUrl: u.profile_banner_url || '',
+ createdAt: u.created_at ? new Date(u.created_at).toISOString() : '',
+ isProtected: u.protected ?? false,
+ verifiedType: core?.affiliates_highlighted_label?.label?.userLabelType ||
+ (u.verified ? 'LegacyVerified' : (core?.is_blue_verified ? 'BlueVerified' : 'none')),
+ };
+}
+
+export async function fetchXTweets(username, authToken, ct0, limit = 200) {
+ // First resolve the userId from the profile query
+ const profileVariables = JSON.stringify({ screen_name: username, withSafetyModeUserFields: true });
+ const profileUrl = `https://api.x.com/graphql/${X_QUERY_IDS.UserByScreenName}/UserByScreenName?variables=${encodeURIComponent(profileVariables)}&features=${encodeURIComponent(PROFILE_FEATURES)}`;
+ const profileData = await xFetch(profileUrl, authToken, ct0);
+
+ const userId = (
+ profileData?.data?.user_result_by_screen_name?.result?.rest_id ||
+ profileData?.data?.user?.result?.rest_id
+ );
+ if (!userId) throw new Error('Could not resolve X user ID');
+
+ const tweets = [];
+ let cursor = null;
+ let pages = 0;
+
+ while (pages < 10 && tweets.length < limit) {
+ const variables = JSON.stringify({
+ userId,
+ count: Math.min(20, limit - tweets.length),
+ includePromotedContent: false,
+ withQuickPromoteEligibilityTweetFields: true,
+ withVoice: true,
+ withV2Timeline: true,
+ ...(cursor ? { cursor } : {}),
+ });
+
+ const url = `https://api.x.com/graphql/${X_QUERY_IDS.UserTweets}/UserTweets?variables=${encodeURIComponent(variables)}&features=${encodeURIComponent(TWEETS_FEATURES)}`;
+ const data = await xFetch(url, authToken, ct0);
+
+ const instructions = data?.data?.user?.result?.timeline_v2?.timeline?.instructions ?? [];
+ const timelineAddEntries = instructions.find(i => i.type === 'TimelineAddEntries');
+ const entries = timelineAddEntries?.entries ?? [];
+
+ let foundCursor = null;
+ for (const entry of entries) {
+ const content = entry.content;
+ if (!content) continue;
+
+ if (content.entryType === 'TimelineTimelineCursor' && content.cursorType === 'Bottom') {
+ foundCursor = content.value;
+ continue;
+ }
+
+ const tweet = content?.itemContent?.tweet_results?.result?.legacy ||
+ content?.itemContent?.tweet_results?.result?.tweet?.legacy;
+ const tweetResult = content?.itemContent?.tweet_results?.result ||
+ content?.itemContent?.tweet_results?.result?.tweet;
+
+ if (!tweet || !tweetResult) continue;
+
+ const tweetId = tweetResult.rest_id || tweetResult.tweet?.rest_id;
+ tweets.push({
+ id: tweetId || entry.entryId,
+ text: tweet.full_text || tweet.text || '',
+ createdAt: tweet.created_at ? new Date(tweet.created_at).toISOString() : '',
+ likeCount: tweet.favorite_count ?? 0,
+ retweetCount: tweet.retweet_count ?? 0,
+ replyCount: tweet.reply_count ?? 0,
+ quoteCount: tweet.quote_count ?? 0,
+ bookmarkCount: tweet.bookmark_count ?? 0,
+ // views.count is available for authenticated requests on own account
+ impressionCount: parseInt(tweetResult.views?.count ?? tweetResult.tweet?.views?.count ?? 0, 10) || 0,
+ isRetweet: !!tweet.retweeted_status_id_str,
+ isReply: !!tweet.in_reply_to_status_id_str,
+ isQuote: tweet.is_quote_status ?? false,
+ lang: tweet.lang || '',
+ permalink: tweetId ? `https://x.com/${username}/status/${tweetId}` : '',
+ mediaType: tweet.entities?.media?.[0]?.type || (tweet.entities?.urls?.length ? 'link' : 'text'),
+ });
+ }
+
+ cursor = foundCursor;
+ if (!cursor || entries.length < 3) break;
+ pages++;
+ }
+
+ return tweets.slice(0, limit);
+}
+
+export function computeXAnalytics(profile, tweets) {
+ const empty = {
+ fetchedTweets: 0, totalLikes: 0, avgLikes: 0,
+ totalRetweets: 0, avgRetweets: 0, totalReplies: 0, avgReplies: 0,
+ totalQuotes: 0, totalBookmarks: 0, totalImpressions: 0, avgImpressions: 0,
+ engagementRate: 0, avgEngagement: 0,
+ topTweets: [], tweetTypeDistribution: {},
+ postsByDayOfWeek: [], postsByHour: [], monthlyBreakdown: [],
+ postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
+ postFrequency: { perWeek: 0, perMonth: 0 },
+ viralityScore: 0, consistencyScore: 0,
+ bestPostingDay: '', bestPostingHour: '',
+ };
+
+ if (!tweets || tweets.length === 0) return empty;
+
+ const ownTweets = tweets.filter(t => !t.isRetweet);
+
+ const totalLikes = ownTweets.reduce((s, t) => s + t.likeCount, 0);
+ const totalRetweets = ownTweets.reduce((s, t) => s + t.retweetCount, 0);
+ const totalReplies = ownTweets.reduce((s, t) => s + t.replyCount, 0);
+ const totalQuotes = ownTweets.reduce((s, t) => s + t.quoteCount, 0);
+ const totalBookmarks = ownTweets.reduce((s, t) => s + t.bookmarkCount, 0);
+ const totalImpressions = ownTweets.reduce((s, t) => s + t.impressionCount, 0);
+
+ const n = ownTweets.length || 1;
+ const avgLikes = Math.round(totalLikes / n);
+ const avgRetweets = Math.round(totalRetweets / n);
+ const avgReplies = Math.round(totalReplies / n);
+ const avgImpressions = Math.round(totalImpressions / n);
+ const avgEngagement = Math.round((totalLikes + totalRetweets + totalReplies) / n);
+ const engagementRate = profile.followersCount > 0
+ ? parseFloat(((avgLikes + avgRetweets + avgReplies) / profile.followersCount * 100).toFixed(2))
+ : 0;
+
+ // Tweet type distribution
+ const tweetTypeDistribution = { tweet: 0, retweet: 0, reply: 0, quote: 0 };
+ tweets.forEach(t => {
+ if (t.isRetweet) tweetTypeDistribution.retweet++;
+ else if (t.isReply) tweetTypeDistribution.reply++;
+ else if (t.isQuote) tweetTypeDistribution.quote++;
+ else tweetTypeDistribution.tweet++;
+ });
+
+ // Day of week and hour analysis (own tweets only)
+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+ const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, likes: 0, impressions: 0 }));
+ const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, likes: 0, impressions: 0 }));
+ const dates = ownTweets.map(t => t.createdAt ? new Date(t.createdAt) : null).filter(Boolean);
+
+ dates.forEach((d, i) => {
+ const t = ownTweets[i];
+ const day = d.getDay();
+ dayBuckets[day].count++;
+ dayBuckets[day].likes += t?.likeCount ?? 0;
+ dayBuckets[day].impressions += t?.impressionCount ?? 0;
+ const h = d.getHours();
+ hourBuckets[h].count++;
+ hourBuckets[h].likes += t?.likeCount ?? 0;
+ hourBuckets[h].impressions += t?.impressionCount ?? 0;
+ });
+
+ const postsByDayOfWeek = dayBuckets.map((b, i) => ({
+ day: dayNames[i], shortDay: dayNames[i].slice(0, 3),
+ posts: b.count,
+ avgLikes: b.count > 0 ? Math.round(b.likes / b.count) : 0,
+ avgImpressions: b.count > 0 ? Math.round(b.impressions / b.count) : 0,
+ }));
+ const bestDay = postsByDayOfWeek.reduce((best, d) => d.avgLikes > best.avgLikes ? d : best, postsByDayOfWeek[0]);
+
+ const postsByHour = hourBuckets.map((b, i) => ({
+ hour: i, label: `${i}:00`,
+ posts: b.count,
+ avgLikes: b.count > 0 ? Math.round(b.likes / b.count) : 0,
+ avgImpressions: b.count > 0 ? Math.round(b.impressions / b.count) : 0,
+ }));
+ const bestHour = postsByHour.reduce((best, h) => h.avgLikes > best.avgLikes ? h : best, postsByHour[0]);
+
+ // Monthly breakdown (own tweets)
+ const monthMap = {};
+ ownTweets.forEach(t => {
+ if (!t.createdAt) return;
+ const d = new Date(t.createdAt);
+ if (isNaN(d)) return;
+ const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
+ if (!monthMap[key]) monthMap[key] = { posts: 0, likes: 0, retweets: 0, impressions: 0 };
+ monthMap[key].posts++;
+ monthMap[key].likes += t.likeCount;
+ monthMap[key].retweets += t.retweetCount;
+ monthMap[key].impressions += t.impressionCount;
+ });
+ const monthlyBreakdown = Object.entries(monthMap)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([month, s]) => ({
+ month, posts: s.posts, likes: s.likes, retweets: s.retweets, impressions: s.impressions,
+ avgLikes: Math.round(s.likes / s.posts),
+ }));
+
+ // Recency
+ const now = Date.now();
+ const postsLast7Days = dates.filter(d => (now - d.getTime()) <= 7 * 86400000).length;
+ const postsLast30Days = dates.filter(d => (now - d.getTime()) <= 30 * 86400000).length;
+ const postsLast90Days = dates.filter(d => (now - d.getTime()) <= 90 * 86400000).length;
+
+ // Post frequency
+ let perWeek = 0, perMonth = 0;
+ if (dates.length >= 2) {
+ const newest = Math.max(...dates.map(d => d.getTime()));
+ const oldest = Math.min(...dates.map(d => d.getTime()));
+ const spanDays = Math.max(1, (newest - oldest) / 86400000);
+ perWeek = parseFloat((ownTweets.length / spanDays * 7).toFixed(1));
+ perMonth = parseFloat((ownTweets.length / spanDays * 30).toFixed(1));
+ }
+
+ // Virality and consistency (based on likes)
+ const byLikes = [...ownTweets].sort((a, b) => b.likeCount - a.likeCount);
+ const bestLikes = byLikes[0]?.likeCount ?? 0;
+ const viralityScore = avgLikes > 0 ? parseFloat((bestLikes / avgLikes).toFixed(1)) : 0;
+
+ let consistencyScore = 0;
+ if (ownTweets.length >= 3) {
+ const likes = ownTweets.map(t => t.likeCount);
+ const mean = likes.reduce((s, v) => s + v, 0) / likes.length;
+ const variance = likes.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / likes.length;
+ const stdDev = Math.sqrt(variance);
+ const cv = mean > 0 ? stdDev / mean : (stdDev > 0 ? 10 : 0);
+ consistencyScore = Math.max(0, Math.min(100, Math.round(100 / (1 + cv))));
+ }
+
+ return {
+ fetchedTweets: tweets.length,
+ totalLikes, avgLikes, totalRetweets, avgRetweets,
+ totalReplies, avgReplies, totalQuotes, totalBookmarks,
+ totalImpressions, avgImpressions,
+ engagementRate, avgEngagement,
+ topTweets: byLikes.slice(0, 10),
+ tweetTypeDistribution,
+ postsByDayOfWeek, bestPostingDay: bestDay?.day ?? '',
+ postsByHour, bestPostingHour: bestHour?.posts > 0 ? bestHour.label : '',
+ monthlyBreakdown,
+ postsLast7Days, postsLast30Days, postsLast90Days,
+ postFrequency: { perWeek, perMonth },
+ viralityScore, consistencyScore,
+ };
+}
+
+// Strips auth_token and ct0 before any API response.
+// Exposes hasCookie: boolean so the frontend can show session status.
+export function safeXAccount(account) {
+ const copy = { ...account };
+ copy.hasCookie = !!(copy.authToken && copy.ct0);
+ delete copy.authToken;
+ delete copy.ct0;
+ return copy;
+}
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 5233e2c..9147c2a 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -30,7 +30,8 @@
│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 │
│ │ │ (cache) │ │ ├── Instagram Graph API v25 │
│ │ │ (cache) │ │ ├── Reddit Public JSON API │
-│ tables: │ │ │ │ └── Cloudinary Upload API │
+│ tables: │ │ │ │ ├── X (Twitter) GraphQL API │
+│ │ │ (cache) │ │ └── Cloudinary Upload API │
│ accounts │ │ keys: │ └──────────────────────────────────────┘
│ settings │ │ videos: │
│ sched_ │ │ {u}:{a} │
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index 86f5d0b..bc1fad8 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -25,6 +25,7 @@ export async function getVideosCache(redis, userId, accountId) {
| `videos:{userId}:{accountId}` | Array of YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds | `DELETE /api/accounts/:id` |
| `ig:{userId}:{accountId}` | Array of Instagram media objects | `GET /api/accounts/:id/ig-analytics` succeeds | `DELETE /api/accounts/:id` |
| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds | `DELETE /api/accounts/:id` |
+| `x:{userId}:{accountId}` | Object `{ profile, analytics, tweets }` for X account | `GET /api/accounts/:id/x-analytics` succeeds | `DELETE /api/accounts/:id` |
| `oauth_ig:{state}` | userId string (legacy, Redis-backed) | Instagram OAuth URL generation | Consumed on callback; 10-min TTL |
**Note:** The `oauth_ig:` key is a legacy path. The current OAuth implementation uses HMAC-signed state tokens that don't require Redis. This key is set and consumed only when Redis is available, as a secondary verification layer.
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 6b4fbe4..485f70e 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -68,6 +68,13 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.js` | Fetch profile + posts + computed analytics; cached in Redis |
| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.js` | Returns cached post list or live-fetched posts |
+### X (Twitter)
+| Method | Path | File | Purpose |
+|---|---|---|---|
+| POST | `/api/accounts/x` | `routes/accounts.js` | Add X account by username + auth_token + ct0 session cookies |
+| GET | `/api/accounts/:id/x-analytics` | `routes/x.js` | Fetch profile + tweets + computed analytics; cached in Redis |
+| GET | `/api/accounts/:id/x-tweets` | `routes/x.js` | Returns cached tweet list or live-fetched tweets |
+
### Settings
| Method | Path | File | Purpose |
|---|---|---|---|
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index b0a77f8..72b2a01 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -122,6 +122,33 @@ Reddit integration requires no Worker secrets. The session cookie is a per-user
---
+---
+
+## `backend/services/x.js`
+
+### HTTP Client
+
+All X (Twitter) internal GraphQL API calls go through `xFetch(url, authToken, ct0)`. Requests include the X web client bearer token in `Authorization`, the `ct0` value in `x-csrf-token`, and both cookies in `Cookie`. The bearer token (`X_BEARER` constant) is X's own web client token and has been stable for years. GraphQL query IDs (`X_QUERY_IDS`) rotate when X deploys frontend changes and must be updated in the service file when HTTP 400 errors appear.
+
+### Key Functions
+
+| Function | Purpose |
+|---|---|
+| `fetchXProfile(username, authToken, ct0)` | Fetches profile via `UserByScreenName` GraphQL query: followers, following, tweet count, bio, verified status, profile image |
+| `fetchXTweets(username, authToken, ct0, limit)` | Paginates own tweets via `UserTweets` GraphQL query; up to 200 tweets; includes likes, retweets, replies, quotes, bookmarks, impressions |
+| `computeXAnalytics(profile, tweets)` | Computes engagement rate, avg metrics, posting time patterns, monthly breakdown, tweet type distribution, virality/consistency scores |
+| `safeXAccount(account)` | Strips `authToken` and `ct0` fields before any API response |
+
+### `safeXAccount(account)`
+
+Strips `authToken` and `ct0` from the account object before it is returned in any API response. Exposes `hasCookie: boolean` to indicate whether session credentials are stored.
+
+### No Worker secrets required
+
+X integration requires no Worker secrets. The `auth_token` and `ct0` session cookies are per-user credentials stored in `accounts.data.authToken` and `accounts.data.ct0`. They are read server-side by the Worker and never returned to the frontend.
+
+---
+
## Adding a New Service
1. Create `backend/services/myPlatform.js`
diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.md
index 4fda2a8..9bd1113 100644
--- a/docs/architecture/data-flows/ANALYTICS.md
+++ b/docs/architecture/data-flows/ANALYTICS.md
@@ -203,6 +203,82 @@ RedditAnalytics.jsx mounts -> api.getRedditAnalytics(id)
Note: Reddit disabled `view_count` from their API in December 2018. The field always returns `null` regardless of authentication method. Views are not available for Reddit posts.
+## X (Twitter) Analytics Flow
+
+```
+User navigates to /x/:id
+ │
+ ▼
+XAnalytics.jsx mounts -> api.getXAnalytics(id)
+ -> GET /api/accounts/:id/x-analytics
+ │
+ ▼
+ Worker: xRouter
+ 1. getAccountById(supabase, id, userId) - verify ownership
+ 2. redis cache check: key x:{userId}:{accountId}
+ -> cache hit: return immediately
+ -> cache miss: continue
+ 3. Fetch from X internal GraphQL API (auth_token + ct0 cookies):
+ a. GET /graphql/{queryId}/UserByScreenName
+ -> profile: username, displayName, description, followersCount,
+ followingCount, tweetCount, listedCount, verifiedType,
+ profileImageUrl, location, website, createdAt
+ b. Resolve userId from profile, then paginate /graphql/{queryId}/UserTweets
+ -> up to 10 pages x 20 = up to 200 tweets
+ 4. computeXAnalytics(profile, tweets)
+ -> engagement metrics, posting patterns, timeline
+ 5. Cache result in Redis
+ 6. Return { profile, analytics, tweets }
+```
+
+### computeXAnalytics() Output (partial)
+
+```js
+{
+ fetchedTweets: 200,
+ totalLikes: 45000, avgLikes: 225,
+ totalRetweets: 8000, avgRetweets: 40,
+ totalReplies: 3200, avgReplies: 16,
+ totalQuotes: 1200, totalBookmarks: 5000,
+ totalImpressions: 2000000, avgImpressions: 10000,
+ engagementRate: 1.4, // (avgLikes+avgRetweets+avgReplies) / followers * 100
+ avgEngagement: 281,
+ topTweets: [ /* top 10 by likes */ ],
+ tweetTypeDistribution: { tweet: 150, retweet: 20, reply: 25, quote: 5 },
+ postsByDayOfWeek: [ /* 7 entries with avgLikes and post count per day */ ],
+ postsByHour: [ /* 24 entries with avgLikes per hour */ ],
+ bestPostingDay: 'Tuesday',
+ bestPostingHour: '14:00',
+ monthlyBreakdown: [
+ { month: '2025-06', posts: 15, likes: 3200, retweets: 600, impressions: 150000, avgLikes: 213 },
+ // ...
+ ],
+ postsLast7Days: 4,
+ postsLast30Days: 18,
+ postsLast90Days: 52,
+ postFrequency: { perWeek: 4.2, perMonth: 18.1 },
+ viralityScore: 8.2, // peak tweet likes / avg likes
+ consistencyScore: 54, // 0-100, higher = more uniform performance
+}
+```
+
+### Per-tweet fields
+
+```js
+{
+ id, text, createdAt,
+ likeCount, retweetCount, replyCount, quoteCount, bookmarkCount,
+ impressionCount, // views.count from X API - available for own tweets
+ isRetweet, isReply, isQuote,
+ lang, permalink,
+ mediaType, // 'text' | 'image' | 'video' | 'link'
+}
+```
+
+Note: `impressionCount` requires authentication as the account owner. It is available for own tweets via X's `views.count` field in the GraphQL response. Older tweets or tweets viewed without authentication return 0.
+
+Note: X's GraphQL `queryId` values in `X_QUERY_IDS` (backend/services/x.js) rotate when X deploys frontend updates. Update them when the API returns HTTP 400.
+
## Overview Dashboard (Cross-Account)
```
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 91b4111..d57d194 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -16,6 +16,9 @@ frontend/src/
│ │ ├── RedditAnalytics.jsx <- Reddit account analytics (karma, scores, subreddits)
│ │ ├── RedditPosts.jsx <- Per-account post explorer
│ │ └── RedditPostsAll.jsx <- Global post explorer (all Reddit accounts)
+│ │ └── x/
+│ │ ├── XAnalytics.jsx <- X account analytics (followers, impressions, engagement, top tweets)
+│ │ └── XTweets.jsx <- Per-account tweet explorer with type filter and sort
│ ├── accounts/
│ │ └── AccountManager.jsx <- Add/remove connected accounts
│ ├── publishing/
@@ -78,6 +81,8 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
| Reddit Analytics | `/reddit/:id` | Reddit analytics for one account - karma breakdown, score timeline, post type distribution, day/hour analysis, subreddit breakdown, top posts |
| Reddit Posts (global) | `/reddit-posts` | Combined post explorer across all Reddit accounts with account and subreddit filters |
| Reddit Posts (per account) | `/reddit-posts/:id` | Searchable and sortable post list for a single Reddit account |
+| X Analytics | `/x/:id` | X account analytics - follower stats, impressions timeline, tweet type breakdown, posting time charts, top tweets table |
+| X Tweets | `/x-tweets/:id` | Searchable tweet explorer with type filter (original/retweet/reply/quote) and sort by likes/retweets/impressions |
| Video Explorer | `/videos/:id` | YouTube video library with search and sort |
| Publish | `/publish/:id` | Publish a post to Instagram immediately |
| Schedule | `/schedule/:id` | View and manage the scheduled post queue |
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index 2454e39..fd8dfe8 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -17,6 +17,8 @@ The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `Browser
| `/reddit/:id` | `RedditAnalytics.jsx` | `:id` = account.id for Reddit accounts |
| `/reddit-posts` | `RedditPostsAll.jsx` | Combined post explorer across all connected Reddit accounts |
| `/reddit-posts/:id` | `RedditPosts.jsx` | `:id` = account.id; filterable/sortable post explorer for one account |
+| `/x/:id` | `XAnalytics.jsx` | `:id` = account.id for X accounts |
+| `/x-tweets/:id` | `XTweets.jsx` | `:id` = account.id; filterable/sortable tweet explorer for one X account |
| `/videos/:id` | `VideoExplorer.jsx` | `:id` = account.id for YouTube accounts |
| `/publish/:id` | `Publish.jsx` | `:id` = account.id for Instagram accounts |
| `/schedule/:id` | `Schedule.jsx` | `:id` = account.id for Instagram accounts |
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index f654287..a5634ff 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -21,6 +21,8 @@ const Settings = lazy(() => import('./features/settings/Settings'));
const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
const RedditPosts = lazy(() => import('./features/analytics/reddit/RedditPosts'));
const RedditPostsAll = lazy(() => import('./features/analytics/reddit/RedditPostsAll'));
+const XAnalytics = lazy(() => import('./features/analytics/x/XAnalytics'));
+const XTweets = lazy(() => import('./features/analytics/x/XTweets'));
const router = createBrowserRouter([
{
@@ -49,6 +51,8 @@ const router = createBrowserRouter([
{ path: 'reddit/:id', element: <RedditAnalytics /> },
{ path: 'reddit-posts', element: <RedditPostsAll /> },
{ path: 'reddit-posts/:id', element: <RedditPosts /> },
+ { path: 'x/:id', element: <XAnalytics /> },
+ { path: 'x-tweets/:id', element: <XTweets /> },
{ path: '*', element: <Navigate to="/" replace /> },
],
},
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index 81d672f..ebf93c5 100644
--- a/frontend/src/features/accounts/AccountManager.jsx
+++ b/frontend/src/features/accounts/AccountManager.jsx
@@ -10,7 +10,7 @@ import {
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Plus, Trash2, RefreshCw, Search, Users, CheckCircle2,
- Tv, Camera, Link2, Info, ExternalLink, MessageSquare, Lock,
+ Tv, Camera, Link2, Info, ExternalLink, MessageSquare, Lock, Twitter,
} from 'lucide-react';
import MainCard from '../../components/MainCard';
import { useAppContext } from '../../context/AppContext';
@@ -30,6 +30,10 @@ export default function AccountManager() {
const [redditUsername, setRedditUsername] = useState('');
const [redditCookie, setRedditCookie] = useState('');
const [addingReddit, setAddingReddit] = useState(false);
+ const [xUsername, setXUsername] = useState('');
+ const [xAuthToken, setXAuthToken] = useState('');
+ const [xCt0, setXCt0] = useState('');
+ const [addingX, setAddingX] = useState(false);
const [refreshingId, setRefreshingId] = useState(null);
// Handle Instagram OAuth redirect result (?ig_connected=true or ?ig_error=...)
@@ -146,17 +150,36 @@ export default function AccountManager() {
}
};
+ const handleAddX = async () => {
+ if (!xUsername.trim() || !xAuthToken.trim() || !xCt0.trim()) return;
+ setAddingX(true);
+ try {
+ await api.addXAccount(xUsername.trim(), xAuthToken.trim(), xCt0.trim());
+ showToast('X account added');
+ closeDialog();
+ loadAccounts();
+ } catch (err) {
+ showToast('Failed to add X account: ' + err.message, 'error');
+ } finally {
+ setAddingX(false);
+ }
+ };
+
const closeDialog = () => {
setDialogOpen(false);
setResolved(null);
setInput('');
setRedditUsername('');
setRedditCookie('');
+ setXUsername('');
+ setXAuthToken('');
+ setXCt0('');
};
- const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');
+ const ytAccounts = accounts.filter(a => !['instagram', 'reddit', 'x'].includes(a.platform));
const igAccounts = accounts.filter(a => a.platform === 'instagram');
const redditAccounts = accounts.filter(a => a.platform === 'reddit');
+ const xAccounts = accounts.filter(a => a.platform === 'x');
return (
<div className="space-y-6">
@@ -169,6 +192,7 @@ export default function AccountManager() {
ytAccounts.length ? `${ytAccounts.length} YouTube` : null,
igAccounts.length ? `${igAccounts.length} Instagram` : null,
redditAccounts.length ? `${redditAccounts.length} Reddit` : null,
+ xAccounts.length ? `${xAccounts.length} X` : null,
].filter(Boolean).join(' · ') || 'No accounts added yet'}
</p>
</div>
@@ -286,6 +310,34 @@ export default function AccountManager() {
</div>
</div>
)}
+
+ {/* X */}
+ {xAccounts.length > 0 && (
+ <div>
+ <div className="flex items-center gap-2 mb-3">
+ <Twitter className="h-5 w-5 text-sky-500" />
+ <h2 className="text-base font-semibold">X Accounts</h2>
+ <Badge variant="outline" className="border-sky-200 bg-sky-50 text-sky-600 text-xs">{xAccounts.length}</Badge>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
+ {xAccounts.map(acct => (
+ <AccountCard
+ key={acct.id}
+ acct={acct}
+ platform="x"
+ metrics={[
+ { label: 'Followers', value: fmtNum(acct.followersCount), className: 'bg-sky-50 text-sky-700' },
+ { label: 'Following', value: fmtNum(acct.followingCount), className: 'bg-blue-50 text-blue-700' },
+ { label: 'Tweets', value: fmtNum(acct.tweetCount), className: 'bg-slate-50 text-slate-700' },
+ ]}
+ refreshingId={refreshingId}
+ onRefresh={handleRefreshOne}
+ onDelete={handleDelete}
+ />
+ ))}
+ </div>
+ </div>
+ )}
</div>
)}
@@ -308,6 +360,9 @@ export default function AccountManager() {
<TabsTrigger value="reddit" className="flex-1 gap-1.5">
<MessageSquare className="h-3.5 w-3.5" /> Reddit
</TabsTrigger>
+ <TabsTrigger value="x" className="flex-1 gap-1.5">
+ <Twitter className="h-3.5 w-3.5" /> X
+ </TabsTrigger>
</TabsList>
<TabsContent value="youtube" className="space-y-4 mt-4">
@@ -410,6 +465,50 @@ export default function AccountManager() {
</AlertDescription>
</Alert>
</TabsContent>
+
+ <TabsContent value="x" className="space-y-4 mt-4">
+ <p className="text-sm text-muted-foreground">
+ Session cookies are required to fetch your X analytics from the server.
+ </p>
+ <div className="space-y-3">
+ <div className="relative">
+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground font-medium">@</span>
+ <Input
+ className="pl-8"
+ value={xUsername}
+ onChange={e => setXUsername(e.target.value)}
+ placeholder="your_username"
+ onKeyDown={e => e.key === 'Enter' && handleAddX()}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium">auth_token</label>
+ <Input
+ type="password"
+ value={xAuthToken}
+ onChange={e => setXAuthToken(e.target.value)}
+ placeholder="auth_token cookie value"
+ onKeyDown={e => e.key === 'Enter' && handleAddX()}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium">ct0</label>
+ <Input
+ type="password"
+ value={xCt0}
+ onChange={e => setXCt0(e.target.value)}
+ placeholder="ct0 cookie value"
+ onKeyDown={e => e.key === 'Enter' && handleAddX()}
+ />
+ </div>
+ </div>
+ <Alert>
+ <Info className="h-4 w-4" />
+ <AlertDescription className="text-xs">
+ Log in to x.com in your browser. Open DevTools (F12), go to <strong>Application &gt; Cookies &gt; https://x.com</strong>. Copy the values of <strong>auth_token</strong> and <strong>ct0</strong> and paste them above.
+ </AlertDescription>
+ </Alert>
+ </TabsContent>
</Tabs>
<DialogFooter>
@@ -426,6 +525,12 @@ export default function AccountManager() {
Add Reddit Account
</Button>
)}
+ {dialogTab === 'x' && (
+ <Button onClick={handleAddX} disabled={!xUsername.trim() || !xAuthToken.trim() || !xCt0.trim() || addingX} className="gap-1.5">
+ {addingX && <RefreshCw className="h-3.5 w-3.5 animate-spin" />}
+ Add X Account
+ </Button>
+ )}
</DialogFooter>
</DialogContent>
</Dialog>
@@ -436,12 +541,15 @@ export default function AccountManager() {
function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelete }) {
const isIG = platform === 'instagram';
const isReddit = platform === 'reddit';
+ const isX = platform === 'x';
const initials = (acct.title || '?').slice(0, 2).toUpperCase();
- const fallbackBg = isIG ? 'bg-pink-500' : isReddit ? 'bg-orange-500' : 'bg-red-500';
+ const fallbackBg = isIG ? 'bg-pink-500' : isReddit ? 'bg-orange-500' : isX ? 'bg-sky-500' : 'bg-red-500';
const subtitle = isIG
? `@${acct.username || acct.igUsername || ''}`
: isReddit
? `u/${acct.username || ''}`
+ : isX
+ ? `@${acct.username || ''}`
: (acct.customUrl || '');
return (
@@ -468,17 +576,17 @@ function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelet
))}
</div>
- {isReddit && (
+ {(isReddit || isX) && (
<div className="flex items-center gap-1.5 text-xs">
{acct.hasCookie ? (
<>
<Lock className="h-3 w-3 text-green-500" />
- <span className="text-green-600">Session cookie stored</span>
+ <span className="text-green-600">Session cookies stored</span>
</>
) : (
<>
<Lock className="h-3 w-3 text-destructive" />
- <span className="text-destructive">No cookie - re-add account</span>
+ <span className="text-destructive">No cookies - re-add account</span>
</>
)}
</div>
diff --git a/frontend/src/features/analytics/x/XAnalytics.jsx b/frontend/src/features/analytics/x/XAnalytics.jsx
new file mode 100644
index 0000000..fbb66ef
--- /dev/null
+++ b/frontend/src/features/analytics/x/XAnalytics.jsx
@@ -0,0 +1,423 @@
+import React, { useState, useEffect } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import { Button } from '@/components/ui/button';
+import { Badge } from '@/components/ui/badge';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Progress } from '@/components/ui/progress';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { Separator } from '@/components/ui/separator';
+import {
+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,
+ ResponsiveContainer, AreaChart, Area, PieChart, Pie, Cell, Legend,
+} from 'recharts';
+import { Spinner } from '@/components/ui/spinner';
+import StatCard from '../../../components/ui/StatCard';
+import MainCard from '../../../components/MainCard';
+import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
+import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';
+import {
+ ArrowLeft, RefreshCw, TrendingUp, MessageSquare, BarChart2,
+ Calendar, Clock, Zap, Flame, Trophy, ExternalLink, FileText,
+ Heart, Repeat2, Quote, Bookmark, Eye, CheckCircle2, MapPin, Link2,
+} from 'lucide-react';
+
+const X_BLUE = '#1D9BF0';
+const X_COLORS = ['#1D9BF0', '#0F6CBD', '#7BC8F6', '#5B9BD5', '#A8D8F0', '#C8E8F8'];
+const TYPE_LABELS = { tweet: 'Original', retweet: 'Retweet', reply: 'Reply', quote: 'Quote' };
+const TYPE_COLORS = { tweet: '#1D9BF0', retweet: '#17BF63', reply: '#F45D22', quote: '#794BC4' };
+
+const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };
+
+export default function XAnalytics() {
+ const { id } = useParams();
+ const { accounts, showToast } = useAppContext();
+ const navigate = useNavigate();
+ const account = accounts.find(a => a.id === id);
+
+ const [loading, setLoading] = useState(true);
+ const [profile, setProfile] = useState(null);
+ const [analytics, setAnalytics] = useState(null);
+ const [refreshing, setRefreshing] = useState(false);
+
+ const loadAnalytics = async () => {
+ if (!account) return;
+ setLoading(true);
+ try {
+ const data = await api.getXAnalytics(account.id);
+ setProfile(data.profile);
+ setAnalytics(data.analytics);
+ } catch (err) {
+ showToast('Failed to load X analytics: ' + err.message, 'error');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => { loadAnalytics(); }, [id]);
+
+ const handleRefresh = async () => {
+ setRefreshing(true);
+ try {
+ await api.refreshAccount(account.id);
+ await loadAnalytics();
+ showToast('X account refreshed');
+ } catch (err) {
+ showToast('Refresh failed: ' + err.message, 'error');
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ if (!account) {
+ return (
+ <div className="space-y-3">
+ <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">
+ <ArrowLeft className="h-4 w-4" /> Back
+ </Button>
+ <p className="text-muted-foreground">Account not found.</p>
+ </div>
+ );
+ }
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center min-h-[50vh]">
+ <div className="flex flex-col items-center gap-3">
+ <Spinner className="size-10" />
+ <p className="text-sm text-muted-foreground">Loading X analytics...</p>
+ </div>
+ </div>
+ );
+ }
+
+ const p = profile || account;
+ const a = analytics || {};
+
+ const tweetTypeData = a.tweetTypeDistribution
+ ? Object.entries(a.tweetTypeDistribution)
+ .filter(([, v]) => v > 0)
+ .map(([key, value]) => ({
+ name: TYPE_LABELS[key] || key,
+ value,
+ color: TYPE_COLORS[key] || X_COLORS[0],
+ }))
+ : [];
+
+ const isVerified = p.verifiedType && p.verifiedType !== 'none';
+
+ return (
+ <div className="space-y-6">
+ <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">
+ <ArrowLeft className="h-4 w-4" /> Back
+ </Button>
+
+ {/* Profile header */}
+ <MainCard>
+ <div className="flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between">
+ <div className="flex items-center gap-4">
+ <Avatar className="h-16 w-16">
+ <AvatarImage src={p.profileImageUrl || p.thumbnail} />
+ <AvatarFallback style={{ background: X_BLUE }} className="text-white font-bold text-lg">
+ {(p.username || p.title || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <h1 className="text-xl font-bold">{p.displayName || p.title}</h1>
+ {isVerified && (
+ <CheckCircle2 className="h-5 w-5 text-blue-400 flex-shrink-0" />
+ )}
+ </div>
+ <p className="text-sm text-muted-foreground">@{p.username}</p>
+ {p.description && (
+ <p className="text-sm mt-1 max-w-md leading-snug">{p.description}</p>
+ )}
+ <div className="flex items-center gap-3 mt-1.5 flex-wrap">
+ {p.location && (
+ <span className="flex items-center gap-1 text-xs text-muted-foreground">
+ <MapPin className="h-3 w-3" /> {p.location}
+ </span>
+ )}
+ {p.website && (
+ <a href={p.website} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 text-xs text-blue-400 hover:underline">
+ <Link2 className="h-3 w-3" /> {p.website.replace(/^https?:\/\//, '')}
+ </a>
+ )}
+ {p.createdAt && (
+ <span className="text-xs text-muted-foreground">Joined {fmtDate(p.createdAt)}</span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ Last refreshed: {timeAgo(account.lastUpdated)}
+ </p>
+ </div>
+ </div>
+ <div className="flex gap-2 shrink-0 flex-wrap">
+ <Button
+ variant="outline"
+ size="sm"
+ className="gap-2"
+ onClick={() => navigate(`/x-tweets/${account.id}`)}
+ >
+ <FileText className="h-3.5 w-3.5" />
+ View Tweets
+ </Button>
+ <Button
+ size="sm"
+ className="gap-2"
+ onClick={handleRefresh}
+ disabled={refreshing}
+ >
+ <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />
+ {refreshing ? 'Refreshing...' : 'Refresh'}
+ </Button>
+ </div>
+ </div>
+ </MainCard>
+
+ {/* Account stats - followers/following are the core audience metrics */}
+ <MainCard>
+ <div className="flex items-center gap-2 mb-4">
+ <TrendingUp className="h-4 w-4" style={{ color: X_BLUE }} />
+ <span className="text-sm font-semibold">Account</span>
+ <span className="text-xs text-muted-foreground">followers and activity totals</span>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
+ {[
+ { label: 'Followers', value: fmtNum(p.followersCount), sub: fmtNumFull(p.followersCount) },
+ { label: 'Following', value: fmtNum(p.followingCount), sub: 'accounts followed' },
+ { label: 'Tweets', value: fmtNum(p.tweetCount), sub: 'lifetime posts' },
+ { label: 'Listed', value: fmtNum(p.listedCount ?? 0), sub: 'public lists' },
+ ].map(item => (
+ <div key={item.label} className="text-center p-3 rounded-lg bg-muted/40">
+ <p className="text-xl font-bold tabular-nums" style={{ color: X_BLUE }}>{item.value}</p>
+ <p className="text-xs font-medium mt-0.5">{item.label}</p>
+ <p className="text-[10px] text-muted-foreground mt-0.5">{item.sub}</p>
+ </div>
+ ))}
+ </div>
+ </MainCard>
+
+ {/* KPI cards */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
+ <StatCard icon={<FileText />} label="Tweets Fetched" value={fmtNum(a.fetchedTweets)} subtitle={`${a.postsLast30Days ?? 0} in the last 30 days`} gradient="blue" />
+ <StatCard icon={<Heart />} label="Total Likes" value={fmtNum(a.totalLikes)} subtitle={`Avg ${fmtNum(a.avgLikes)} per tweet`} gradient="red" />
+ <StatCard icon={<Eye />} label="Total Impressions" value={fmtNum(a.totalImpressions)} subtitle={`Avg ${fmtNum(a.avgImpressions)} per tweet`} gradient="purple" />
+ <StatCard icon={<TrendingUp />} label="Engagement Rate" value={`${a.engagementRate ?? 0}%`} subtitle="(likes+retweets+replies) / followers" gradient="green" />
+ </div>
+
+ {/* Impressions timeline + tweet type pie */}
+ {a.monthlyBreakdown?.length > 0 && (
+ <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
+ <MainCard title="Impressions Over Time" className="xl:col-span-2">
+ <ResponsiveContainer width="100%" height={240} debounce={200}>
+ <AreaChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="xGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={X_BLUE} stopOpacity={0.18} />
+ <stop offset="95%" stopColor={X_BLUE} stopOpacity={0.01} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
+ <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />
+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'impressions' ? 'Impressions' : 'Likes']} />
+ <Area type="monotone" dataKey="impressions" stroke={X_BLUE} strokeWidth={2} fill="url(#xGrad)" dot={{ fill: X_BLUE, r: 3, strokeWidth: 0 }} />
+ </AreaChart>
+ </ResponsiveContainer>
+ </MainCard>
+
+ {tweetTypeData.length > 0 && (
+ <MainCard title="Tweet Type Breakdown">
+ <ResponsiveContainer width="100%" height={240} debounce={200}>
+ <PieChart>
+ <Pie data={tweetTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={44} paddingAngle={3} strokeWidth={0}>
+ {tweetTypeData.map((entry, i) => <Cell key={i} fill={entry.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={TS} formatter={(v) => [fmtNumFull(v), 'tweets']} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
+ </PieChart>
+ </ResponsiveContainer>
+ </MainCard>
+ )}
+ </div>
+ )}
+
+ {/* Detail cards */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
+ <MainCard title="Posting Frequency">
+ <div className="space-y-3">
+ {[
+ { label: 'Last 7 days', value: `${a.postsLast7Days} tweets` },
+ { label: 'Last 30 days', value: `${a.postsLast30Days} tweets` },
+ { label: 'Last 90 days', value: `${a.postsLast90Days} tweets` },
+ ].map(item => (
+ <div key={item.label} className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">{item.label}</span>
+ <span className="text-sm font-semibold tabular-nums">{item.value}</span>
+ </div>
+ ))}
+ <Separator />
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">Avg per week</span>
+ <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perWeek ?? 0}</span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">Avg per month</span>
+ <span className="text-sm font-semibold tabular-nums">{a.postFrequency?.perMonth ?? 0}</span>
+ </div>
+ </div>
+ </MainCard>
+
+ <MainCard title="Engagement Breakdown">
+ <div className="space-y-3">
+ {[
+ { label: 'Avg likes', value: fmtNum(a.avgLikes) },
+ { label: 'Avg retweets', value: fmtNum(a.avgRetweets) },
+ { label: 'Avg replies', value: fmtNum(a.avgReplies) },
+ { label: 'Total quotes', value: fmtNum(a.totalQuotes) },
+ { label: 'Total bookmarks',value: fmtNum(a.totalBookmarks) },
+ { label: 'Avg engagement', value: fmtNum(a.avgEngagement) },
+ ].map(item => (
+ <div key={item.label} className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">{item.label}</span>
+ <span className="text-sm font-semibold tabular-nums">{item.value}</span>
+ </div>
+ ))}
+ </div>
+ </MainCard>
+
+ <MainCard title="Performance Indicators">
+ <div className="space-y-4">
+ {[
+ { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Ratio of best tweet likes to average - higher means more viral outliers' },
+ { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Like reliability across tweets - 100 means very uniform performance' },
+ ].map(item => (
+ <div key={item.label} className="space-y-1.5">
+ <div className="flex items-center justify-between text-sm">
+ <span className="font-medium">{item.label}</span>
+ <span className="text-muted-foreground tabular-nums">{item.value}</span>
+ </div>
+ <Progress value={(item.value / item.max) * 100} className="h-1.5" />
+ <p className="text-xs text-muted-foreground">{item.desc}</p>
+ </div>
+ ))}
+ </div>
+ </MainCard>
+ </div>
+
+ {/* Best posting times */}
+ {a.postsByDayOfWeek?.length > 0 && (
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
+ <MainCard title="Tweets by Day of Week">
+ <ResponsiveContainer width="100%" height={220} debounce={200}>
+ <BarChart data={a.postsByDayOfWeek} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
+ <XAxis dataKey="shortDay" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />
+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgLikes' ? 'Avg Likes' : 'Tweets']} />
+ <Bar dataKey="posts" fill={X_BLUE} opacity={0.35} radius={[3, 3, 0, 0]} />
+ <Bar dataKey="avgLikes" fill={X_BLUE} radius={[3, 3, 0, 0]} />
+ </BarChart>
+ </ResponsiveContainer>
+ {a.bestPostingDay && (
+ <p className="text-xs text-muted-foreground mt-2">
+ Best day: <span className="font-medium text-foreground">{a.bestPostingDay}</span>
+ </p>
+ )}
+ </MainCard>
+
+ <MainCard title="Tweets by Hour">
+ <ResponsiveContainer width="100%" height={220} debounce={200}>
+ <BarChart data={a.postsByHour} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
+ <XAxis dataKey="hour" tickFormatter={h => `${h}h`} tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }} axisLine={false} tickLine={false} interval={3} />
+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={36} />
+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'avgLikes' ? 'Avg Likes' : 'Tweets']} />
+ <Bar dataKey="avgLikes" fill="#0F6CBD" radius={[3, 3, 0, 0]} />
+ </BarChart>
+ </ResponsiveContainer>
+ {a.bestPostingHour && (
+ <p className="text-xs text-muted-foreground mt-2">
+ Best hour: <span className="font-medium text-foreground">{a.bestPostingHour}</span>
+ </p>
+ )}
+ </MainCard>
+ </div>
+ )}
+
+ {/* Likes timeline bar chart */}
+ {a.monthlyBreakdown?.length > 0 && (
+ <MainCard title="Likes by Month">
+ <ResponsiveContainer width="100%" height={200} debounce={200}>
+ <BarChart data={a.monthlyBreakdown} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
+ <XAxis dataKey="month" tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} axisLine={false} tickLine={false} />
+ <YAxis tick={{ fill: 'var(--muted-foreground)', fontSize: 11 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={48} />
+ <ReTooltip contentStyle={TS} formatter={(v, n) => [fmtNumFull(v), n === 'likes' ? 'Likes' : n === 'retweets' ? 'Retweets' : 'Posts']} />
+ <Bar dataKey="likes" fill={X_BLUE} radius={[3, 3, 0, 0]} />
+ <Bar dataKey="retweets" fill="#17BF63" radius={[3, 3, 0, 0]} opacity={0.8} />
+ </BarChart>
+ </ResponsiveContainer>
+ </MainCard>
+ )}
+
+ {/* Top tweets */}
+ {a.topTweets?.length > 0 && (
+ <MainCard title="Top Tweets by Likes" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">#</TableHead>
+ <TableHead>Tweet</TableHead>
+ <TableHead className="text-right">Likes</TableHead>
+ <TableHead className="text-right">Retweets</TableHead>
+ <TableHead className="text-right">Replies</TableHead>
+ <TableHead className="text-right">Impressions</TableHead>
+ <TableHead className="text-right">Posted</TableHead>
+ <TableHead className="w-8" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {a.topTweets.map((tweet, i) => (
+ <TableRow key={tweet.id}>
+ <TableCell>
+ <span className={`text-xs font-bold ${i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground'}`}>
+ {i + 1}
+ </span>
+ </TableCell>
+ <TableCell>
+ <div className="max-w-sm">
+ <p className="text-sm leading-snug line-clamp-2">{tweet.text}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-xs text-muted-foreground">
+ {TYPE_LABELS[tweet.isRetweet ? 'retweet' : tweet.isReply ? 'reply' : tweet.isQuote ? 'quote' : 'tweet']}
+ </span>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums" style={{ color: X_BLUE }}>{fmtNum(tweet.likeCount)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(tweet.retweetCount)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(tweet.replyCount)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums text-muted-foreground">{fmtNum(tweet.impressionCount)}</TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">{fmtDate(tweet.createdAt)}</TableCell>
+ <TableCell>
+ {tweet.permalink && (
+ <a href={tweet.permalink} target="_blank" rel="noopener noreferrer">
+ <Button variant="ghost" size="icon" className="size-7">
+ <ExternalLink className="h-3.5 w-3.5" />
+ </Button>
+ </a>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </MainCard>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/features/analytics/x/XTweets.jsx b/frontend/src/features/analytics/x/XTweets.jsx
new file mode 100644
index 0000000..1f65c17
--- /dev/null
+++ b/frontend/src/features/analytics/x/XTweets.jsx
@@ -0,0 +1,195 @@
+import React, { useState, useEffect, useMemo } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Badge } from '@/components/ui/badge';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
+import { Spinner } from '@/components/ui/spinner';
+import StatCard from '../../../components/ui/StatCard';
+import MainCard from '../../../components/MainCard';
+import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
+import { fmtNum, fmtNumFull, fmtDate, fmtDateShort } from '../../../utils/formatters';
+import { ArrowLeft, Search, ExternalLink, Heart, Repeat2, MessageSquare, Eye, FileText } from 'lucide-react';
+
+const TYPE_LABELS = { tweet: 'Original', retweet: 'Retweet', reply: 'Reply', quote: 'Quote' };
+const TYPE_BADGE_VARIANT = { tweet: 'secondary', retweet: 'outline', reply: 'outline', quote: 'outline' };
+
+function tweetType(t) {
+ if (t.isRetweet) return 'retweet';
+ if (t.isReply) return 'reply';
+ if (t.isQuote) return 'quote';
+ return 'tweet';
+}
+
+export default function XTweets() {
+ const { id } = useParams();
+ const { accounts, showToast } = useAppContext();
+ const navigate = useNavigate();
+ const account = accounts.find(a => a.id === id);
+
+ const [loading, setLoading] = useState(true);
+ const [tweets, setTweets] = useState([]);
+ const [search, setSearch] = useState('');
+ const [typeFilter, setTypeFilter] = useState('all');
+ const [sortBy, setSortBy] = useState('date');
+
+ useEffect(() => {
+ if (!account) return;
+ setLoading(true);
+ api.getXTweets(account.id)
+ .then(setTweets)
+ .catch(err => showToast('Failed to load tweets: ' + err.message, 'error'))
+ .finally(() => setLoading(false));
+ }, [id]);
+
+ const filtered = useMemo(() => {
+ let list = [...tweets];
+ if (typeFilter !== 'all') list = list.filter(t => tweetType(t) === typeFilter);
+ if (search.trim()) {
+ const q = search.toLowerCase();
+ list = list.filter(t => t.text?.toLowerCase().includes(q));
+ }
+ if (sortBy === 'likes') list.sort((a, b) => b.likeCount - a.likeCount);
+ else if (sortBy === 'retweets') list.sort((a, b) => b.retweetCount - a.retweetCount);
+ else if (sortBy === 'impressions') list.sort((a, b) => b.impressionCount - a.impressionCount);
+ else list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
+ return list;
+ }, [tweets, search, typeFilter, sortBy]);
+
+ const totalLikes = filtered.reduce((s, t) => s + t.likeCount, 0);
+ const totalImpressions = filtered.reduce((s, t) => s + t.impressionCount, 0);
+
+ if (!account) {
+ return (
+ <div className="space-y-3">
+ <Button variant="ghost" onClick={() => navigate('/')} className="gap-2 -ml-2 text-muted-foreground">
+ <ArrowLeft className="h-4 w-4" /> Back
+ </Button>
+ <p className="text-muted-foreground">Account not found.</p>
+ </div>
+ );
+ }
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center min-h-[50vh]">
+ <div className="flex flex-col items-center gap-3">
+ <Spinner className="size-10" />
+ <p className="text-sm text-muted-foreground">Loading tweets...</p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center gap-3 flex-wrap">
+ <Button variant="ghost" onClick={() => navigate(`/x/${account.id}`)} className="gap-2 -ml-2 text-muted-foreground">
+ <ArrowLeft className="h-4 w-4" /> {account.title}
+ </Button>
+ <span className="text-muted-foreground text-sm">/</span>
+ <span className="text-sm font-medium">Tweets</span>
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <StatCard icon={<FileText />} label="Tweets Shown" value={fmtNum(filtered.length)} subtitle={`of ${fmtNum(tweets.length)} fetched`} gradient="blue" />
+ <StatCard icon={<Heart />} label="Combined Likes" value={fmtNum(totalLikes)} subtitle="across shown tweets" gradient="red" />
+ <StatCard icon={<Eye />} label="Total Impressions" value={fmtNum(totalImpressions)} subtitle="across shown tweets" gradient="purple" />
+ </div>
+
+ <MainCard content={false}>
+ {/* Filters */}
+ <div className="flex flex-wrap gap-3 p-4 border-b border-border">
+ <div className="relative flex-1 min-w-48">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ className="pl-9"
+ placeholder="Search tweets..."
+ value={search}
+ onChange={e => setSearch(e.target.value)}
+ />
+ </div>
+ <Select value={typeFilter} onValueChange={setTypeFilter}>
+ <SelectTrigger className="w-36">
+ <SelectValue placeholder="Type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All types</SelectItem>
+ <SelectItem value="tweet">Original</SelectItem>
+ <SelectItem value="retweet">Retweets</SelectItem>
+ <SelectItem value="reply">Replies</SelectItem>
+ <SelectItem value="quote">Quotes</SelectItem>
+ </SelectContent>
+ </Select>
+ <Select value={sortBy} onValueChange={setSortBy}>
+ <SelectTrigger className="w-40">
+ <SelectValue placeholder="Sort by" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="date">Newest first</SelectItem>
+ <SelectItem value="likes">Most likes</SelectItem>
+ <SelectItem value="retweets">Most retweets</SelectItem>
+ <SelectItem value="impressions">Most impressions</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {filtered.length === 0 ? (
+ <div className="py-16 text-center text-sm text-muted-foreground">
+ No tweets match your filters.
+ </div>
+ ) : (
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">#</TableHead>
+ <TableHead>Tweet</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead className="text-right">Likes</TableHead>
+ <TableHead className="text-right">Retweets</TableHead>
+ <TableHead className="text-right">Impressions</TableHead>
+ <TableHead className="text-right">Date</TableHead>
+ <TableHead className="w-8" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.map((tweet, i) => {
+ const type = tweetType(tweet);
+ return (
+ <TableRow key={tweet.id}>
+ <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>
+ <TableCell>
+ <p className="text-sm leading-snug line-clamp-2 max-w-sm">{tweet.text}</p>
+ </TableCell>
+ <TableCell>
+ <Badge variant={TYPE_BADGE_VARIANT[type]} className="text-xs whitespace-nowrap">
+ {TYPE_LABELS[type]}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums font-medium text-[#1D9BF0]">{fmtNum(tweet.likeCount)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(tweet.retweetCount)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums text-muted-foreground">{fmtNum(tweet.impressionCount)}</TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground whitespace-nowrap">{fmtDateShort(tweet.createdAt)}</TableCell>
+ <TableCell>
+ {tweet.permalink && (
+ <a href={tweet.permalink} target="_blank" rel="noopener noreferrer">
+ <Button variant="ghost" size="icon" className="size-7">
+ <ExternalLink className="h-3.5 w-3.5" />
+ </Button>
+ </a>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ </MainCard>
+ </div>
+ );
+}
diff --git a/frontend/src/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsx
index 44482b2..c470a15 100644
--- a/frontend/src/layout/Sidebar.jsx
+++ b/frontend/src/layout/Sidebar.jsx
@@ -8,7 +8,7 @@ import {
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
LayoutDashboard, PlaySquare, Scissors, Camera,
- Upload, Users, Settings, Flame,
+ Upload, Users, Settings, Flame, Twitter,
} from 'lucide-react';
import { useAppContext } from '../context/AppContext';
@@ -21,6 +21,7 @@ const NAV_GROUPS = [
{ path: '/shorts', label: 'Shorts', icon: Scissors },
{ path: '/reels', label: 'IG Content', icon: Camera },
{ path: '/reddit-posts', label: 'Reddit Posts', icon: Flame },
+ { path: '/x-tweets', label: 'X Tweets', icon: Twitter },
],
},
{
@@ -104,9 +105,10 @@ export default function AppSidebar() {
{accounts.map((acc) => {
const isIG = acc.platform === 'instagram';
const isReddit = acc.platform === 'reddit';
- const path = isIG ? `/instagram/${acc.id}` : isReddit ? `/reddit/${acc.id}` : `/channel/${acc.id}`;
+ const isX = acc.platform === 'x';
+ const path = isIG ? `/instagram/${acc.id}` : isReddit ? `/reddit/${acc.id}` : isX ? `/x/${acc.id}` : `/channel/${acc.id}`;
const initials = (acc.title || '?').slice(0, 2).toUpperCase();
- const avatarBg = isIG ? '#ec4899' : isReddit ? '#f97316' : '#ef4444';
+ const avatarBg = isIG ? '#ec4899' : isReddit ? '#f97316' : isX ? '#1D9BF0' : '#ef4444';
return (
<SidebarMenuItem key={acc.id}>
<SidebarMenuButton
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 99199ae..f8ac4de 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -65,6 +65,11 @@ export const api = {
getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
+ // X (Twitter) accounts
+ addXAccount: (username, authToken, ct0) => request('/accounts/x', { method: 'POST', body: JSON.stringify({ username, authToken, ct0 }) }),
+ getXAnalytics: (id) => request(`/accounts/${id}/x-analytics`),
+ getXTweets: (id) => request(`/accounts/${id}/x-tweets`),
+
// GitHub settings
getGithubSettings: () => request('/settings/github'),
saveGithubSettings: (data) => request('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),
diff --git a/frontend/src/utils/formatters.js b/frontend/src/utils/formatters.js
index 6313d8d..602557d 100644
--- a/frontend/src/utils/formatters.js
+++ b/frontend/src/utils/formatters.js
@@ -87,6 +87,16 @@ export function normalizeAccount(acct) {
commentKarma: acct.commentKarma || 0,
};
}
+ if (acct.platform === 'x') {
+ return {
+ ...acct,
+ title: acct.title || `@${acct.username}`,
+ thumbnail: acct.profileImageUrl || '',
+ followersCount: acct.followersCount || 0,
+ followingCount: acct.followingCount || 0,
+ tweetCount: acct.tweetCount || 0,
+ };
+ }
return {
...acct,
title: acct.title || acct.name || acct.channelTitle || acct.channelId,