78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
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) => {
|
|
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++;
|
|
}
|
|
}
|
|
|
|
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 {
|
|
const payload = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
|
|
|
|
if (!payload || !payload.repository) {
|
|
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) {
|
|
return res.status(200).send('No new commits to report')
|
|
}
|
|
|
|
// Send to Telegram
|
|
const telegramUrl = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`
|
|
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
|
|
})
|
|
})
|
|
|
|
res.status(200).send('ok')
|
|
} catch (error) {
|
|
console.error('Error processing webhook:', error)
|
|
res.status(500).send(`Error: ${error.message}`)
|
|
}
|
|
}
|
|
|
|
// Export both handlers
|
|
module.exports = {
|
|
webhook,
|
|
cleanup
|
|
};
|