const { handleGitea } = require('./gitea') const { handleGithub } = require('./github') // Store for already reported commit hashes (in-memory, resets on restart) const reportedCommits = new Set(); const commitTimestamps = new Map(); // TTL constants (used in cleanup) const COMMIT_TTL = 30 * 24 * 60 * 60 * 1000; // 30 days /** * Cleanup old commits (called by Vercel Cron) * @param {Object} req - Express request object * @param {Object} res - Express response object */ const cleanup = (req, res) => { console.log('๐Ÿงน Starting cleanup') const now = Date.now(); let cleaned = 0; for (const [hash, timestamp] of commitTimestamps.entries()) { if (now - timestamp > COMMIT_TTL) { commitTimestamps.delete(hash); reportedCommits.delete(hash); cleaned++; } } console.log('๐Ÿงน Cleanup completed:', { cleaned, remaining: reportedCommits.size }) res.status(200).json({ cleaned }); }; /** * Webhook handler that supports both JSON and x-www-form-urlencoded formats * @param {Object} req - Express request object * @param {Object} res - Express response object */ const webhook = async (req, res) => { try { console.log('๐ŸŽฏ Webhook received:', { headers: req.headers, method: req.method, path: req.path }) const payload = typeof req.body === 'string' ? JSON.parse(req.body) : req.body console.log('๐Ÿ“ฆ Payload type:', { isGitea: !!payload?.repository?.owner?.username, hasCommits: Array.isArray(payload?.commits), repoName: payload?.repository?.full_name, eventType: req.headers['x-github-event'] || req.headers['x-gitea-event'] || 'unknown' }) if (!payload || !payload.repository) { console.warn('โŒ Invalid payload:', payload) return res.status(400).send('Invalid webhook payload') } // Determine webhook type and handle accordingly const message = payload.repository.owner?.username // Gitea specific field ? handleGitea(payload, reportedCommits, commitTimestamps) : handleGithub(payload, reportedCommits, commitTimestamps) if (!message) { console.log('โญ๏ธ No new commits to report') return res.status(200).send('No new commits to report') } console.log('๐Ÿ“จ Sending message to Telegram:', message) // Send to Telegram const telegramUrl = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage` const response = await fetch(telegramUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: `-100${process.env.TELEGRAM_CHAT_ID}`, text: message, parse_mode: 'Markdown', disable_web_page_preview: true }) }) const telegramResult = await response.json() console.log('โœ… Telegram response:', telegramResult) res.status(200).send('ok') } catch (error) { console.error('๐Ÿ’ฅ Error processing webhook:', error, { body: req.body, headers: req.headers }) res.status(500).send(`Error: ${error.message}`) } } // Export both handlers module.exports = { webhook, cleanup };