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