|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const https = require('https'); |
| 4 | + |
| 5 | +const repoRoot = path.resolve(__dirname, '..', '..'); |
| 6 | +const metricsPath = path.join(repoRoot, 'metrics.json'); |
| 7 | +const refreshDate = new Date().toISOString().slice(0, 10); |
| 8 | +const repo = process.env.REPO; |
| 9 | +const token = process.env.TRAFFIC_TOKEN; |
| 10 | +const markerPattern = /<!-- START BADGE -->[\s\S]*?<!-- END BADGE -->/g; |
| 11 | + |
| 12 | +function readMetrics() { |
| 13 | + if (!fs.existsSync(metricsPath)) { |
| 14 | + return { totalViews: 0, refreshDate }; |
| 15 | + } |
| 16 | + |
| 17 | + try { |
| 18 | + return JSON.parse(fs.readFileSync(metricsPath, 'utf8')); |
| 19 | + } catch { |
| 20 | + return { totalViews: 0, refreshDate }; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +function writeMetrics(metrics) { |
| 25 | + fs.writeFileSync(metricsPath, `${JSON.stringify(metrics, null, 2)}\n`, 'utf8'); |
| 26 | +} |
| 27 | + |
| 28 | +function fetchTrafficViews() { |
| 29 | + if (!repo || !token) { |
| 30 | + return Promise.resolve(null); |
| 31 | + } |
| 32 | + |
| 33 | + return new Promise((resolve) => { |
| 34 | + const request = https.request( |
| 35 | + { |
| 36 | + hostname: 'api.github.com', |
| 37 | + path: `/repos/${repo}/traffic/views`, |
| 38 | + method: 'GET', |
| 39 | + headers: { |
| 40 | + 'User-Agent': 'Cloud2BR-visitor-counter', |
| 41 | + Accept: 'application/vnd.github+json', |
| 42 | + Authorization: `Bearer ${token}`, |
| 43 | + }, |
| 44 | + }, |
| 45 | + (response) => { |
| 46 | + let data = ''; |
| 47 | + response.on('data', (chunk) => { |
| 48 | + data += chunk; |
| 49 | + }); |
| 50 | + response.on('end', () => { |
| 51 | + if (response.statusCode !== 200) { |
| 52 | + console.warn(`GitHub traffic API returned ${response.statusCode}.`); |
| 53 | + resolve(null); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + try { |
| 58 | + const parsed = JSON.parse(data); |
| 59 | + resolve(typeof parsed.count === 'number' ? parsed.count : null); |
| 60 | + } catch { |
| 61 | + resolve(null); |
| 62 | + } |
| 63 | + }); |
| 64 | + } |
| 65 | + ); |
| 66 | + |
| 67 | + request.on('error', () => resolve(null)); |
| 68 | + request.end(); |
| 69 | + }); |
| 70 | +} |
| 71 | + |
| 72 | +function findMarkdownFiles(startDir) { |
| 73 | + const results = []; |
| 74 | + for (const entry of fs.readdirSync(startDir, { withFileTypes: true })) { |
| 75 | + if (entry.name === '.git' || entry.name === 'node_modules') { |
| 76 | + continue; |
| 77 | + } |
| 78 | + |
| 79 | + const fullPath = path.join(startDir, entry.name); |
| 80 | + if (entry.isDirectory()) { |
| 81 | + results.push(...findMarkdownFiles(fullPath)); |
| 82 | + continue; |
| 83 | + } |
| 84 | + |
| 85 | + if (entry.isFile() && entry.name.endsWith('.md')) { |
| 86 | + results.push(fullPath); |
| 87 | + } |
| 88 | + } |
| 89 | + return results; |
| 90 | +} |
| 91 | + |
| 92 | +function buildBadgeBlock(totalViews) { |
| 93 | + return [ |
| 94 | + '<!-- START BADGE -->', |
| 95 | + '<div align="center">', |
| 96 | + ` <img src="https://img.shields.io/badge/Total%20views-${totalViews}-limegreen" alt="Total views">`, |
| 97 | + ` <p>Refresh Date: ${refreshDate}</p>`, |
| 98 | + '</div>', |
| 99 | + '<!-- END BADGE -->', |
| 100 | + ].join('\n'); |
| 101 | +} |
| 102 | + |
| 103 | +function updateMarkdownBadges(totalViews) { |
| 104 | + const replacement = buildBadgeBlock(totalViews); |
| 105 | + for (const filePath of findMarkdownFiles(repoRoot)) { |
| 106 | + const content = fs.readFileSync(filePath, 'utf8'); |
| 107 | + if (!markerPattern.test(content)) { |
| 108 | + markerPattern.lastIndex = 0; |
| 109 | + continue; |
| 110 | + } |
| 111 | + |
| 112 | + markerPattern.lastIndex = 0; |
| 113 | + const updated = content.replace(markerPattern, replacement); |
| 114 | + fs.writeFileSync(filePath, updated, 'utf8'); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +async function main() { |
| 119 | + const currentMetrics = readMetrics(); |
| 120 | + const fetchedViews = await fetchTrafficViews(); |
| 121 | + const totalViews = fetchedViews ?? currentMetrics.totalViews ?? 0; |
| 122 | + const nextMetrics = { totalViews, refreshDate }; |
| 123 | + |
| 124 | + writeMetrics(nextMetrics); |
| 125 | + updateMarkdownBadges(totalViews); |
| 126 | + console.log(`Visitor badge refreshed with ${totalViews} total views.`); |
| 127 | +} |
| 128 | + |
| 129 | +main().catch((error) => { |
| 130 | + console.error(error); |
| 131 | + process.exit(1); |
| 132 | +}); |
0 commit comments