Skip to content
Shell
9.1 KB
Raw Blame
/**
 * Email Alert Integration
 * Sends email notifications for high-value discoveries
 *
 * Uses nodemailer-compatible SMTP or can integrate with services like:
 * - SendGrid
 * - Mailgun
 * - AWS SES
 * - Resend
 */

import { execFileNoThrow } from '../utils/execFileNoThrow.js';
import type { GoldmineScore, MarketInsight } from '../types.js';

/**
 * Escape HTML entities to prevent XSS in emails
 */
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;');
}

export interface EmailConfig {
  to: string;
  from?: string;
  smtpHost?: string;
  smtpPort?: number;
  smtpUser?: string;
  smtpPass?: string;
  // Or use API-based services
  sendgridApiKey?: string;
  resendApiKey?: string;
}

/**
 * Format thread as HTML email
 */
function formatThreadEmail(thread: GoldmineScore): { subject: string; html: string; text: string } {
  const subject = `πŸ† Reddit Goldmine: ${thread.title.slice(0, 50)}...`;

  const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: #ff4500; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
    .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }
    .stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin: 20px 0; }
    .stat { background: white; padding: 15px; border-radius: 4px; text-align: center; }
    .stat-value { font-size: 24px; font-weight: bold; color: #ff4500; }
    .stat-label { font-size: 12px; color: #666; }
    .cta { display: inline-block; background: #ff4500; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin-top: 20px; }
  </style>
</head>
<body>
  <div class="header">
    <h1>πŸ† High-Value Thread Found!</h1>
  </div>
  <div class="content">
    <h2>${escapeHtml(thread.title)}</h2>
    <p><strong>Subreddit:</strong> r/${escapeHtml(thread.subreddit)}</p>

    <div class="stats">
      <div class="stat">
        <div class="stat-value">${escapeHtml(String(thread.goldmineScore))}</div>
        <div class="stat-label">Goldmine Score</div>
      </div>
      <div class="stat">
        <div class="stat-value">${escapeHtml(String(thread.score))}</div>
        <div class="stat-label">Post Score</div>
      </div>
      <div class="stat">
        <div class="stat-value">${escapeHtml(String(thread.numComments))}</div>
        <div class="stat-label">Comments</div>
      </div>
      <div class="stat">
        <div class="stat-value">${escapeHtml(String(Math.round(thread.upvoteRatio * 100)))}%</div>
        <div class="stat-label">Upvote Ratio</div>
      </div>
    </div>

    <a href="${escapeHtml(thread.url)}" class="cta">View Thread β†’</a>
  </div>
</body>
</html>
  `.trim();

  const text = `
πŸ† HIGH-VALUE THREAD FOUND!

${thread.title}

Subreddit: r/${thread.subreddit}
Goldmine Score: ${thread.goldmineScore}
Post Score: ${thread.score}
Comments: ${thread.numComments}
Upvote Ratio: ${Math.round(thread.upvoteRatio * 100)}%

View: ${thread.url}
  `.trim();

  return { subject, html, text };
}

/**
 * Format insights as HTML email
 */
function formatInsightsEmail(insight: MarketInsight, threadTitle: string): { subject: string; html: string; text: string } {
  const subject = `πŸ“Š Market Insights: ${threadTitle.slice(0, 40)}...`;

  const painPointsHtml = insight.painPoints.length > 0
    ? `<h3>πŸ”΄ Pain Points</h3><ul>${insight.painPoints.map(p => `<li><strong>${escapeHtml(p.description)}</strong> (frequency: ${escapeHtml(String(p.frequency))})</li>`).join('')}</ul>`
    : '';

  const opportunitiesHtml = insight.opportunities.length > 0
    ? `<h3>πŸ’‘ Opportunities</h3><ul>${insight.opportunities.map(o => `<li><strong>[${escapeHtml(o.confidence)}]</strong> ${escapeHtml(o.description)}<br><small>Target: ${escapeHtml(o.targetAudience)}</small></li>`).join('')}</ul>`
    : '';

  const competitorsHtml = insight.competitorMentions.length > 0
    ? `<h3>🏒 Competitors Mentioned</h3><ul>${insight.competitorMentions.map(c => `<li><strong>${escapeHtml(c.name)}</strong> (${escapeHtml(c.sentiment)}) - ${escapeHtml(c.context)}</li>`).join('')}</ul>`
    : '';

  const signalsHtml = insight.buyingSignals.length > 0
    ? `<h3>πŸ’° Buying Signals</h3><ul>${insight.buyingSignals.map(s => `<li>"${escapeHtml(s.quote.slice(0, 150))}..." - u/${escapeHtml(s.author)} (${escapeHtml(String(s.score))} pts)</li>`).join('')}</ul>`
    : '';

  const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: #0066cc; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
    .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }
    .summary { background: white; padding: 15px; border-radius: 4px; border-left: 4px solid #0066cc; margin: 20px 0; }
    h3 { color: #333; margin-top: 25px; }
    ul { padding-left: 20px; }
    li { margin: 10px 0; }
    .cta { display: inline-block; background: #0066cc; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin-top: 20px; }
  </style>
</head>
<body>
  <div class="header">
    <h1>πŸ“Š Market Insights Extracted</h1>
  </div>
  <div class="content">
    <p><strong>Thread:</strong> ${escapeHtml(threadTitle)}</p>
    <p><strong>Subreddit:</strong> r/${escapeHtml(insight.subreddit)}</p>

    <div class="summary">
      <strong>Summary:</strong> ${escapeHtml(insight.summary)}
    </div>

    ${painPointsHtml}
    ${opportunitiesHtml}
    ${competitorsHtml}
    ${signalsHtml}

    <a href="${escapeHtml(insight.threadUrl)}" class="cta">View Thread β†’</a>
  </div>
</body>
</html>
  `.trim();

  const text = `
πŸ“Š MARKET INSIGHTS EXTRACTED

Thread: ${threadTitle}
Subreddit: r/${insight.subreddit}

Summary: ${insight.summary}

Pain Points (${insight.painPoints.length}):
${insight.painPoints.map(p => `- ${p.description}`).join('\n')}

Opportunities (${insight.opportunities.length}):
${insight.opportunities.map(o => `- [${o.confidence}] ${o.description}`).join('\n')}

View: ${insight.threadUrl}
  `.trim();

  return { subject, html, text };
}

/**
 * Send email via Resend API
 */
async function sendViaResend(apiKey: string, to: string, from: string, subject: string, html: string): Promise<boolean> {
  const result = await execFileNoThrow('curl', [
    '-s',
    '-X', 'POST',
    'https://api.resend.com/emails',
    '-H', `Authorization: Bearer ${apiKey}`,
    '-H', 'Content-Type: application/json',
    '-d', JSON.stringify({ from, to: [to], subject, html })
  ]);

  return result.status === 'success' && result.stdout.includes('"id"');
}

/**
 * Send email via SendGrid API
 */
async function sendViaSendGrid(apiKey: string, to: string, from: string, subject: string, html: string, text: string): Promise<boolean> {
  const result = await execFileNoThrow('curl', [
    '-s',
    '-X', 'POST',
    'https://api.sendgrid.com/v3/mail/send',
    '-H', `Authorization: Bearer ${apiKey}`,
    '-H', 'Content-Type: application/json',
    '-d', JSON.stringify({
      personalizations: [{ to: [{ email: to }] }],
      from: { email: from },
      subject,
      content: [
        { type: 'text/plain', value: text },
        { type: 'text/html', value: html }
      ]
    })
  ]);

  return result.status === 'success';
}

/**
 * Email Alert Manager
 */
export class EmailAlerts {
  private config: EmailConfig;

  constructor(config: EmailConfig) {
    this.config = {
      from: 'Reddit Research Agent <[email protected]>',
      ...config
    };
  }

  /**
   * Send email using configured provider
   */
  private async sendEmail(subject: string, html: string, text: string): Promise<boolean> {
    const { to, from, resendApiKey, sendgridApiKey } = this.config;

    if (resendApiKey) {
      return sendViaResend(resendApiKey, to, from || '[email protected]', subject, html);
    }

    if (sendgridApiKey) {
      return sendViaSendGrid(sendgridApiKey, to, from || '[email protected]', subject, html, text);
    }

    console.warn('No email provider configured. Set RESEND_API_KEY or SENDGRID_API_KEY.');
    return false;
  }

  /**
   * Alert on high-value thread
   */
  async alertThread(thread: GoldmineScore): Promise<boolean> {
    const { subject, html, text } = formatThreadEmail(thread);
    return this.sendEmail(subject, html, text);
  }

  /**
   * Alert on new insights
   */
  async alertInsights(insight: MarketInsight, threadTitle: string): Promise<boolean> {
    const { subject, html, text } = formatInsightsEmail(insight, threadTitle);
    return this.sendEmail(subject, html, text);
  }
}

/**
 * Create email alerts from environment
 */
export function createEmailAlerts(): EmailAlerts | null {
  const to = process.env.ALERT_EMAIL_TO;
  if (!to) {
    return null;
  }

  return new EmailAlerts({
    to,
    from: process.env.ALERT_EMAIL_FROM,
    resendApiKey: process.env.RESEND_API_KEY,
    sendgridApiKey: process.env.SENDGRID_API_KEY
  });
}