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(reddit): add Reddit platform integration with cookie-based auth

spacesdrive6d2d1db1b853
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c53750..45fa079 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,22 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]
+### Added
+
+**Reddit Integration**
+- `POST /api/accounts/reddit` - add Reddit account by username with optional session cookie
+- `GET /api/accounts/:id/reddit-analytics` - full analytics: profile, score stats, subreddit breakdown, posting time patterns, monthly breakdown, virality and consistency scores
+- `GET /api/accounts/:id/reddit-posts` - paginated post list (up to 100 posts, cached in Redis)
+- `backend/services/reddit.js` - Reddit public JSON API client (`redditFetch`), `fetchRedditProfile`, `fetchRedditPosts`, `computeRedditAnalytics`, `safeRedditAccount`
+- Reddit cache key `reddit:{userId}:{accountId}` in Upstash Redis; invalidated on account delete
+- `frontend/src/features/analytics/reddit/RedditAnalytics.jsx` - detailed stats page with karma breakdown, score timeline, post type distribution, day/hour analysis, subreddit breakdown, top posts table
+- `frontend/src/features/analytics/reddit/RedditPosts.jsx` - filterable/sortable post explorer with subreddit filter, search, sort by score/comments/date
+- Reddit tab in Account Manager dialog (username + optional session cookie)
+- Reddit accounts section in Account Manager accounts list
+- Reddit accounts included in Overview totals, leaderboards, and all-accounts table
+- Reddit accounts in Sidebar quick navigation (routes to `/reddit/:id`)
+- Routes `/reddit/:id` and `/reddit-posts/:id` in App.jsx
+
### Fixed
- Strip non-ASCII characters from `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` env vars in `scripts/publish-scheduled.js` using `/[^\x20-\x7E]/g` to defend against BOM injected by PowerShell 5.1 when setting GitHub Actions secrets
- Replaced embedded literal U+FEFF in BOM-strip regex with proper `` unicode escape
diff --git a/DECISIONS.md b/DECISIONS.md
index 8685c3a..472f401 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -285,3 +285,28 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- GitHub PAT is stored in plaintext in Supabase jsonb - acceptable for a self-hosted deployment where the admin trusts the storage layer
- The `settings` table design (user_id + key + jsonb value) is generic enough to hold any future per-user configuration
+
+---
+
+## ADR-013: Reddit integration uses cookie-based auth via public JSON API
+
+**Date:** 2026-07-10
+**Status:** Accepted
+
+**Decision:** Reddit accounts are added by username. An optional `reddit_session` cookie value can be provided for private accounts or improved rate limits. Analytics are fetched from Reddit's public JSON API (`https://www.reddit.com/user/{username}/about.json` and `/submitted.json`).
+
+**Alternatives considered:**
+- Reddit OAuth 2.0 (script app): Requires registering a Reddit app, storing `REDDIT_CLIENT_ID` and `REDDIT_CLIENT_SECRET` as Worker secrets, and implementing the token grant flow. Higher complexity for a self-hosted product.
+- Reddit OAuth 2.0 (web app): Full OAuth redirect flow matching the Instagram pattern. Requires a registered Reddit app and callback route.
+
+**Reasoning:**
+- Reddit's public JSON API returns full post data for public accounts with no authentication at all
+- Cookie-based auth extends this to private accounts without any app registration
+- No new Worker secrets are required - the cookie is per-user data stored in `accounts.data.cookie`
+- The cookie is stripped by `safeRedditAccount()` before any API response, matching the Instagram access token pattern
+- For most self-hosted users tracking their own public Reddit account, the public API is sufficient
+
+**Trade-offs:**
+- `reddit_session` cookies expire when the user's Reddit session ends - the user must re-enter the cookie if it expires
+- Reddit's public API has stricter rate limits (60 req/10min without auth) than the OAuth API (600 req/10min)
+- No token refresh cron - unlike Instagram, Reddit session cookies cannot be programmatically refreshed
diff --git a/backend/lib/cache.js b/backend/lib/cache.js
index eaa8b35..d9ec138 100644
--- a/backend/lib/cache.js
+++ b/backend/lib/cache.js
@@ -32,6 +32,21 @@ export async function deleteIGCache(redis, userId, accountId) {
try { await redis.del(`ig:${userId}:${accountId}`); } catch { /* non-fatal */ }
}
+export async function getRedditCache(redis, userId, accountId) {
+ if (!redis) return null;
+ try { return (await redis.get(`reddit:${userId}:${accountId}`)) || null; } catch { return null; }
+}
+
+export async function setRedditCache(redis, userId, accountId, data) {
+ if (!redis) return;
+ try { await redis.set(`reddit:${userId}:${accountId}`, data); } catch { /* non-fatal */ }
+}
+
+export async function deleteRedditCache(redis, userId, accountId) {
+ if (!redis) return;
+ try { await redis.del(`reddit:${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 8b4ba0b..5664e6d 100644
--- a/backend/routes/accounts.js
+++ b/backend/routes/accounts.js
@@ -2,15 +2,17 @@ import { Hono } from 'hono';
import {
getAccounts, getAccountById, createAccount, updateAccount, deleteAccount,
} from '../lib/db.js';
-import { deleteVideosCache, deleteIGCache } from '../lib/cache.js';
+import { deleteVideosCache, deleteIGCache, deleteRedditCache } 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';
const app = new Hono();
function safeAccount(account) {
const copy = { ...account };
delete copy.accessToken;
+ delete copy.cookie;
return copy;
}
@@ -82,6 +84,43 @@ app.post('/accounts', async (c) => {
}
});
+app.post('/accounts/reddit', async (c) => {
+ try {
+ const { username, cookie } = await c.req.json();
+ if (!username) return c.json({ success: false, message: 'Username is required' }, 400);
+
+ const supabase = c.get('supabase');
+ const userId = c.get('userId');
+
+ const profile = await fetchRedditProfile(username.replace(/^u\//i, '').trim(), cookie || null);
+
+ const accounts = await getAccounts(supabase, userId);
+ if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {
+ return c.json({ success: false, message: 'This Reddit account is already added' }, 400);
+ }
+
+ const newAccount = {
+ id: Date.now().toString() + Math.random().toString(36).substring(2, 6),
+ platform: 'reddit',
+ username: profile.username,
+ title: `u/${profile.username}`,
+ totalKarma: profile.totalKarma,
+ postKarma: profile.postKarma,
+ commentKarma: profile.commentKarma,
+ iconUrl: profile.iconUrl,
+ createdAt: profile.createdAt,
+ cookie: cookie || null,
+ addedAt: new Date().toISOString(),
+ lastUpdated: new Date().toISOString(),
+ };
+
+ await createAccount(supabase, newAccount, userId);
+ return c.json({ success: true, account: safeRedditAccount(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();
@@ -160,6 +199,15 @@ app.post('/accounts/refresh-all', async (c) => {
username: profile.username,
profilePictureUrl: profile.profilePictureUrl,
};
+ } else if (account.platform === 'reddit') {
+ const profile = await fetchRedditProfile(account.username, account.cookie ?? null);
+ updates = {
+ ...updates,
+ totalKarma: profile.totalKarma,
+ postKarma: profile.postKarma,
+ commentKarma: profile.commentKarma,
+ iconUrl: profile.iconUrl,
+ };
} else {
if (!apiKey) throw new Error('No YouTube API key');
const channelData = await fetchChannelData(account.channelId, apiKey);
@@ -237,6 +285,15 @@ app.post('/accounts/:id/refresh', async (c) => {
biography: profile.biography,
website: profile.website,
};
+ } else if (account.platform === 'reddit') {
+ const profile = await fetchRedditProfile(account.username, account.cookie ?? null);
+ updates = {
+ ...updates,
+ totalKarma: profile.totalKarma,
+ postKarma: profile.postKarma,
+ commentKarma: profile.commentKarma,
+ iconUrl: profile.iconUrl,
+ };
} else {
const apiKey = c.env.YOUTUBE_API_KEY;
if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);
@@ -275,6 +332,7 @@ app.delete('/accounts/:id', async (c) => {
deleteAccount(supabase, id, userId),
deleteVideosCache(redis, userId, id),
deleteIGCache(redis, userId, id),
+ deleteRedditCache(redis, userId, id),
]);
return c.json({ success: true });
} catch (err) {
diff --git a/backend/routes/reddit.js b/backend/routes/reddit.js
new file mode 100644
index 0000000..9ea0cde
--- /dev/null
+++ b/backend/routes/reddit.js
@@ -0,0 +1,57 @@
+import { Hono } from 'hono';
+import { getAccountById } from '../lib/db.js';
+import { getRedditCache, setRedditCache } from '../lib/cache.js';
+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.js';
+
+const router = new Hono();
+
+// Full analytics: profile + computed stats + recent posts
+router.get('/accounts/:id/reddit-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 !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+
+ const cached = await getRedditCache(redis, userId, id);
+ if (cached) return c.json(cached);
+
+ const [profile, posts] = await Promise.all([
+ fetchRedditProfile(account.username, account.cookie ?? null),
+ fetchRedditPosts(account.username, account.cookie ?? null, 100),
+ ]);
+ const analytics = computeRedditAnalytics(profile, posts);
+ const result = { profile, analytics, posts };
+
+ await setRedditCache(redis, userId, id, result);
+ return c.json(result);
+ } catch (err) {
+ console.error(`GET /accounts/${id}/reddit-analytics:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+// Post list only (served from cache when available)
+router.get('/accounts/:id/reddit-posts', 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 !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+
+ const cached = await getRedditCache(redis, userId, id);
+ if (cached?.posts) return c.json(cached.posts);
+
+ const posts = await fetchRedditPosts(account.username, account.cookie ?? null, 100);
+ return c.json(posts);
+ } catch (err) {
+ console.error(`GET /accounts/${id}/reddit-posts:`, err.message);
+ return c.json({ error: err.message }, 500);
+ }
+});
+
+export default router;
diff --git a/backend/server.js b/backend/server.js
index 864b48e..b181dd3 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -9,6 +9,7 @@ import analyticsRouter from './routes/analytics.js';
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 { urlHandler, callbackHandler } from './routes/instagramAuth.js';
import { processScheduledPosts } from './utils/scheduler.js';
import { autoRefreshInstagramTokens } from './services/instagram.js';
@@ -51,6 +52,7 @@ api.route('/', analyticsRouter);
api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
+api.route('/', redditRouter);
// Instagram OAuth URL generator - protected (needs userId to create state token)
api.get('/auth/instagram/url', urlHandler);
diff --git a/backend/services/reddit.js b/backend/services/reddit.js
new file mode 100644
index 0000000..002c2a7
--- /dev/null
+++ b/backend/services/reddit.js
@@ -0,0 +1,248 @@
+// fetch is a global in Cloudflare Workers - no import needed.
+
+const REDDIT_BASE = 'https://www.reddit.com';
+const USER_AGENT = 'Twiligent/1.0 (social analytics dashboard; personal use)';
+
+async function redditFetch(path, cookie = null) {
+ const headers = {
+ 'User-Agent': USER_AGENT,
+ 'Accept': 'application/json',
+ };
+ if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
+
+ const res = await fetch(`${REDDIT_BASE}${path}`, { headers });
+
+ if (res.status === 404) throw new Error('Reddit user not found - check the username');
+ if (res.status === 403) throw new Error('Account is private or suspended');
+ if (res.status === 429) throw new Error('Reddit rate limit hit - try again in a moment');
+ if (!res.ok) throw new Error(`Reddit API ${res.status}: ${res.statusText}`);
+
+ const data = await res.json();
+ if (data.error) throw new Error(data.message || 'Reddit API error');
+ return data;
+}
+
+export async function fetchRedditProfile(username, cookie = null) {
+ const data = await redditFetch(`/user/${username}/about.json`, cookie);
+ const u = data.data;
+ return {
+ username: u.name,
+ totalKarma: u.total_karma ?? (u.link_karma + u.comment_karma),
+ postKarma: u.link_karma ?? 0,
+ commentKarma: u.comment_karma ?? 0,
+ awardeeKarma: u.awardee_karma ?? 0,
+ awarderKarma: u.awarder_karma ?? 0,
+ iconUrl: (u.icon_img || u.snoovatar_img || '').replace(/&/g, '&'),
+ createdAt: u.created_utc ? new Date(u.created_utc * 1000).toISOString() : '',
+ isGold: u.is_gold ?? false,
+ isMod: u.is_mod ?? false,
+ verified: u.verified ?? false,
+ };
+}
+
+export async function fetchRedditPosts(username, cookie = null, limit = 100) {
+ let allPosts = [];
+ let after = null;
+ let pages = 0;
+
+ while (pages < 10 && allPosts.length < limit) {
+ const qs = new URLSearchParams({
+ limit: String(Math.min(100, limit - allPosts.length)),
+ sort: 'new',
+ });
+ if (after) qs.set('after', after);
+
+ const data = await redditFetch(`/user/${username}/submitted.json?${qs}`, cookie);
+ const children = data.data?.children ?? [];
+ if (children.length === 0) break;
+
+ for (const child of children) allPosts.push(child.data);
+ after = data.data?.after ?? null;
+ if (!after) break;
+ pages++;
+ }
+
+ return allPosts.slice(0, limit).map(p => ({
+ id: p.id,
+ title: p.title,
+ subreddit: p.subreddit,
+ subredditPrefixed: p.subreddit_name_prefixed ?? `r/${p.subreddit}`,
+ score: p.score ?? 0,
+ upvoteRatio: p.upvote_ratio ?? 0,
+ numComments: p.num_comments ?? 0,
+ url: p.url ?? '',
+ permalink: `https://reddit.com${p.permalink}`,
+ thumbnail: (p.thumbnail && p.thumbnail.startsWith('http')) ? p.thumbnail : '',
+ mediaType: p.is_video ? 'video' : (p.post_hint === 'image' ? 'image' : p.is_self ? 'text' : 'link'),
+ isSelf: p.is_self ?? false,
+ isVideo: p.is_video ?? false,
+ isNsfw: p.over_18 ?? false,
+ createdAt: p.created_utc ? new Date(p.created_utc * 1000).toISOString() : '',
+ flair: p.link_flair_text ?? '',
+ }));
+}
+
+export function computeRedditAnalytics(profile, posts) {
+ const empty = {
+ fetchedPosts: 0, totalScore: 0, avgScore: 0, medianScore: 0,
+ totalComments: 0, avgComments: 0, avgUpvoteRatio: 0,
+ topPosts: [], worstPosts: [], subredditBreakdown: [],
+ mediaTypeDistribution: {}, postsByDayOfWeek: [], postsByHour: [],
+ monthlyBreakdown: [], engagementTimeline: [],
+ postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
+ postFrequency: { perWeek: 0, perMonth: 0 },
+ viralityScore: 0, consistencyScore: 0,
+ bestPostingDay: '', bestPostingHour: '',
+ };
+
+ if (!posts || posts.length === 0) return empty;
+
+ const totalScore = posts.reduce((s, p) => s + p.score, 0);
+ const totalComments = posts.reduce((s, p) => s + p.numComments, 0);
+ const avgScore = Math.round(totalScore / posts.length);
+ const avgComments = Math.round(totalComments / posts.length);
+ const avgUpvoteRatio = parseFloat(
+ (posts.reduce((s, p) => s + p.upvoteRatio, 0) / posts.length * 100).toFixed(1)
+ );
+
+ const sortedScores = [...posts].map(p => p.score).sort((a, b) => a - b);
+ const mid = Math.floor(sortedScores.length / 2);
+ const medianScore = sortedScores.length % 2
+ ? sortedScores[mid]
+ : Math.round((sortedScores[mid - 1] + sortedScores[mid]) / 2);
+
+ const byScore = [...posts].sort((a, b) => b.score - a.score);
+
+ // Subreddit breakdown
+ const subMap = {};
+ posts.forEach(p => {
+ const sub = p.subreddit;
+ if (!subMap[sub]) subMap[sub] = { subreddit: sub, posts: 0, totalScore: 0, totalComments: 0 };
+ subMap[sub].posts++;
+ subMap[sub].totalScore += p.score;
+ subMap[sub].totalComments += p.numComments;
+ });
+ const subredditBreakdown = Object.values(subMap)
+ .map(s => ({
+ ...s,
+ avgScore: Math.round(s.totalScore / s.posts),
+ avgComments: Math.round(s.totalComments / s.posts),
+ }))
+ .sort((a, b) => b.posts - a.posts)
+ .slice(0, 20);
+
+ // Media type distribution
+ const mediaTypeDistribution = {};
+ posts.forEach(p => { mediaTypeDistribution[p.mediaType] = (mediaTypeDistribution[p.mediaType] ?? 0) + 1; });
+
+ // Day of week and hour analysis
+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+ const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, score: 0, comments: 0 }));
+ const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, score: 0 }));
+ const dates = posts
+ .map(p => p.createdAt ? new Date(p.createdAt) : null)
+ .filter(Boolean);
+
+ dates.forEach((d, i) => {
+ const day = d.getDay();
+ dayBuckets[day].count++;
+ dayBuckets[day].score += posts[i]?.score ?? 0;
+ dayBuckets[day].comments += posts[i]?.numComments ?? 0;
+ const h = d.getHours();
+ hourBuckets[h].count++;
+ hourBuckets[h].score += posts[i]?.score ?? 0;
+ });
+
+ const postsByDayOfWeek = dayBuckets.map((b, i) => ({
+ day: dayNames[i], shortDay: dayNames[i].slice(0, 3),
+ posts: b.count,
+ avgScore: b.count > 0 ? Math.round(b.score / b.count) : 0,
+ avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,
+ }));
+ const bestDayObj = postsByDayOfWeek.reduce(
+ (best, d) => d.avgScore > best.avgScore ? d : best,
+ postsByDayOfWeek[0]
+ );
+
+ const postsByHour = hourBuckets.map((b, i) => ({
+ hour: i, label: `${i}:00`,
+ posts: b.count,
+ avgScore: b.count > 0 ? Math.round(b.score / b.count) : 0,
+ }));
+ const bestHourObj = postsByHour.reduce(
+ (best, h) => h.avgScore > best.avgScore ? h : best,
+ postsByHour[0]
+ );
+
+ // Monthly breakdown
+ const monthMap = {};
+ posts.forEach(p => {
+ if (!p.createdAt) return;
+ const d = new Date(p.createdAt);
+ if (isNaN(d)) return;
+ const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
+ if (!monthMap[key]) monthMap[key] = { posts: 0, score: 0, comments: 0 };
+ monthMap[key].posts++;
+ monthMap[key].score += p.score;
+ monthMap[key].comments += p.numComments;
+ });
+ const monthlyBreakdown = Object.entries(monthMap)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([month, s]) => ({
+ month, posts: s.posts, score: s.score, comments: s.comments,
+ avgScore: Math.round(s.score / s.posts),
+ }));
+
+ // Recency counts
+ 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((posts.length / spanDays * 7).toFixed(1));
+ perMonth = parseFloat((posts.length / spanDays * 30).toFixed(1));
+ }
+
+ // Virality and consistency
+ const bestScore = byScore[0]?.score ?? 0;
+ const viralityScore = avgScore > 0 ? parseFloat((bestScore / avgScore).toFixed(1)) : 0;
+
+ let consistencyScore = 0;
+ if (posts.length >= 3) {
+ const scores = posts.map(p => p.score);
+ const mean = scores.reduce((s, v) => s + v, 0) / scores.length;
+ const variance = scores.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / scores.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 {
+ fetchedPosts: posts.length,
+ totalScore, avgScore, medianScore,
+ totalComments, avgComments, avgUpvoteRatio,
+ topPosts: byScore.slice(0, 10),
+ worstPosts: byScore.slice(-5).reverse(),
+ subredditBreakdown,
+ mediaTypeDistribution,
+ postsByDayOfWeek, bestPostingDay: bestDayObj?.day ?? '',
+ postsByHour, bestPostingHour: bestHourObj?.posts > 0 ? bestHourObj.label : '',
+ monthlyBreakdown, engagementTimeline: monthlyBreakdown,
+ postsLast7Days, postsLast30Days, postsLast90Days,
+ postFrequency: { perWeek, perMonth },
+ viralityScore, consistencyScore,
+ };
+}
+
+// Strips the session cookie before any API response - treat cookie like an access token.
+export function safeRedditAccount(account) {
+ const copy = { ...account };
+ delete copy.cookie;
+ return copy;
+}
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index 6fe4156..86f5d0b 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -24,6 +24,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` |
| `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 bc0e55c..6b4fbe4 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -61,6 +61,13 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
| GET | `/api/process-scheduled` | `routes/scheduledPosts.js` | Manual trigger - runs `processScheduledPosts()` immediately (dev/test) |
| POST | `/api/process-scheduled` | `routes/scheduledPosts.js` | Same as above |
+### Reddit
+| Method | Path | File | Purpose |
+|---|---|---|---|
+| POST | `/api/accounts/reddit` | `routes/accounts.js` | Add Reddit account by username + optional session cookie |
+| 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 |
+
### Settings
| Method | Path | File | Purpose |
|---|---|---|---|
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index e144eaa..b0a77f8 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -97,6 +97,31 @@ async function ytFetch(path, params, env) {
---
+## `backend/services/reddit.js`
+
+### HTTP Client
+
+All Reddit public JSON API calls go through `redditFetch(path, cookie)`. Requests include a descriptive `User-Agent` header (required by Reddit). Cookie is optional - if provided, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits.
+
+### Key Functions
+
+| Function | Purpose |
+|---|---|
+| `fetchRedditProfile(username, cookie)` | Fetches profile data from `/user/{username}/about.json` |
+| `fetchRedditPosts(username, cookie, limit)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |
+| `computeRedditAnalytics(profile, posts)` | Computes score stats, subreddit breakdown, posting time patterns, monthly breakdown, virality/consistency scores |
+| `safeRedditAccount(account)` | Strips the `cookie` field before any API response |
+
+### `safeRedditAccount(account)`
+
+Strips the `cookie` field before the account object is returned in any API response, identical in purpose to `safeAccount()` for Instagram access tokens.
+
+### No Worker secrets required
+
+Reddit integration requires no Worker secrets. The session cookie is a per-user credential stored in `accounts.data.cookie` (in the Supabase DB). It is 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/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 4212f73..33d6960 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -67,10 +67,12 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
| Feature | Path | Description |
|---|---|---|
-| Overview | `/` | Aggregate KPIs across all connected accounts |
-| Accounts | `/accounts` | Connect/disconnect social accounts |
+| Overview | `/` | Aggregate KPIs across all connected accounts (YouTube, Instagram, Reddit) |
+| Accounts | `/accounts` | Connect/disconnect social accounts (YouTube, Instagram, Reddit) |
| Channel Analytics | `/channel/:id` | YouTube analytics for one channel |
| Instagram Analytics | `/instagram/:id` | Instagram analytics for one account |
+| Reddit Analytics | `/reddit/:id` | Reddit analytics for one account - karma, post scores, subreddit breakdown, timing |
+| Reddit Posts | `/reddit-posts/:id` | Searchable and sortable post list for a Reddit account |
| 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 a829631..a93d615 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -14,6 +14,8 @@ The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `Browser
| `/accounts` | `Accounts.jsx` | Connect/disconnect accounts |
| `/channel/:id` | `ChannelAnalytics.jsx` | `:id` = account.id for YouTube accounts |
| `/instagram/:id` | `InstagramAnalytics.jsx` | `:id` = account.id for Instagram accounts |
+| `/reddit/:id` | `RedditAnalytics.jsx` | `:id` = account.id for Reddit accounts |
+| `/reddit-posts/:id` | `RedditPosts.jsx` | `:id` = account.id; filterable/sortable post explorer |
| `/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 5d72561..4af9a88 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -18,6 +18,8 @@ const ReelsExplorer = lazy(() => import('./features/analytics/reels/ReelsEx
const UploadContent = lazy(() => import('./features/publishing/UploadContent'));
const AccountManager = lazy(() => import('./features/accounts/AccountManager'));
const Settings = lazy(() => import('./features/settings/Settings'));
+const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
+const RedditPosts = lazy(() => import('./features/analytics/reddit/RedditPosts'));
const router = createBrowserRouter([
{
@@ -41,8 +43,10 @@ const router = createBrowserRouter([
{ path: 'shorts', element: <ShortsExplorer /> },
{ path: 'reels', element: <ReelsExplorer /> },
{ path: 'upload', element: <UploadContent /> },
- { path: 'accounts', element: <AccountManager /> },
- { path: 'settings', element: <Settings /> },
+ { path: 'accounts', element: <AccountManager /> },
+ { path: 'settings', element: <Settings /> },
+ { path: 'reddit/:id', element: <RedditAnalytics /> },
+ { path: 'reddit-posts/:id', element: <RedditPosts /> },
{ path: '*', element: <Navigate to="/" replace /> },
],
},
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index e237032..ca81de3 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,
+ Tv, Camera, Link2, Info, ExternalLink, MessageSquare,
} from 'lucide-react';
import MainCard from '../../components/MainCard';
import { useAppContext } from '../../context/AppContext';
@@ -26,8 +26,11 @@ export default function AccountManager() {
const [resolving, setResolving] = useState(false);
const [resolved, setResolved] = useState(null);
const [adding, setAdding] = useState(false);
- const [connecting, setConnecting] = useState(false);
- const [refreshingId, setRefreshingId] = useState(null);
+ const [connecting, setConnecting] = useState(false);
+ const [redditUsername, setRedditUsername] = useState('');
+ const [redditCookie, setRedditCookie] = useState('');
+ const [addingReddit, setAddingReddit] = useState(false);
+ const [refreshingId, setRefreshingId] = useState(null);
// Handle Instagram OAuth redirect result (?ig_connected=true or ?ig_error=...)
useEffect(() => {
@@ -128,14 +131,34 @@ export default function AccountManager() {
}
};
+ const handleAddReddit = async () => {
+ if (!redditUsername.trim()) return;
+ setAddingReddit(true);
+ try {
+ await api.addRedditAccount(redditUsername.trim(), redditCookie.trim() || null);
+ showToast('Reddit account added');
+ setRedditUsername('');
+ setRedditCookie('');
+ closeDialog();
+ loadAccounts();
+ } catch (err) {
+ showToast('Failed to add Reddit account: ' + err.message, 'error');
+ } finally {
+ setAddingReddit(false);
+ }
+ };
+
const closeDialog = () => {
setDialogOpen(false);
setResolved(null);
setInput('');
+ setRedditUsername('');
+ setRedditCookie('');
};
- const ytAccounts = accounts.filter(a => a.platform !== 'instagram');
- const igAccounts = accounts.filter(a => a.platform === 'instagram');
+ const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');
+ const igAccounts = accounts.filter(a => a.platform === 'instagram');
+ const redditAccounts = accounts.filter(a => a.platform === 'reddit');
return (
<div className="space-y-6">
@@ -144,7 +167,11 @@ export default function AccountManager() {
<div>
<h1 className="text-2xl font-bold tracking-tight">Manage Accounts</h1>
<p className="text-sm text-muted-foreground mt-0.5">
- {ytAccounts.length} YouTube channels · {igAccounts.length} Instagram accounts
+ {[
+ ytAccounts.length ? `${ytAccounts.length} YouTube` : null,
+ igAccounts.length ? `${igAccounts.length} Instagram` : null,
+ redditAccounts.length ? `${redditAccounts.length} Reddit` : null,
+ ].filter(Boolean).join(' · ') || 'No accounts added yet'}
</p>
</div>
<div className="flex gap-2">
@@ -191,7 +218,7 @@ export default function AccountManager() {
<AccountCard
key={acct.id}
acct={acct}
- isIG={false}
+ platform="youtube"
metrics={[
{ label: 'Subscribers', value: fmtNum(acct.subscriberCount), className: 'bg-red-50 text-red-700' },
{ label: 'Views', value: fmtNum(acct.viewCount), className: 'bg-blue-50 text-blue-700' },
@@ -219,7 +246,7 @@ export default function AccountManager() {
<AccountCard
key={acct.id}
acct={acct}
- isIG={true}
+ platform="instagram"
metrics={[
{ label: 'Followers', value: fmtNum(acct.followersCount), className: 'bg-pink-50 text-pink-700' },
{ label: 'Following', value: fmtNum(acct.followsCount), className: 'bg-purple-50 text-purple-700' },
@@ -233,6 +260,34 @@ export default function AccountManager() {
</div>
</div>
)}
+
+ {/* Reddit */}
+ {redditAccounts.length > 0 && (
+ <div>
+ <div className="flex items-center gap-2 mb-3">
+ <MessageSquare className="h-5 w-5 text-orange-500" />
+ <h2 className="text-base font-semibold">Reddit Accounts</h2>
+ <Badge variant="outline" className="border-orange-200 bg-orange-50 text-orange-600 text-xs">{redditAccounts.length}</Badge>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
+ {redditAccounts.map(acct => (
+ <AccountCard
+ key={acct.id}
+ acct={acct}
+ platform="reddit"
+ metrics={[
+ { label: 'Total Karma', value: fmtNum(acct.totalKarma), className: 'bg-orange-50 text-orange-700' },
+ { label: 'Post Karma', value: fmtNum(acct.postKarma), className: 'bg-red-50 text-red-700' },
+ { label: 'Comment Karma', value: fmtNum(acct.commentKarma), className: 'bg-amber-50 text-amber-700' },
+ ]}
+ refreshingId={refreshingId}
+ onRefresh={handleRefreshOne}
+ onDelete={handleDelete}
+ />
+ ))}
+ </div>
+ </div>
+ )}
</div>
)}
@@ -252,6 +307,9 @@ export default function AccountManager() {
<TabsTrigger value="instagram" className="flex-1 gap-1.5">
<Camera className="h-3.5 w-3.5" /> Instagram
</TabsTrigger>
+ <TabsTrigger value="reddit" className="flex-1 gap-1.5">
+ <MessageSquare className="h-3.5 w-3.5" /> Reddit
+ </TabsTrigger>
</TabsList>
<TabsContent value="youtube" className="space-y-4 mt-4">
@@ -311,7 +369,7 @@ export default function AccountManager() {
{connecting
? <RefreshCw className="h-4 w-4 animate-spin" />
: <ExternalLink className="h-4 w-4" />}
- {connecting ? 'Opening Instagram…' : 'Connect with Instagram'}
+ {connecting ? 'Opening Instagram...' : 'Connect with Instagram'}
</Button>
<Alert>
<Info className="h-4 w-4" />
@@ -320,6 +378,41 @@ export default function AccountManager() {
</AlertDescription>
</Alert>
</TabsContent>
+
+ <TabsContent value="reddit" className="space-y-4 mt-4">
+ <p className="text-sm text-muted-foreground">
+ Enter your Reddit username to track your public post analytics.
+ </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">u/</span>
+ <Input
+ className="pl-8"
+ value={redditUsername}
+ onChange={e => setRedditUsername(e.target.value)}
+ placeholder="your_username"
+ onKeyDown={e => e.key === 'Enter' && handleAddReddit()}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-muted-foreground">
+ Session Cookie (optional - for private accounts or higher rate limits)
+ </label>
+ <Input
+ type="password"
+ value={redditCookie}
+ onChange={e => setRedditCookie(e.target.value)}
+ placeholder="reddit_session cookie value"
+ />
+ </div>
+ </div>
+ <Alert>
+ <Info className="h-4 w-4" />
+ <AlertDescription className="text-xs">
+ Public accounts work without a cookie. To get your session cookie, open Reddit in a browser, open DevTools (F12), go to Application &gt; Cookies, and copy the <code className="bg-muted px-1 rounded">reddit_session</code> value.
+ </AlertDescription>
+ </Alert>
+ </TabsContent>
</Tabs>
<DialogFooter>
@@ -330,6 +423,12 @@ export default function AccountManager() {
Add Channel
</Button>
)}
+ {dialogTab === 'reddit' && (
+ <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || addingReddit} className="gap-1.5">
+ {addingReddit && <RefreshCw className="h-3.5 w-3.5 animate-spin" />}
+ Add Reddit Account
+ </Button>
+ )}
</DialogFooter>
</DialogContent>
</Dialog>
@@ -337,22 +436,29 @@ export default function AccountManager() {
);
}
-function AccountCard({ acct, isIG, metrics, refreshingId, onRefresh, onDelete }) {
+function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelete }) {
+ const isIG = platform === 'instagram';
+ const isReddit = platform === 'reddit';
const initials = (acct.title || '?').slice(0, 2).toUpperCase();
+ const fallbackBg = isIG ? 'bg-pink-500' : isReddit ? 'bg-orange-500' : 'bg-red-500';
+ const subtitle = isIG
+ ? `@${acct.username || acct.igUsername || ''}`
+ : isReddit
+ ? `u/${acct.username || ''}`
+ : (acct.customUrl || '');
+
return (
<div className="border border-border rounded-xl p-4 bg-card hover:shadow-sm transition-shadow space-y-3">
<div className="flex items-center gap-3">
<Avatar className="h-11 w-11">
<AvatarImage src={acct.thumbnail || acct.profilePictureUrl || acct.thumbnails?.default} />
- <AvatarFallback className={`text-xs font-bold text-white ${isIG ? 'bg-pink-500' : 'bg-red-500'}`}>
+ <AvatarFallback className={`text-xs font-bold text-white ${fallbackBg}`}>
{initials}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold truncate">{acct.title || acct.channelId}</p>
- <p className="text-xs text-muted-foreground truncate">
- {isIG ? `@${acct.username || acct.igUsername || ''}` : (acct.customUrl || '')}
- </p>
+ <p className="text-xs text-muted-foreground truncate">{subtitle}</p>
</div>
</div>
diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsx
index fff4ae9..7c3daaa 100644
--- a/frontend/src/features/analytics/overview/Overview.jsx
+++ b/frontend/src/features/analytics/overview/Overview.jsx
@@ -15,7 +15,7 @@ import StatCard from '../../../components/ui/StatCard';
import MainCard from '../../../components/MainCard';
import { useAppContext } from '../../../context/AppContext';
import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
-import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera } from 'lucide-react';
+import { RefreshCw, Users, Eye, VideoIcon, BarChart3, ExternalLink, Tv, Camera, MessageSquare } from 'lucide-react';
const CHART_COLORS = ['hsl(221.2,83.2%,53.3%)', '#22c55e', '#f97316', '#a855f7', '#06b6d4', '#ec4899', '#6366f1', '#eab308'];
@@ -23,43 +23,57 @@ export default function Overview() {
const { accounts, loading, refreshAll } = useAppContext();
const navigate = useNavigate();
- const ytAccounts = accounts.filter(a => a.platform !== 'instagram');
- const igAccounts = accounts.filter(a => a.platform === 'instagram');
+ const ytAccounts = accounts.filter(a => a.platform !== 'instagram' && a.platform !== 'reddit');
+ const igAccounts = accounts.filter(a => a.platform === 'instagram');
+ const redditAccounts = accounts.filter(a => a.platform === 'reddit');
const totals = accounts.reduce((acc, a) => {
if (a.platform === 'instagram') {
return { ...acc, followers: acc.followers + (a.followersCount || 0), posts: acc.posts + (a.mediaCount || 0) };
}
+ if (a.platform === 'reddit') {
+ return { ...acc, karma: acc.karma + (a.totalKarma || 0) };
+ }
return {
...acc,
subscribers: acc.subscribers + (a.subscriberCount || 0),
views: acc.views + (a.viewCount || 0),
videos: acc.videos + (a.videoCount || 0),
};
- }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0 });
+ }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0, karma: 0 });
+
+ const totalAudience = totals.subscribers + totals.followers + totals.karma;
- const totalAudience = totals.subscribers + totals.followers;
+ const audienceMetric = (a) => {
+ if (a.platform === 'reddit') return a.totalKarma || 0;
+ if (a.platform === 'instagram') return a.followersCount || 0;
+ return a.subscriberCount || 0;
+ };
+ const contentMetric = (a) => {
+ if (a.platform === 'reddit') return 0;
+ if (a.platform === 'instagram') return a.mediaCount || 0;
+ return a.viewCount || 0;
+ };
const sorted = {
- byAudience: [...accounts].sort((a, b) =>
- (b.subscriberCount || b.followersCount || 0) - (a.subscriberCount || a.followersCount || 0)),
- byContent: [...accounts].sort((a, b) =>
- (b.viewCount || b.mediaCount || 0) - (a.viewCount || a.mediaCount || 0)),
+ byAudience: [...accounts].sort((a, b) => audienceMetric(b) - audienceMetric(a)),
+ byContent: [...accounts].sort((a, b) => contentMetric(b) - contentMetric(a)),
};
const chartData = accounts.map(a => ({
name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),
- audience: a.subscriberCount || a.followersCount || 0,
+ audience: audienceMetric(a),
}));
const pieData = accounts.map((a, i) => ({
name: (a.title || '').slice(0, 14) + ((a.title || '').length > 14 ? '…' : ''),
- value: a.subscriberCount || a.followersCount || 0,
+ value: audienceMetric(a),
color: CHART_COLORS[i % CHART_COLORS.length],
}));
const handleViewChannel = (acc) => {
if (acc.platform === 'instagram') navigate(`/instagram/${acc.id}`);
+ else if (acc.platform === 'reddit') navigate(`/reddit/${acc.id}`);
else navigate(`/channel/${acc.id}`);
};
@@ -72,7 +86,12 @@ export default function Overview() {
<p className="text-sm text-muted-foreground mt-0.5">
{accounts.length === 0
? 'Add your first account to start tracking'
- : `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''} · ${ytAccounts.length} YouTube · ${igAccounts.length} Instagram`}
+ : [
+ `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''}`,
+ ytAccounts.length ? `${ytAccounts.length} YouTube` : null,
+ igAccounts.length ? `${igAccounts.length} Instagram` : null,
+ redditAccounts.length ? `${redditAccounts.length} Reddit` : null,
+ ].filter(Boolean).join(' · ')}
</p>
</div>
<Button
@@ -95,7 +114,7 @@ export default function Overview() {
{ icon: <Users />, label: 'Total Audience', value: fmtNum(totalAudience), subtitle: `${fmtNum(totals.subscribers)} subs · ${fmtNum(totals.followers)} followers`, gradient: 'purple' },
{ icon: <Eye />, label: 'Total Views', value: fmtNum(totals.views), subtitle: fmtNumFull(totals.views), gradient: 'red' },
{ icon: <VideoIcon />, label: 'Total Content', value: fmtNum(totals.videos + totals.posts), subtitle: `${fmtNum(totals.videos)} videos · ${fmtNum(totals.posts)} posts`, gradient: 'blue' },
- { icon: <BarChart3 />, label: 'Accounts', value: accounts.length, subtitle: `${ytAccounts.length} YouTube · ${igAccounts.length} Instagram`, gradient: 'orange' },
+ { icon: <BarChart3 />, label: 'Accounts', value: accounts.length, subtitle: [ytAccounts.length ? `${ytAccounts.length} YouTube` : null, igAccounts.length ? `${igAccounts.length} Instagram` : null, redditAccounts.length ? `${redditAccounts.length} Reddit` : null].filter(Boolean).join(' · '), gradient: 'orange' },
].map((card, i) => (
<StatCard key={i} {...card} loading={loading} />
))}
@@ -162,21 +181,30 @@ export default function Overview() {
{
title: 'Top by Audience',
list: sorted.byAudience,
- metric: a => fmtNum(a.platform === 'instagram' ? a.followersCount : a.subscriberCount),
- isIG: a => a.platform === 'instagram',
+ metric: a => {
+ if (a.platform === 'instagram') return `${fmtNum(a.followersCount)} followers`;
+ if (a.platform === 'reddit') return `${fmtNum(a.totalKarma)} karma`;
+ return `${fmtNum(a.subscriberCount)} subs`;
+ },
},
{
title: 'Top by Content',
- list: sorted.byContent,
+ list: sorted.byContent.filter(a => a.platform !== 'reddit'),
metric: a => a.platform === 'instagram' ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views`,
- isIG: a => a.platform === 'instagram',
},
- ].map(({ title, list, metric, isIG }) => (
+ ].map(({ title, list, metric }) => (
<MainCard key={title} title={title}>
<div className="space-y-1">
{list.map((a, i) => {
- const ig = isIG(a);
- const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
+ const ig = a.platform === 'instagram';
+ const reddit = a.platform === 'reddit';
+ const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
+ const fallbackBg = ig ? 'bg-pink-500' : reddit ? 'bg-orange-500' : 'bg-red-500';
+ const badgeCls = ig
+ ? 'border-pink-200 bg-pink-50 text-pink-700'
+ : reddit
+ ? 'border-orange-200 bg-orange-50 text-orange-700'
+ : 'border-green-200 bg-green-50 text-green-700';
return (
<button
key={a.id}
@@ -186,12 +214,12 @@ export default function Overview() {
<span className={`w-5 text-xs font-bold tabular-nums ${medalColor}`}>{i + 1}</span>
<Avatar className="h-7 w-7 flex-shrink-0">
<AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} />
- <AvatarFallback className={`text-[0.55rem] font-bold text-white ${ig ? 'bg-pink-500' : 'bg-red-500'}`}>
+ <AvatarFallback className={`text-[0.55rem] font-bold text-white ${fallbackBg}`}>
{(a.title || '?').slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="flex-1 text-sm font-medium truncate">{a.title}</span>
- <Badge variant="outline" className={`text-xs font-semibold ${ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-green-200 bg-green-50 text-green-700'}`}>
+ <Badge variant="outline" className={`text-xs font-semibold ${badgeCls}`}>
{metric(a)}
</Badge>
</button>
@@ -218,8 +246,15 @@ export default function Overview() {
</TableHeader>
<TableBody>
{sorted.byAudience.map((a, i) => {
- const ig = a.platform === 'instagram';
+ const ig = a.platform === 'instagram';
+ const reddit = a.platform === 'reddit';
const medalColor = i === 0 ? 'text-yellow-500' : i === 1 ? 'text-slate-400' : i === 2 ? 'text-orange-400' : 'text-muted-foreground';
+ const fallbackBg = ig ? 'bg-pink-500' : reddit ? 'bg-orange-500' : 'bg-red-500';
+ const platformBadgeCls = ig
+ ? 'border-pink-200 bg-pink-50 text-pink-700'
+ : reddit
+ ? 'border-orange-200 bg-orange-50 text-orange-700'
+ : 'border-red-200 bg-red-50 text-red-700';
return (
<TableRow key={a.id} className="cursor-pointer" onClick={() => handleViewChannel(a)}>
<TableCell>
@@ -229,29 +264,29 @@ export default function Overview() {
<div className="flex items-center gap-2.5">
<Avatar className="h-8 w-8">
<AvatarImage src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} />
- <AvatarFallback className={`text-xs font-bold text-white ${ig ? 'bg-pink-500' : 'bg-red-500'}`}>
+ <AvatarFallback className={`text-xs font-bold text-white ${fallbackBg}`}>
{(a.title || '?').slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<p className="text-sm font-semibold leading-none">{a.title}</p>
<p className="text-xs text-muted-foreground mt-0.5">
- {ig ? `@${a.username || ''}` : (a.customUrl || a.channelId || '')}
+ {ig ? `@${a.username || ''}` : reddit ? `u/${a.username || ''}` : (a.customUrl || a.channelId || '')}
</p>
</div>
</div>
</TableCell>
<TableCell className="text-center">
- <Badge variant="outline" className={`text-xs ${ig ? 'border-pink-200 bg-pink-50 text-pink-700' : 'border-red-200 bg-red-50 text-red-700'}`}>
- {ig ? 'Instagram' : 'YouTube'}
+ <Badge variant="outline" className={`text-xs ${platformBadgeCls}`}>
+ {ig ? 'Instagram' : reddit ? 'Reddit' : 'YouTube'}
</Badge>
</TableCell>
<TableCell className="text-right">
- <p className="text-sm font-semibold">{fmtNum(ig ? a.followersCount : a.subscriberCount)}</p>
- <p className="text-xs text-muted-foreground">{ig ? 'followers' : 'subscribers'}</p>
+ <p className="text-sm font-semibold">{fmtNum(ig ? a.followersCount : reddit ? a.totalKarma : a.subscriberCount)}</p>
+ <p className="text-xs text-muted-foreground">{ig ? 'followers' : reddit ? 'karma' : 'subscribers'}</p>
</TableCell>
<TableCell className="text-right text-sm">
- {ig ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`}
+ {ig ? `${fmtNum(a.mediaCount)} posts` : reddit ? `${fmtNum(a.postKarma)} post karma` : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} vids`}
</TableCell>
<TableCell className="text-right text-xs text-muted-foreground">
{timeAgo(a.lastUpdated)}
diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
new file mode 100644
index 0000000..cd802ac
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
@@ -0,0 +1,414 @@
+import React, { useState, useEffect } from 'react';
+import { useParams, useNavigate, Link } 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, Award, BarChart2,
+ Calendar, Clock, Zap, Flame, Trophy, ExternalLink, FileText, Link2,
+ Image, Video,
+} from 'lucide-react';
+
+const REDDIT_COLORS = ['#FF4500', '#FF6534', '#FF8C00', '#FFA500', '#FFB347', '#FFC080'];
+const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };
+const MEDIA_TYPE_COLORS = { text: '#6366f1', image: '#22c55e', video: '#f97316', link: '#06b6d4' };
+
+const TS = { background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 };
+
+export default function RedditAnalytics() {
+ 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.getRedditAnalytics(account.id);
+ setProfile(data.profile);
+ setAnalytics(data.analytics);
+ } catch (err) {
+ showToast('Failed to load Reddit analytics: ' + err.message, 'error');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => { loadAnalytics(); }, [id]);
+
+ const handleRefresh = async () => {
+ setRefreshing(true);
+ try {
+ await api.refreshAccount(account.id);
+ await loadAnalytics();
+ showToast('Reddit 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 Reddit analytics...</p>
+ </div>
+ </div>
+ );
+ }
+
+ const p = profile || account;
+ const a = analytics || {};
+
+ const mediaTypeData = a.mediaTypeDistribution
+ ? Object.entries(a.mediaTypeDistribution).map(([key, value], i) => ({
+ name: MEDIA_TYPE_LABELS[key] || key,
+ value,
+ color: MEDIA_TYPE_COLORS[key] || REDDIT_COLORS[i % REDDIT_COLORS.length],
+ }))
+ : [];
+
+ return (
+ <div className="space-y-6">
+ {/* Back button */}
+ <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.iconUrl || account.thumbnail} />
+ <AvatarFallback className="bg-orange-500 text-white font-bold text-lg">
+ {(p.username || account.title || '?').slice(0, 2).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <h1 className="text-xl font-bold">u/{p.username || account.username}</h1>
+ {p.isGold && <Badge className="bg-yellow-500 text-white text-xs">Gold</Badge>}
+ {p.verified && <Badge className="bg-blue-500 text-white text-xs">Verified</Badge>}
+ {p.isMod && <Badge variant="outline" className="text-xs">Mod</Badge>}
+ </div>
+ <p className="text-sm text-muted-foreground mt-0.5">
+ Reddit account
+ {p.createdAt ? ` - joined ${fmtDate(p.createdAt)}` : ''}
+ </p>
+ <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(`/reddit-posts/${account.id}`)}
+ >
+ <FileText className="h-3.5 w-3.5" />
+ View Posts
+ </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>
+
+ <Separator className="my-4" />
+
+ {/* Karma breakdown */}
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
+ {[
+ { label: 'Total Karma', value: fmtNum(p.totalKarma), sub: fmtNumFull(p.totalKarma) },
+ { label: 'Post Karma', value: fmtNum(p.postKarma), sub: fmtNumFull(p.postKarma) },
+ { label: 'Comment Karma', value: fmtNum(p.commentKarma), sub: fmtNumFull(p.commentKarma) },
+ ].map(item => (
+ <div key={item.label} className="text-center p-3 rounded-lg bg-muted/40">
+ <p className="text-xl font-bold tabular-nums">{item.value}</p>
+ <p className="text-xs text-muted-foreground mt-0.5">{item.label}</p>
+ </div>
+ ))}
+ </div>
+ </MainCard>
+
+ {/* KPI cards */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
+ <StatCard icon={<TrendingUp />} label="Posts Analyzed" value={fmtNum(a.fetchedPosts)} subtitle={`${a.postsLast30Days ?? 0} in last 30 days`} gradient="orange" />
+ <StatCard icon={<Award />} label="Total Score" value={fmtNum(a.totalScore)} subtitle={`Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />
+ <StatCard icon={<MessageSquare />} label="Total Comments" value={fmtNum(a.totalComments)} subtitle={`Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" />
+ <StatCard icon={<BarChart2 />} label="Upvote Rate" value={`${a.avgUpvoteRatio ?? 0}%`} subtitle="average upvote ratio" gradient="purple" />
+ </div>
+
+ {/* Score timeline + media type pie */}
+ {a.monthlyBreakdown?.length > 0 && (
+ <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
+ <MainCard title="Score 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="redditGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#FF4500" stopOpacity={0.18} />
+ <stop offset="95%" stopColor="#FF4500" 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 === 'score' ? 'Total Score' : 'Posts']} />
+ <Area type="monotone" dataKey="score" stroke="#FF4500" strokeWidth={2} fill="url(#redditGrad)" dot={{ fill: '#FF4500', r: 3, strokeWidth: 0 }} />
+ </AreaChart>
+ </ResponsiveContainer>
+ </MainCard>
+
+ {mediaTypeData.length > 0 && (
+ <MainCard title="Post Type Breakdown">
+ <ResponsiveContainer width="100%" height={240} debounce={200}>
+ <PieChart>
+ <Pie data={mediaTypeData} dataKey="value" nameKey="name" cx="50%" cy="44%" outerRadius={80} innerRadius={44} paddingAngle={3} strokeWidth={0}>
+ {mediaTypeData.map((entry, i) => <Cell key={i} fill={entry.color} />)}
+ </Pie>
+ <ReTooltip contentStyle={TS} formatter={(v) => [fmtNumFull(v), 'posts']} />
+ <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />
+ </PieChart>
+ </ResponsiveContainer>
+ </MainCard>
+ )}
+ </div>
+ )}
+
+ {/* Activity scores */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
+ <MainCard title="Post Activity">
+ <div className="space-y-3">
+ {[
+ { label: 'Last 7 days', value: a.postsLast7Days },
+ { label: 'Last 30 days', value: a.postsLast30Days },
+ { label: 'Last 90 days', value: a.postsLast90Days },
+ ].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} posts</span>
+ </div>
+ ))}
+ <Separator />
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">Per week (avg)</span>
+ <span className="text-sm font-semibold">{a.postFrequency?.perWeek ?? 0}</span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-muted-foreground">Per month (avg)</span>
+ <span className="text-sm font-semibold">{a.postFrequency?.perMonth ?? 0}</span>
+ </div>
+ </div>
+ </MainCard>
+
+ <MainCard title="Score Distribution">
+ <div className="space-y-3">
+ {[
+ { label: 'Avg score', value: fmtNum(a.avgScore) },
+ { label: 'Median score', value: fmtNum(a.medianScore) },
+ { label: 'Best score', value: fmtNum(a.topPosts?.[0]?.score) },
+ { label: 'Avg upvote %', value: `${a.avgUpvoteRatio ?? 0}%` },
+ ].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 Scores">
+ <div className="space-y-4">
+ {[
+ { label: 'Virality Score', value: a.viralityScore, max: Math.max(10, a.viralityScore), desc: 'Peak vs average score ratio' },
+ { label: 'Consistency', value: a.consistencyScore, max: 100, desc: 'Score reliability across posts' },
+ ].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="Posts 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 === 'avgScore' ? 'Avg Score' : 'Posts']} />
+ <Bar dataKey="posts" fill="#FF4500" opacity={0.35} radius={[3, 3, 0, 0]} />
+ <Bar dataKey="avgScore" fill="#FF4500" 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="Posts 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 === 'avgScore' ? 'Avg Score' : 'Posts']} />
+ <Bar dataKey="avgScore" fill="#FF6534" 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>
+ )}
+
+ {/* Subreddit breakdown */}
+ {a.subredditBreakdown?.length > 0 && (
+ <MainCard title="Top Subreddits" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">#</TableHead>
+ <TableHead>Subreddit</TableHead>
+ <TableHead className="text-right">Posts</TableHead>
+ <TableHead className="text-right">Total Score</TableHead>
+ <TableHead className="text-right">Avg Score</TableHead>
+ <TableHead className="text-right">Avg Comments</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {a.subredditBreakdown.map((sub, i) => (
+ <TableRow key={sub.subreddit}>
+ <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>
+ <TableCell>
+ <a
+ href={`https://reddit.com/r/${sub.subreddit}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-sm font-medium hover:underline flex items-center gap-1"
+ >
+ r/{sub.subreddit}
+ <ExternalLink className="h-3 w-3 text-muted-foreground" />
+ </a>
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{sub.posts}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.totalScore)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.avgScore)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(sub.avgComments)}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </MainCard>
+ )}
+
+ {/* Top posts */}
+ {a.topPosts?.length > 0 && (
+ <MainCard title="Top Posts by Score" content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">#</TableHead>
+ <TableHead>Post</TableHead>
+ <TableHead className="text-right">Score</TableHead>
+ <TableHead className="text-right">Comments</TableHead>
+ <TableHead className="text-right">Upvote %</TableHead>
+ <TableHead className="text-right">Posted</TableHead>
+ <TableHead className="w-8" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {a.topPosts.map((post, i) => (
+ <TableRow key={post.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 font-medium leading-snug line-clamp-2">{post.title}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>
+ {post.flair && <Badge variant="outline" className="text-[10px] px-1 py-0">{post.flair}</Badge>}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">{fmtNum(post.score)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{Math.round((post.upvoteRatio ?? 0) * 100)}%</TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">{fmtDate(post.createdAt)}</TableCell>
+ <TableCell>
+ <a href={post.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/reddit/RedditPosts.jsx b/frontend/src/features/analytics/reddit/RedditPosts.jsx
new file mode 100644
index 0000000..5d8e71c
--- /dev/null
+++ b/frontend/src/features/analytics/reddit/RedditPosts.jsx
@@ -0,0 +1,228 @@
+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 { Skeleton } from '@/components/ui/skeleton';
+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 MainCard from '../../../components/MainCard';
+import { useAppContext } from '../../../context/AppContext';
+import { api } from '../../../services/api';
+import { fmtNum, fmtDate } from '../../../utils/formatters';
+import { ArrowLeft, Search, ExternalLink, TrendingUp, MessageSquare, FileText, Image, Video, Link2 } from 'lucide-react';
+
+const MEDIA_TYPE_LABELS = { text: 'Text', image: 'Image', video: 'Video', link: 'Link' };
+const SORT_OPTIONS = [
+ { value: 'score-desc', label: 'Score (high to low)' },
+ { value: 'score-asc', label: 'Score (low to high)' },
+ { value: 'comments-desc', label: 'Comments (most)' },
+ { value: 'date-desc', label: 'Newest first' },
+ { value: 'date-asc', label: 'Oldest first' },
+];
+
+function MediaTypeIcon({ type }) {
+ const props = { className: 'h-3.5 w-3.5' };
+ if (type === 'image') return <Image {...props} />;
+ if (type === 'video') return <Video {...props} />;
+ if (type === 'link') return <Link2 {...props} />;
+ return <FileText {...props} />;
+}
+
+export default function RedditPosts() {
+ const { id } = useParams();
+ const { accounts, showToast } = useAppContext();
+ const navigate = useNavigate();
+ const account = accounts.find(a => a.id === id);
+
+ const [loading, setLoading] = useState(true);
+ const [posts, setPosts] = useState([]);
+ const [query, setQuery] = useState('');
+ const [sort, setSort] = useState('score-desc');
+ const [subFilter, setSubFilter] = useState('all');
+
+ useEffect(() => {
+ if (!account) return;
+ setLoading(true);
+ api.getRedditPosts(account.id)
+ .then(data => setPosts(Array.isArray(data) ? data : []))
+ .catch(err => showToast('Failed to load posts: ' + err.message, 'error'))
+ .finally(() => setLoading(false));
+ }, [id]);
+
+ const subreddits = useMemo(() => {
+ const seen = new Set();
+ posts.forEach(p => seen.add(p.subreddit));
+ return ['all', ...Array.from(seen).sort()];
+ }, [posts]);
+
+ const filtered = useMemo(() => {
+ let result = posts;
+ if (subFilter !== 'all') result = result.filter(p => p.subreddit === subFilter);
+ if (query.trim()) {
+ const q = query.toLowerCase();
+ result = result.filter(p =>
+ p.title.toLowerCase().includes(q) ||
+ p.subreddit.toLowerCase().includes(q) ||
+ (p.flair || '').toLowerCase().includes(q)
+ );
+ }
+ return [...result].sort((a, b) => {
+ if (sort === 'score-desc') return b.score - a.score;
+ if (sort === 'score-asc') return a.score - b.score;
+ if (sort === 'comments-desc') return b.numComments - a.numComments;
+ if (sort === 'date-desc') return new Date(b.createdAt) - new Date(a.createdAt);
+ if (sort === 'date-asc') return new Date(a.createdAt) - new Date(b.createdAt);
+ return 0;
+ });
+ }, [posts, query, sort, subFilter]);
+
+ 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>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <Button variant="ghost" onClick={() => navigate(`/reddit/${account.id}`)} className="gap-2 -ml-2 text-muted-foreground mb-2">
+ <ArrowLeft className="h-4 w-4" /> Back to Analytics
+ </Button>
+ <h1 className="text-2xl font-bold tracking-tight">Posts - u/{account.username}</h1>
+ <p className="text-sm text-muted-foreground mt-0.5">
+ {loading ? 'Loading...' : `${filtered.length} of ${posts.length} posts`}
+ </p>
+ </div>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center justify-center min-h-[40vh]">
+ <div className="flex flex-col items-center gap-3">
+ <Spinner className="size-10" />
+ <p className="text-sm text-muted-foreground">Loading posts...</p>
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* Filters */}
+ <MainCard>
+ <div className="flex flex-col sm:flex-row gap-3">
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search posts..."
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ className="pl-9"
+ />
+ </div>
+ <Select value={subFilter} onValueChange={setSubFilter}>
+ <SelectTrigger className="w-full sm:w-48">
+ <SelectValue placeholder="All subreddits" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All subreddits</SelectItem>
+ {subreddits.filter(s => s !== 'all').map(s => (
+ <SelectItem key={s} value={s}>r/{s}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={sort} onValueChange={setSort}>
+ <SelectTrigger className="w-full sm:w-52">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SORT_OPTIONS.map(o => (
+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </MainCard>
+
+ {/* Posts table */}
+ <MainCard content={false}>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">#</TableHead>
+ <TableHead>Post</TableHead>
+ <TableHead className="w-24">Type</TableHead>
+ <TableHead className="text-right w-24">Score</TableHead>
+ <TableHead className="text-right w-28">Comments</TableHead>
+ <TableHead className="text-right w-20">Upvote %</TableHead>
+ <TableHead className="text-right w-28">Date</TableHead>
+ <TableHead className="w-8" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={8} className="text-center text-muted-foreground py-12">
+ No posts match the current filters
+ </TableCell>
+ </TableRow>
+ ) : (
+ filtered.map((post, i) => (
+ <TableRow key={post.id}>
+ <TableCell className="text-xs text-muted-foreground">{i + 1}</TableCell>
+ <TableCell>
+ <div className="max-w-md">
+ <p className="text-sm font-medium leading-snug line-clamp-2">{post.title}</p>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-xs text-muted-foreground">{post.subredditPrefixed}</span>
+ {post.flair && (
+ <Badge variant="outline" className="text-[10px] px-1 py-0 h-4">
+ {post.flair}
+ </Badge>
+ )}
+ {post.isNsfw && (
+ <Badge className="text-[10px] px-1 py-0 h-4 bg-red-100 text-red-700 border-red-200">
+ NSFW
+ </Badge>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <MediaTypeIcon type={post.mediaType} />
+ <span>{MEDIA_TYPE_LABELS[post.mediaType] || post.mediaType}</span>
+ </div>
+ </TableCell>
+ <TableCell className="text-right text-sm font-semibold tabular-nums text-orange-500">
+ {fmtNum(post.score)}
+ </TableCell>
+ <TableCell className="text-right text-sm tabular-nums">{fmtNum(post.numComments)}</TableCell>
+ <TableCell className="text-right text-sm tabular-nums">
+ {Math.round((post.upvoteRatio ?? 0) * 100)}%
+ </TableCell>
+ <TableCell className="text-right text-xs text-muted-foreground">
+ {fmtDate(post.createdAt)}
+ </TableCell>
+ <TableCell>
+ <a href={post.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/layout/Sidebar.jsx b/frontend/src/layout/Sidebar.jsx
index 089e45b..009a5fc 100644
--- a/frontend/src/layout/Sidebar.jsx
+++ b/frontend/src/layout/Sidebar.jsx
@@ -101,9 +101,11 @@ export default function AppSidebar() {
<SidebarGroupLabel>Accounts</SidebarGroupLabel>
<SidebarMenu>
{accounts.map((acc) => {
- const isIG = acc.platform === 'instagram';
- const path = isIG ? `/instagram/${acc.id}` : `/channel/${acc.id}`;
+ const isIG = acc.platform === 'instagram';
+ const isReddit = acc.platform === 'reddit';
+ const path = isIG ? `/instagram/${acc.id}` : isReddit ? `/reddit/${acc.id}` : `/channel/${acc.id}`;
const initials = (acc.title || '?').slice(0, 2).toUpperCase();
+ const avatarBg = isIG ? '#ec4899' : isReddit ? '#f97316' : '#ef4444';
return (
<SidebarMenuItem key={acc.id}>
<SidebarMenuButton
@@ -117,7 +119,7 @@ export default function AppSidebar() {
alt={acc.title}
/>
<AvatarFallback
- style={{ background: isIG ? '#ec4899' : '#ef4444' }}
+ style={{ background: avatarBg }}
className="text-[0.5rem] font-bold text-white"
>
{initials}
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 992642f..99199ae 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -60,6 +60,11 @@ export const api = {
getIGContainerStatus: (containerId, accountId) => request(`/ig-container/${containerId}/status?accountId=${accountId}`),
publishIGContainer: (id, containerId) => request(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
+ // Reddit accounts
+ addRedditAccount: (username, cookie) => request('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
+ getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
+ getRedditPosts: (id) => request(`/accounts/${id}/reddit-posts`),
+
// 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 b236cb9..6313d8d 100644
--- a/frontend/src/utils/formatters.js
+++ b/frontend/src/utils/formatters.js
@@ -64,7 +64,7 @@ export const CATEGORY_MAP = {
'42': 'Shorts', '43': 'Shows', '44': 'Trailers',
};
-// Normalize account data (handles both old/new backend formats and Instagram)
+// Normalize account data (handles YouTube, Instagram, and Reddit)
export function normalizeAccount(acct) {
if (!acct) return acct;
if (acct.platform === 'instagram') {
@@ -77,6 +77,16 @@ export function normalizeAccount(acct) {
mediaCount: acct.mediaCount || 0,
};
}
+ if (acct.platform === 'reddit') {
+ return {
+ ...acct,
+ title: acct.title || `u/${acct.username}`,
+ thumbnail: acct.iconUrl || '',
+ totalKarma: acct.totalKarma || 0,
+ postKarma: acct.postKarma || 0,
+ commentKarma: acct.commentKarma || 0,
+ };
+ }
return {
...acct,
title: acct.title || acct.name || acct.channelTitle || acct.channelId,