Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(reddit): use RSS fallback when Reddit JSON API is blocked
spacesdrive55e518b1484a
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.jsindex 84ed344..96ff444 100644--- a/backend/routes/accounts.js+++ b/backend/routes/accounts.js@@ -108,11 +108,11 @@ app.post('/accounts/reddit', async (c) => {platform: 'reddit',username: profile.username,title: `u/${profile.username}`,- totalKarma: profile.totalKarma,- postKarma: profile.postKarma,- commentKarma: profile.commentKarma,- iconUrl: profile.iconUrl,- createdAt: profile.createdAt,+ totalKarma: profile.totalKarma ?? 0,+ postKarma: profile.postKarma ?? 0,+ commentKarma: profile.commentKarma ?? 0,+ iconUrl: profile.iconUrl ?? '',+ createdAt: profile.createdAt ?? '',...(cookie ? { cookie } : {}),addedAt: new Date().toISOString(),lastUpdated: new Date().toISOString(),diff --git a/backend/routes/reddit.js b/backend/routes/reddit.jsindex 934bffb..91779ec 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 } from '../services/reddit.js';+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics, safeRedditAccount } from '../services/reddit.js';const router = new Hono();diff --git a/backend/services/reddit.js b/backend/services/reddit.jsindex 527ae95..a620419 100644--- a/backend/services/reddit.js+++ b/backend/services/reddit.js@@ -1,5 +1,5 @@// fetch is a global in Cloudflare Workers - no import needed.-// No crypto or DB imports needed - Reddit uses the public JSON API.+// 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.const REDDIT_BASE = 'https://www.reddit.com';@@ -51,7 +51,10 @@ async function redditFetch(path, cookie = null, token = null) {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');- throw new Error('Reddit blocked the request - set REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET on the server to enable authenticated API access');+ // 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 === 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}`);@@ -61,27 +64,125 @@ async function redditFetch(path, cookie = null, token = null) {return data;}-export async function fetchRedditProfile(username, cookie = null, env = null) {- const token = await getAppOnlyToken(env);- const data = await redditFetch(`/user/${username}/about.json`, cookie, token);- const u = data.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 blockedreturn {- 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,+ username,+ totalKarma: null,+ postKarma: null,+ commentKarma: null,+ awardeeKarma: null,+ awarderKarma: null,+ iconUrl: '',+ createdAt: '',+ isGold: false,+ isMod: false,+ verified: false,+ apiRestricted: true,};}+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(/&/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) {let allPosts = [];let after = null;let pages = 0;@@ -123,6 +224,11 @@ export async function fetchRedditPosts(username, cookie = null, limit = 100, env}));}+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,@@ -134,14 +240,15 @@ 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 = Math.round(totalScore / posts.length);- const avgComments = Math.round(totalComments / posts.length);+ const avgScore = posts.length > 0 ? Math.round(totalScore / posts.length) : 0;+ const avgComments = posts.length > 0 ? Math.round(totalComments / posts.length) : 0;const avgUpvoteRatio = parseFloat((posts.reduce((s, p) => s + p.upvoteRatio, 0) / posts.length * 100).toFixed(1));@@ -201,7 +308,7 @@ export function computeRedditAnalytics(profile, posts) {avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,}));const bestDayObj = postsByDayOfWeek.reduce(- (best, d) => d.avgScore > best.avgScore ? d : best,+ (best, d) => d.posts > best.posts ? d : best,postsByDayOfWeek[0]);@@ -211,7 +318,7 @@ export function computeRedditAnalytics(profile, posts) {avgScore: b.count > 0 ? Math.round(b.score / b.count) : 0,}));const bestHourObj = postsByHour.reduce(- (best, h) => h.avgScore > best.avgScore ? h : best,+ (best, h) => h.posts > best.posts ? h : best,postsByHour[0]);@@ -231,7 +338,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: Math.round(s.score / s.posts),+ avgScore: s.posts > 0 ? Math.round(s.score / s.posts) : 0,}));// Recency counts@@ -250,12 +357,13 @@ export function computeRedditAnalytics(profile, posts) {perMonth = parseFloat((posts.length / spanDays * 30).toFixed(1));}- // Virality and consistency+ // Virality and consistency - only meaningful when scores are available+ const apiRestricted = profile?.apiRestricted ?? false;const bestScore = byScore[0]?.score ?? 0;- const viralityScore = avgScore > 0 ? parseFloat((bestScore / avgScore).toFixed(1)) : 0;+ const viralityScore = (!apiRestricted && avgScore > 0) ? parseFloat((bestScore / avgScore).toFixed(1)) : 0;let consistencyScore = 0;- if (posts.length >= 3) {+ if (!apiRestricted && 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;@@ -278,6 +386,7 @@ export function computeRedditAnalytics(profile, posts) {postsLast7Days, postsLast30Days, postsLast90Days,postFrequency: { perWeek, perMonth },viralityScore, consistencyScore,+ apiRestricted,};}diff --git a/frontend/src/features/analytics/reddit/RedditAnalytics.jsx b/frontend/src/features/analytics/reddit/RedditAnalytics.jsxindex cd802ac..655b6f9 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,+ Image, Video, AlertTriangle,} 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: 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) },+ { 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) },].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,12 +174,26 @@ 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={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" />+ <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" /></div>{/* Score timeline + media type pie */}