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.

refactor(reddit): simplify to cookie-only auth, remove OAuth and RSS

spacesdrive6c074970ed01
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.js
index 96ff444..ffe803d 100644
--- a/backend/routes/accounts.js
+++ b/backend/routes/accounts.js
@@ -91,12 +91,13 @@ 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);
+ if (!cookie) return c.json({ success: false, message: 'Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here' }, 400);
const supabase = c.get('supabase');
const userId = c.get('userId');
const cleanUsername = username.replace(/^u\//i, '').trim();
- const profile = await fetchRedditProfile(cleanUsername, cookie ?? null, c.env);
+ const profile = await fetchRedditProfile(cleanUsername, cookie);
const accounts = await getAccounts(supabase, userId);
if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {
@@ -108,12 +109,12 @@ app.post('/accounts/reddit', async (c) => {
platform: 'reddit',
username: profile.username,
title: `u/${profile.username}`,
- totalKarma: profile.totalKarma ?? 0,
- postKarma: profile.postKarma ?? 0,
- commentKarma: profile.commentKarma ?? 0,
- iconUrl: profile.iconUrl ?? '',
- createdAt: profile.createdAt ?? '',
- ...(cookie ? { cookie } : {}),
+ totalKarma: profile.totalKarma,
+ postKarma: profile.postKarma,
+ commentKarma: profile.commentKarma,
+ iconUrl: profile.iconUrl,
+ createdAt: profile.createdAt,
+ cookie,
addedAt: new Date().toISOString(),
lastUpdated: new Date().toISOString(),
};
@@ -204,7 +205,8 @@ app.post('/accounts/refresh-all', async (c) => {
profilePictureUrl: profile.profilePictureUrl,
};
} else if (account.platform === 'reddit') {
- const profile = await fetchRedditProfile(account.username, account.cookie ?? null, c.env);
+ if (!account.cookie) throw new Error('No session cookie stored - re-add this account with a session cookie from reddit.com DevTools');
+ const profile = await fetchRedditProfile(account.username, account.cookie);
updates = {
...updates,
totalKarma: profile.totalKarma,
@@ -290,7 +292,8 @@ app.post('/accounts/:id/refresh', async (c) => {
website: profile.website,
};
} else if (account.platform === 'reddit') {
- const profile = await fetchRedditProfile(account.username, account.cookie ?? null, c.env);
+ if (!account.cookie) return c.json({ success: false, message: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);
+ const profile = await fetchRedditProfile(account.username, account.cookie);
updates = {
...updates,
totalKarma: profile.totalKarma,
diff --git a/backend/routes/reddit.js b/backend/routes/reddit.js
index 91779ec..cafdf1b 100644
--- a/backend/routes/reddit.js
+++ b/backend/routes/reddit.js
@@ -1,7 +1,7 @@
import { Hono } from 'hono';
import { getAccountById } from '../lib/db.js';
import { getRedditCache, setRedditCache } from '../lib/cache.js';
-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics, safeRedditAccount } from '../services/reddit.js';
+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.js';
const router = new Hono();
@@ -14,14 +14,14 @@ router.get('/accounts/:id/reddit-analytics', async (c) => {
try {
const account = await getAccountById(supabase, id, userId);
if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+ if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);
const cached = await getRedditCache(redis, userId, id);
if (cached) return c.json(cached);
- const cookie = account.cookie ?? null;
const [profile, posts] = await Promise.all([
- fetchRedditProfile(account.username, cookie, c.env),
- fetchRedditPosts(account.username, cookie, 100, c.env),
+ fetchRedditProfile(account.username, account.cookie),
+ fetchRedditPosts(account.username, account.cookie, 100),
]);
const analytics = computeRedditAnalytics(profile, posts);
const result = { profile, analytics, posts };
@@ -43,12 +43,12 @@ router.get('/accounts/:id/reddit-posts', async (c) => {
try {
const account = await getAccountById(supabase, id, userId);
if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
+ if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);
const cached = await getRedditCache(redis, userId, id);
if (cached?.posts) return c.json(cached.posts);
- const cookie = account.cookie ?? null;
- const posts = await fetchRedditPosts(account.username, cookie, 100, c.env);
+ const posts = await fetchRedditPosts(account.username, account.cookie, 100);
return c.json(posts);
} catch (err) {
console.error(`GET /accounts/${id}/reddit-posts:`, err.message);
diff --git a/backend/services/reddit.js b/backend/services/reddit.js
index a620419..f8fd79a 100644
--- a/backend/services/reddit.js
+++ b/backend/services/reddit.js
@@ -1,61 +1,22 @@
// fetch is a global in Cloudflare Workers - no import needed.
-// No crypto or DB imports needed - Reddit uses the public JSON API or RSS.
-// Session cookies are stored as-is (not encrypted) and used directly in requests.
+// Reddit API access requires a session cookie from the user's logged-in browser session.
+// Cookies are stored as-is and sent with every request.
const REDDIT_BASE = 'https://www.reddit.com';
-const REDDIT_OAUTH_BASE = 'https://oauth.reddit.com';
// Reddit requires: <platform>:<appid>:<version> (by /u/<username>)
const USER_AGENT = 'script:twiligent:v1.0 (by /u/spacesdrive)';
-// Module-level token cache. Cloudflare isolates are reused within a data center,
-// so this reduces token fetches. On fresh isolates it re-fetches transparently.
-let _cachedToken = null;
-let _tokenExpiry = 0;
-
-async function getAppOnlyToken(env) {
- if (!env?.REDDIT_CLIENT_ID || !env?.REDDIT_CLIENT_SECRET) return null;
- if (_cachedToken && Date.now() < _tokenExpiry) return _cachedToken;
- try {
- const creds = btoa(`${env.REDDIT_CLIENT_ID}:${env.REDDIT_CLIENT_SECRET}`);
- const res = await fetch('https://www.reddit.com/api/v1/access_token', {
- method: 'POST',
- headers: {
- 'Authorization': `Basic ${creds}`,
- 'User-Agent': USER_AGENT,
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- body: 'grant_type=client_credentials',
- });
- if (!res.ok) return null;
- const data = await res.json();
- if (!data.access_token) return null;
- _cachedToken = data.access_token;
- _tokenExpiry = Date.now() + Math.max(0, (data.expires_in ?? 3600) - 60) * 1000;
- return _cachedToken;
- } catch {
- return null;
- }
-}
-
-async function redditFetch(path, cookie = null, token = null) {
- const base = token ? REDDIT_OAUTH_BASE : REDDIT_BASE;
- const headers = {
- 'User-Agent': USER_AGENT,
- 'Accept': 'application/json',
- };
- if (token) headers['Authorization'] = `Bearer ${token}`;
- if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
-
- const res = await fetch(`${base}${path}`, { headers });
+async function redditFetch(path, cookie) {
+ const res = await fetch(`${REDDIT_BASE}${path}`, {
+ headers: {
+ 'User-Agent': USER_AGENT,
+ 'Accept': 'application/json',
+ 'Cookie': `reddit_session=${cookie}`,
+ },
+ });
if (res.status === 404) throw new Error('Reddit user not found - check the username');
- if (res.status === 403) {
- if (token) throw new Error('Account is private or suspended');
- // Reddit ended unauthenticated JSON access in May 2026 from server IPs.
- const err = new Error('REDDIT_BLOCKED');
- err.status = 403;
- throw err;
- }
+ if (res.status === 403) throw new Error('Session cookie is invalid or expired - open reddit.com in your browser, copy a fresh reddit_session value from DevTools (Application > Cookies > reddit.com), delete this account, and re-add it');
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}`);
@@ -64,125 +25,25 @@ async function redditFetch(path, cookie = null, token = null) {
return data;
}
-// --- RSS fallback ---
-// Reddit's .json API ended unauthenticated server access in May 2026.
-// RSS feeds still return 200 but carry no score or karma data.
-
-function rssExtractAll(xml, tag) {
- const results = [];
- const re = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`, 'g');
- let m;
- while ((m = re.exec(xml)) !== null) {
- results.push(m[1].replace(/<!\[CDATA\[|\]\]>/g, '').trim());
- }
- return results;
-}
-
-function rssExtractAttr(xml, tag, attr) {
- const m = xml.match(new RegExp(`<${tag}[^>]+${attr}="([^"]+)"`));
- return m ? m[1] : '';
-}
-
-async function fetchRedditRSS(username) {
- const res = await fetch(`${REDDIT_BASE}/user/${username}/submitted.rss`, {
- headers: { 'User-Agent': USER_AGENT },
- });
- if (res.status === 404) throw new Error('Reddit user not found - check the username');
- if (!res.ok) throw new Error(`Reddit has blocked all server access to public data (${res.status}). Reddit analytics are unavailable until Reddit re-enables public API access or you provide OAuth credentials.`);
- return res.text();
-}
-
-function parseRSSPosts(username, xml) {
- // Split by <entry> to get individual post blocks
- const raw = xml.split('<entry>').slice(1);
- return raw.map(block => {
- const title = rssExtractAll(block, 'title')[0] || '';
- const link = rssExtractAttr(block, 'link', 'href') || '';
- const published = rssExtractAll(block, 'published')[0] || rssExtractAll(block, 'updated')[0] || '';
- const category = rssExtractAttr(block, 'category', 'term') || '';
- // Extract post ID from permalink: /r/sub/comments/{id}/title/
- const idMatch = link.match(/\/comments\/([a-z0-9]+)\//i);
- return {
- id: idMatch ? idMatch[1] : link,
- title,
- subreddit: category,
- subredditPrefixed: category ? `r/${category}` : '',
- score: 0,
- upvoteRatio: 0,
- numComments: 0,
- url: link,
- permalink: link,
- thumbnail: '',
- mediaType: 'text',
- isSelf: true,
- isVideo: false,
- isNsfw: false,
- createdAt: published,
- flair: '',
- };
- }).filter(p => p.permalink);
-}
-
-// Verify user exists via RSS and return a minimal profile stub.
-// Called when the JSON API is blocked (no OAuth credentials).
-export async function fetchRedditProfileViaRSS(username) {
- await fetchRedditRSS(username); // throws if user not found or blocked
+export async function fetchRedditProfile(username, cookie) {
+ const data = await redditFetch(`/user/${username}/about.json`, cookie);
+ const u = data.data;
return {
- username,
- totalKarma: null,
- postKarma: null,
- commentKarma: null,
- awardeeKarma: null,
- awarderKarma: null,
- iconUrl: '',
- createdAt: '',
- isGold: false,
- isMod: false,
- verified: false,
- apiRestricted: true,
+ 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(/&amp;/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 fetchRedditProfile(username, cookie = null, env = null) {
- const token = await getAppOnlyToken(env);
- try {
- const data = await redditFetch(`/user/${username}/about.json`, cookie, token);
- 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(/&amp;/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,
- apiRestricted: false,
- };
- } catch (err) {
- if (err.message === 'REDDIT_BLOCKED') {
- return fetchRedditProfileViaRSS(username);
- }
- throw err;
- }
-}
-
-export async function fetchRedditPosts(username, cookie = null, limit = 100, env = null) {
- const token = await getAppOnlyToken(env);
- try {
- return await fetchRedditPostsJSON(username, cookie, limit, token);
- } catch (err) {
- if (err.message === 'REDDIT_BLOCKED') {
- return fetchRedditPostsRSS(username);
- }
- throw err;
- }
-}
-
-async function fetchRedditPostsJSON(username, cookie, limit, token) {
+export async function fetchRedditPosts(username, cookie, limit = 100) {
let allPosts = [];
let after = null;
let pages = 0;
@@ -194,7 +55,7 @@ async function fetchRedditPostsJSON(username, cookie, limit, token) {
});
if (after) qs.set('after', after);
- const data = await redditFetch(`/user/${username}/submitted.json?${qs}`, cookie, token);
+ const data = await redditFetch(`/user/${username}/submitted.json?${qs}`, cookie);
const children = data.data?.children ?? [];
if (children.length === 0) break;
@@ -224,11 +85,6 @@ async function fetchRedditPostsJSON(username, cookie, limit, token) {
}));
}
-async function fetchRedditPostsRSS(username) {
- const xml = await fetchRedditRSS(username);
- return parseRSSPosts(username, xml);
-}
-
export function computeRedditAnalytics(profile, posts) {
const empty = {
fetchedPosts: 0, totalScore: 0, avgScore: 0, medianScore: 0,
@@ -240,15 +96,14 @@ export function computeRedditAnalytics(profile, posts) {
postFrequency: { perWeek: 0, perMonth: 0 },
viralityScore: 0, consistencyScore: 0,
bestPostingDay: '', bestPostingHour: '',
- apiRestricted: profile?.apiRestricted ?? false,
};
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 = posts.length > 0 ? Math.round(totalScore / posts.length) : 0;
- const avgComments = posts.length > 0 ? Math.round(totalComments / posts.length) : 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)
);
@@ -308,7 +163,7 @@ export function computeRedditAnalytics(profile, posts) {
avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,
}));
const bestDayObj = postsByDayOfWeek.reduce(
- (best, d) => d.posts > best.posts ? d : best,
+ (best, d) => d.avgScore > best.avgScore ? d : best,
postsByDayOfWeek[0]
);
@@ -318,7 +173,7 @@ export function computeRedditAnalytics(profile, posts) {
avgScore: b.count > 0 ? Math.round(b.score / b.count) : 0,
}));
const bestHourObj = postsByHour.reduce(
- (best, h) => h.posts > best.posts ? h : best,
+ (best, h) => h.avgScore > best.avgScore ? h : best,
postsByHour[0]
);
@@ -338,7 +193,7 @@ export function computeRedditAnalytics(profile, posts) {
.sort(([a], [b]) => a.localeCompare(b))
.map(([month, s]) => ({
month, posts: s.posts, score: s.score, comments: s.comments,
- avgScore: s.posts > 0 ? Math.round(s.score / s.posts) : 0,
+ avgScore: Math.round(s.score / s.posts),
}));
// Recency counts
@@ -357,13 +212,12 @@ export function computeRedditAnalytics(profile, posts) {
perMonth = parseFloat((posts.length / spanDays * 30).toFixed(1));
}
- // Virality and consistency - only meaningful when scores are available
- const apiRestricted = profile?.apiRestricted ?? false;
+ // Virality and consistency
const bestScore = byScore[0]?.score ?? 0;
- const viralityScore = (!apiRestricted && avgScore > 0) ? parseFloat((bestScore / avgScore).toFixed(1)) : 0;
+ const viralityScore = avgScore > 0 ? parseFloat((bestScore / avgScore).toFixed(1)) : 0;
let consistencyScore = 0;
- if (!apiRestricted && posts.length >= 3) {
+ 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;
@@ -386,11 +240,10 @@ export function computeRedditAnalytics(profile, posts) {
postsLast7Days, postsLast30Days, postsLast90Days,
postFrequency: { perWeek, perMonth },
viralityScore, consistencyScore,
- apiRestricted,
};
}
-// Strips the session cookie before any API response - treat it like an access token.
+// Strips the session cookie before any API response.
// Exposes hasCookie as a boolean so the frontend can show session status without the value.
export function safeRedditAccount(account) {
const copy = { ...account };
@@ -401,7 +254,5 @@ export function safeRedditAccount(account) {
return copy;
}
-// No-op: Reddit auto-refresh via automated login is not supported from server IPs.
-// Reddit's login endpoint (ssl.reddit.com/api/login) blocks datacenter IPs.
-// Session cookies must be refreshed manually by the user via the Account Manager.
+// No-op: kept for compatibility with server.js cron handler.
export async function autoRefreshRedditSessions() {}
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index 5fed48b..44b7a51 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -49,8 +49,6 @@ All secrets are set via `wrangler secret put <NAME>`. They are available at runt
| `FRONTEND_URL` | Yes | Frontend URL (for post-OAuth redirect back to the SPA) |
| `UPSTASH_REDIS_REST_URL` | Optional | Upstash Redis endpoint; caching disabled if absent |
| `UPSTASH_REDIS_REST_TOKEN` | Optional | Upstash auth token |
-| `REDDIT_CLIENT_ID` | Optional | Reddit script app client ID for application-only OAuth; Reddit API falls back to unauthenticated if absent (may 403) |
-| `REDDIT_CLIENT_SECRET` | Optional | Reddit script app client secret; required alongside `REDDIT_CLIENT_ID` |
### Setting secrets
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index 3039886..81d672f 100644
--- a/frontend/src/features/accounts/AccountManager.jsx
+++ b/frontend/src/features/accounts/AccountManager.jsx
@@ -10,8 +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, Globe,
+ Tv, Camera, Link2, Info, ExternalLink, MessageSquare, Lock,
} from 'lucide-react';
import MainCard from '../../components/MainCard';
import { useAppContext } from '../../context/AppContext';
@@ -133,10 +132,10 @@ export default function AccountManager() {
};
const handleAddReddit = async () => {
- if (!redditUsername.trim()) return;
+ if (!redditUsername.trim() || !redditCookie.trim()) return;
setAddingReddit(true);
try {
- await api.addRedditAccount(redditUsername.trim(), redditCookie.trim() || null);
+ await api.addRedditAccount(redditUsername.trim(), redditCookie.trim());
showToast('Reddit account added');
closeDialog();
loadAccounts();
@@ -380,7 +379,7 @@ export default function AccountManager() {
<TabsContent value="reddit" className="space-y-4 mt-4">
<p className="text-sm text-muted-foreground">
- Enter your Reddit username. For public accounts no session cookie is needed.
+ A session cookie is required to fetch Reddit analytics from the server.
</p>
<div className="space-y-3">
<div className="relative">
@@ -394,14 +393,12 @@ export default function AccountManager() {
/>
</div>
<div className="space-y-1.5">
- <label className="text-xs font-medium text-muted-foreground">
- Session cookie (optional - for private accounts only)
- </label>
+ <label className="text-xs font-medium">Session cookie</label>
<Input
type="password"
value={redditCookie}
onChange={e => setRedditCookie(e.target.value)}
- placeholder="reddit_session cookie value"
+ placeholder="reddit_session value"
onKeyDown={e => e.key === 'Enter' && handleAddReddit()}
/>
</div>
@@ -409,7 +406,7 @@ export default function AccountManager() {
<Alert>
<Info className="h-4 w-4" />
<AlertDescription className="text-xs">
- Public Reddit accounts work without a session cookie - analytics are fetched from Reddit's public API. For private accounts, open your browser DevTools while logged in to Reddit, go to Application &gt; Cookies &gt; reddit.com, and copy the value of the <strong>reddit_session</strong> cookie.
+ Log in to reddit.com in your browser. Open DevTools (F12), go to <strong>Application &gt; Cookies &gt; https://www.reddit.com</strong>, find the cookie named <strong>reddit_session</strong>, and copy its value.
</AlertDescription>
</Alert>
</TabsContent>
@@ -424,7 +421,7 @@ export default function AccountManager() {
</Button>
)}
{dialogTab === 'reddit' && (
- <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || addingReddit} className="gap-1.5">
+ <Button onClick={handleAddReddit} disabled={!redditUsername.trim() || !redditCookie.trim() || addingReddit} className="gap-1.5">
{addingReddit && <RefreshCw className="h-3.5 w-3.5 animate-spin" />}
Add Reddit Account
</Button>
@@ -480,8 +477,8 @@ function AccountCard({ acct, platform, metrics, refreshingId, onRefresh, onDelet
</>
) : (
<>
- <Globe className="h-3 w-3 text-muted-foreground" />
- <span className="text-muted-foreground">Public access</span>
+ <Lock className="h-3 w-3 text-destructive" />
+ <span className="text-destructive">No cookie - re-add account</span>
</>
)}
</div>
diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
index 655b6f9..c1a4c5b 100644
--- a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
+++ b/frontend/src/features/analytics/reddit/RedditAnalytics.jsx
@@ -20,7 +20,7 @@ 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, AlertTriangle,
+ Image, Video,
} from 'lucide-react';
const REDDIT_COLORS = ['#FF4500', '#FF6534', '#FF8C00', '#FFA500', '#FFB347', '#FFC080'];
@@ -162,9 +162,9 @@ export default function RedditAnalytics() {
{/* Karma breakdown */}
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
{[
- { label: 'Total Karma', value: a.apiRestricted ? 'N/A' : fmtNum(p.totalKarma) },
- { label: 'Post Karma', value: a.apiRestricted ? 'N/A' : fmtNum(p.postKarma) },
- { label: 'Comment Karma', value: a.apiRestricted ? 'N/A' : fmtNum(p.commentKarma) },
+ { label: 'Total Karma', value: fmtNum(p.totalKarma) },
+ { label: 'Post Karma', value: fmtNum(p.postKarma) },
+ { label: 'Comment Karma', value: fmtNum(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>
@@ -174,26 +174,12 @@ export default function RedditAnalytics() {
</div>
</MainCard>
- {/* Reddit API restriction notice */}
- {a.apiRestricted && (
- <div className="flex items-start gap-3 rounded-lg border border-yellow-500/30 bg-yellow-500/10 p-4 text-sm">
- <AlertTriangle className="h-4 w-4 text-yellow-500 mt-0.5 shrink-0" />
- <div>
- <p className="font-medium text-yellow-600 dark:text-yellow-400">Reddit API restricted</p>
- <p className="text-muted-foreground mt-0.5">
- Reddit ended unauthenticated server API access in May 2026. Karma and score data are unavailable.
- Posting activity, subreddit breakdown, and timing patterns are sourced from RSS and remain accurate.
- </p>
- </div>
- </div>
- )}
-
{/* 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={a.apiRestricted ? 'N/A' : fmtNum(a.totalScore)} subtitle={a.apiRestricted ? 'unavailable' : `Avg ${fmtNum(a.avgScore)} per post`} gradient="red" />
- <StatCard icon={<MessageSquare />} label="Total Comments" value={a.apiRestricted ? 'N/A' : fmtNum(a.totalComments)} subtitle={a.apiRestricted ? 'unavailable' : `Avg ${fmtNum(a.avgComments)} per post`} gradient="blue" />
- <StatCard icon={<BarChart2 />} label="Upvote Rate" value={a.apiRestricted ? 'N/A' : `${a.avgUpvoteRatio ?? 0}%`} subtitle="average upvote ratio" gradient="purple" />
+ <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 */}