Skip to content
Shell
6.4 KB
Raw Blame
/**
 * Reddit JSON API Fetcher
 * Uses the hidden /.json endpoint to fetch thread data
 */

import { execFileNoThrow } from '../utils/execFileNoThrow.js';
import type { RedditPost, RedditComment, ThreadData, ThreadMetrics, GoldmineScore } from '../types.js';

const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';

/**
 * Fetch JSON from Reddit using curl (bypasses urllib fingerprinting)
 */
async function fetchRedditJson(url: string): Promise<unknown> {
  // Normalize URL
  url = url.replace('reddit.com', 'www.reddit.com');
  if (url.includes('www.www.')) {
    url = url.replace('www.www.', 'www.');
  }
  if (!url.endsWith('.json')) {
    url = url.replace(/\/?$/, '.json');
  }

  const result = await execFileNoThrow('curl', ['-s', '-A', USER_AGENT, url], {
    maxBuffer: 10 * 1024 * 1024, // 10MB buffer for large threads
  });

  if (result.status === 'error' || !result.stdout) {
    throw new Error(`Failed to fetch Reddit: ${result.stderr}`);
  }

  return JSON.parse(result.stdout);
}

/**
 * Extract comments recursively from Reddit's nested structure
 */
function extractComments(children: any[], depth = 0): RedditComment[] {
  const results: RedditComment[] = [];

  for (const child of children) {
    if (child.kind === 't1') { // t1 = comment
      const data = child.data;
      const comment: RedditComment = {
        id: data.id,
        body: data.body || '',
        score: data.score || 0,
        author: data.author || '[deleted]',
        depth,
        createdUtc: data.created_utc,
        repliesCount: 0,
      };

      // Extract nested replies
      let replies: RedditComment[] = [];
      if (data.replies && typeof data.replies === 'object') {
        const replyChildren = data.replies?.data?.children || [];
        replies = extractComments(replyChildren, depth + 1);
        comment.repliesCount = replies.length;
      }

      results.push(comment);
      results.push(...replies);
    }
  }

  return results;
}

/**
 * Fetch and structure a Reddit thread
 */
export async function fetchThread(url: string): Promise<ThreadData> {
  const data = await fetchRedditJson(url) as any[];

  // Extract post
  const postData = data[0].data.children[0].data;
  const post: RedditPost = {
    id: postData.id,
    title: postData.title || '',
    selftext: postData.selftext || '',
    score: postData.score || 0,
    upvoteRatio: postData.upvote_ratio || 0,
    numComments: postData.num_comments || 0,
    author: postData.author || '[deleted]',
    subreddit: postData.subreddit || '',
    permalink: postData.permalink || '',
    url: `https://reddit.com${postData.permalink}`,
    createdUtc: postData.created_utc,
    flair: postData.link_flair_text,
  };

  // Extract all comments
  const allComments = extractComments(data[1].data.children);

  // Sort by score for top comments
  const topComments = [...allComments]
    .sort((a, b) => b.score - a.score)
    .slice(0, 30);

  // Calculate metrics
  const totalCommentScore = allComments.reduce((sum, c) => sum + c.score, 0);
  const metrics: ThreadMetrics = {
    totalComments: allComments.length,
    totalCommentScore,
    avgCommentScore: allComments.length > 0 ? Math.round((totalCommentScore / allComments.length) * 100) / 100 : 0,
    maxDepth: Math.max(...allComments.map(c => c.depth), 0),
    uniqueAuthors: new Set(allComments.map(c => c.author)).size,
  };

  return {
    extractedAt: new Date().toISOString(),
    post,
    metrics,
    topComments,
    allComments,
  };
}

/**
 * Search a subreddit for threads
 */
export async function searchSubreddit(
  subreddit: string,
  query?: string,
  options: { sort?: string; time?: string; limit?: number } = {}
): Promise<GoldmineScore[]> {
  const { sort = 'top', time = 'year', limit = 25 } = options;

  let url: string;
  if (query) {
    const encodedQuery = encodeURIComponent(query);
    url = `https://www.reddit.com/r/${subreddit}/search.json?q=${encodedQuery}&restrict_sr=1&sort=${sort}&t=${time}&limit=${limit}`;
  } else {
    url = `https://www.reddit.com/r/${subreddit}/${sort}.json?t=${time}&limit=${limit}`;
  }

  const data = await fetchRedditJson(url) as any;
  const threads: GoldmineScore[] = [];

  for (const child of data.data?.children || []) {
    const p = child.data;
    threads.push({
      url: `https://reddit.com${p.permalink}`,
      title: p.title || '',
      score: p.score || 0,
      numComments: p.num_comments || 0,
      upvoteRatio: p.upvote_ratio || 0,
      goldmineScore: calculateGoldmineScore(p),
      subreddit: p.subreddit || subreddit,
    });
  }

  return threads;
}

/**
 * Calculate how valuable a thread is for market research
 */
function calculateGoldmineScore(post: any): number {
  let score = 0;

  // High comment count = lots of discussion
  score += Math.min((post.num_comments || 0) / 10, 20);

  // Good upvote ratio = quality content
  score += (post.upvote_ratio || 0) * 10;

  // Post score indicates visibility
  score += Math.min((post.score || 0) / 50, 10);

  // Bonus for goldmine keywords in title
  const titleLower = (post.title || '').toLowerCase();
  const goldmineKeywords = [
    'wish', 'hate', 'love', 'best', 'worst', 'looking for',
    'recommend', 'help', 'advice', 'alternative', 'switched',
    'paying', 'worth it', 'frustrat', 'problem', 'solution'
  ];

  for (const kw of goldmineKeywords) {
    if (titleLower.includes(kw)) {
      score += 3;
    }
  }

  return Math.round(score * 100) / 100;
}

/**
 * Find goldmine threads across multiple queries
 */
export async function findGoldmineThreads(
  subreddit: string,
  queries: string[] = []
): Promise<GoldmineScore[]> {
  const defaultQueries = [
    'wish existed',
    'hate about',
    'frustrating',
    'looking for',
    'recommend',
    'alternative to',
    'switched from',
    'paying for',
    'game changer',
  ];

  const searchQueries = queries.length > 0 ? queries : defaultQueries;
  const allThreads: GoldmineScore[] = [];
  const seenUrls = new Set<string>();

  for (const query of searchQueries) {
    try {
      const threads = await searchSubreddit(subreddit, query, { limit: 10 });
      for (const thread of threads) {
        if (!seenUrls.has(thread.url)) {
          seenUrls.add(thread.url);
          allThreads.push(thread);
        }
      }
    } catch (error) {
      console.error(`Failed to search "${query}":`, error);
    }
  }

  // Sort by goldmine score
  return allThreads.sort((a, b) => b.goldmineScore - a.goldmineScore);
}