Skip to content
Shell
14.1 KB
Raw Blame
/**
 * Web Dashboard Server
 * Simple HTTP server to explore insights
 */

import { createServer, IncomingMessage, ServerResponse } from 'http';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import {
  initDatabase,
  getStats,
  getInsightsByType,
  getUnanalyzedThreads,
  getRecentRuns,
  getTrackedSources
} from '../db/index.js';

const __dirname = dirname(fileURLToPath(import.meta.url));

/**
 * Escape HTML entities to prevent XSS
 */
function escapeHtml(str: string | undefined | null): string {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

/**
 * Generate HTML dashboard
 */
function generateDashboard(): string {
  const stats = getStats();
  const recentRuns = getRecentRuns(5);
  const sources = getTrackedSources();
  const painPoints = getInsightsByType('pain_point', 10);
  const opportunities = getInsightsByType('opportunity', 10);
  const competitors = getInsightsByType('competitor', 10);
  const signals = getInsightsByType('buying_signal', 10);
  const unanalyzed = getUnanalyzedThreads(10);

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Reddit Research Dashboard</title>
  <style>
    :root {
      --bg: #0f172a;
      --card-bg: #1e293b;
      --text: #e2e8f0;
      --text-muted: #94a3b8;
      --accent: #f97316;
      --success: #22c55e;
      --danger: #ef4444;
      --purple: #a855f7;
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: var(--bg);
      color: var(--text);
      line-height: 1.6;
      padding: 20px;
    }
    .container { max-width: 1400px; margin: 0 auto; }
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #334155;
    }
    h1 { font-size: 1.8rem; display: flex; align-items: center; gap: 10px; }
    h1::before { content: 'πŸ”'; }
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }
    .stat-card {
      background: var(--card-bg);
      border-radius: 12px;
      padding: 20px;
      text-align: center;
    }
    .stat-value {
      font-size: 2.5rem;
      font-weight: bold;
      color: var(--accent);
    }
    .stat-label { color: var(--text-muted); font-size: 0.9rem; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; }
    .card {
      background: var(--card-bg);
      border-radius: 12px;
      padding: 20px;
      overflow: hidden;
    }
    .card h2 {
      font-size: 1.2rem;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #334155;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .list { list-style: none; }
    .list li {
      padding: 12px 0;
      border-bottom: 1px solid #334155;
    }
    .list li:last-child { border-bottom: none; }
    .list a {
      color: var(--text);
      text-decoration: none;
    }
    .list a:hover { color: var(--accent); }
    .badge {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 0.75rem;
      font-weight: 600;
    }
    .badge-success { background: var(--success); color: white; }
    .badge-danger { background: var(--danger); color: white; }
    .badge-purple { background: var(--purple); color: white; }
    .badge-muted { background: #475569; color: white; }
    .meta { color: var(--text-muted); font-size: 0.85rem; margin-top: 5px; }
    .score {
      display: inline-block;
      background: var(--accent);
      color: white;
      padding: 2px 8px;
      border-radius: 4px;
      font-weight: bold;
      font-size: 0.85rem;
    }
    .quote {
      background: #334155;
      padding: 10px 15px;
      border-radius: 8px;
      border-left: 3px solid var(--accent);
      font-style: italic;
      margin: 10px 0;
    }
    .empty { color: var(--text-muted); text-align: center; padding: 30px; }
    .refresh-btn {
      background: var(--accent);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
    }
    .refresh-btn:hover { opacity: 0.9; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #334155; }
    th { color: var(--text-muted); font-weight: 500; }
  </style>
</head>
<body>
  <div class="container">
    <header>
      <h1>Reddit Research Dashboard</h1>
      <button class="refresh-btn" onclick="location.reload()">↻ Refresh</button>
    </header>

    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-value">${stats.totalThreads}</div>
        <div class="stat-label">Threads Scanned</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">${stats.analyzedThreads}</div>
        <div class="stat-label">Threads Analyzed</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">${stats.totalInsights}</div>
        <div class="stat-label">Insights Found</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">${stats.topSubreddits.length}</div>
        <div class="stat-label">Subreddits</div>
      </div>
    </div>

    <div class="grid">
      <!-- Pain Points -->
      <div class="card">
        <h2>πŸ”΄ Pain Points</h2>
        ${painPoints.length === 0 ? '<div class="empty">No pain points found yet</div>' : `
        <ul class="list">
          ${painPoints.map(p => `
            <li>
              <div>${escapeHtml(p.content)}</div>
              ${p.metadata ? `<div class="meta">Frequency: ${escapeHtml(String((p.metadata as any).frequency || 'N/A'))} | Sentiment: ${escapeHtml(String((p.metadata as any).sentiment || 'N/A'))}</div>` : ''}
            </li>
          `).join('')}
        </ul>
        `}
      </div>

      <!-- Opportunities -->
      <div class="card">
        <h2>πŸ’‘ Opportunities</h2>
        ${opportunities.length === 0 ? '<div class="empty">No opportunities found yet</div>' : `
        <ul class="list">
          ${opportunities.map(o => `
            <li>
              <div>
                <span class="badge ${o.confidence === 'high' ? 'badge-success' : o.confidence === 'medium' ? 'badge-purple' : 'badge-muted'}">${escapeHtml(o.confidence || 'unknown')}</span>
                ${escapeHtml(o.content)}
              </div>
              ${o.metadata ? `<div class="meta">Type: ${escapeHtml(String((o.metadata as any).type || 'N/A'))} | Target: ${escapeHtml(String((o.metadata as any).targetAudience || 'N/A'))}</div>` : ''}
            </li>
          `).join('')}
        </ul>
        `}
      </div>

      <!-- Competitors -->
      <div class="card">
        <h2>🏒 Competitors Mentioned</h2>
        ${competitors.length === 0 ? '<div class="empty">No competitors found yet</div>' : `
        <ul class="list">
          ${competitors.map(c => `
            <li>
              <div>
                <strong>${escapeHtml(c.content)}</strong>
                <span class="badge ${(c.metadata as any)?.sentiment === 'positive' ? 'badge-success' : (c.metadata as any)?.sentiment === 'negative' ? 'badge-danger' : 'badge-muted'}">${escapeHtml(String((c.metadata as any)?.sentiment || 'neutral'))}</span>
              </div>
              ${c.metadata ? `<div class="meta">${escapeHtml(String((c.metadata as any).context || ''))}</div>` : ''}
            </li>
          `).join('')}
        </ul>
        `}
      </div>

      <!-- Buying Signals -->
      <div class="card">
        <h2>πŸ’° Buying Signals</h2>
        ${signals.length === 0 ? '<div class="empty">No buying signals found yet</div>' : `
        <ul class="list">
          ${signals.map(s => `
            <li>
              <div class="quote">"${escapeHtml(s.content.slice(0, 150))}${s.content.length > 150 ? '...' : ''}"</div>
              <div class="meta">
                ${(s.metadata as any)?.author ? `u/${escapeHtml(String((s.metadata as any).author))}` : 'Unknown'}
                ${(s.metadata as any)?.score ? ` β€’ ${escapeHtml(String((s.metadata as any).score))} pts` : ''}
                ${(s.metadata as any)?.signalType ? ` β€’ ${escapeHtml(String((s.metadata as any).signalType))}` : ''}
              </div>
            </li>
          `).join('')}
        </ul>
        `}
      </div>

      <!-- Top Subreddits -->
      <div class="card">
        <h2>πŸ“Š Top Subreddits</h2>
        <table>
          <thead>
            <tr><th>Subreddit</th><th>Threads</th></tr>
          </thead>
          <tbody>
            ${stats.topSubreddits.map(s => `
              <tr>
                <td>r/${s.subreddit}</td>
                <td>${s.count}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>

      <!-- Tracked Sources -->
      <div class="card">
        <h2>🎯 Tracked Sources</h2>
        ${sources.length === 0 ? '<div class="empty">No sources configured</div>' : `
        <ul class="list">
          ${sources.map(s => `
            <li>
              <div>r/${escapeHtml(s.subreddit)}${s.query ? ` β€” "${escapeHtml(s.query)}"` : ''}</div>
              ${s.lastScanned ? `<div class="meta">Last scanned: ${escapeHtml(new Date(s.lastScanned).toLocaleString())}</div>` : ''}
            </li>
          `).join('')}
        </ul>
        `}
      </div>

      <!-- Recent Runs -->
      <div class="card">
        <h2>πŸ• Recent Runs</h2>
        ${recentRuns.length === 0 ? '<div class="empty">No runs yet</div>' : `
        <table>
          <thead>
            <tr><th>Started</th><th>Status</th><th>Threads</th><th>Insights</th></tr>
          </thead>
          <tbody>
            ${recentRuns.map(r => `
              <tr>
                <td>${escapeHtml(new Date(r.startedAt).toLocaleString())}</td>
                <td><span class="badge ${r.status === 'completed' ? 'badge-success' : r.status === 'running' ? 'badge-purple' : 'badge-danger'}">${escapeHtml(r.status)}</span></td>
                <td>${escapeHtml(String(r.threadsScanned))}</td>
                <td>${escapeHtml(String(r.insightsFound))}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
        `}
      </div>

      <!-- Unanalyzed Threads -->
      <div class="card">
        <h2>πŸ“‹ Queue (Unanalyzed)</h2>
        ${unanalyzed.length === 0 ? '<div class="empty">All threads analyzed!</div>' : `
        <ul class="list">
          ${unanalyzed.map(t => `
            <li>
              <span class="score">${escapeHtml(String(t.goldmineScore))}</span>
              <a href="${escapeHtml(t.url)}" target="_blank">${escapeHtml(t.url.split('/comments/')[1]?.split('/')[1]?.slice(0, 50) || 'View thread')}...</a>
            </li>
          `).join('')}
        </ul>
        `}
      </div>
    </div>
  </div>

  <script>
    // Auto-refresh every 30 seconds
    // setTimeout(() => location.reload(), 30000);
  </script>
</body>
</html>
  `.trim();
}

/**
 * Generate JSON API response
 */
function generateApiResponse(): string {
  const stats = getStats();
  const recentRuns = getRecentRuns(10);
  const sources = getTrackedSources();
  const painPoints = getInsightsByType('pain_point', 50);
  const opportunities = getInsightsByType('opportunity', 50);
  const competitors = getInsightsByType('competitor', 50);
  const signals = getInsightsByType('buying_signal', 50);

  return JSON.stringify({
    stats,
    recentRuns,
    sources,
    insights: {
      painPoints,
      opportunities,
      competitors,
      buyingSignals: signals
    }
  }, null, 2);
}

/**
 * HTTP request handler
 */
function handleRequest(req: IncomingMessage, res: ServerResponse): void {
  const url = req.url || '/';

  // CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');

  if (req.method === 'OPTIONS') {
    res.writeHead(204);
    res.end();
    return;
  }

  try {
    if (url === '/' || url === '/dashboard') {
      res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      res.end(generateDashboard());
    } else if (url === '/api' || url === '/api/stats') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(generateApiResponse());
    } else if (url === '/api/insights/pain_points') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(getInsightsByType('pain_point', 100)));
    } else if (url === '/api/insights/opportunities') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(getInsightsByType('opportunity', 100)));
    } else if (url === '/api/insights/competitors') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(getInsightsByType('competitor', 100)));
    } else if (url === '/api/insights/buying_signals') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(getInsightsByType('buying_signal', 100)));
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not Found');
    }
  } catch (error) {
    console.error('Dashboard error:', error);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end(`Server Error: ${error}`);
  }
}

/**
 * Start dashboard server
 */
export function startDashboard(port = 3456, dbPath?: string): void {
  // Initialize database
  initDatabase(dbPath);

  const server = createServer(handleRequest);

  server.listen(port, () => {
    console.log(`\n🎯 Reddit Research Dashboard`);
    console.log(`   http://localhost:${port}`);
    console.log(`   http://localhost:${port}/api (JSON API)`);
    console.log(`\nPress Ctrl+C to stop\n`);
  });
}

// CLI entry point
if (process.argv[1]?.includes('dashboard')) {
  const port = parseInt(process.argv[2] || '3456', 10);
  startDashboard(port);
}