This repository was archived by the owner on Apr 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
151 lines (141 loc) · 4.8 KB
/
index.js
File metadata and controls
151 lines (141 loc) · 4.8 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const { spawn } = require('child_process');
const core = require('@actions/core');
const fs = require('fs');
const puppeteer = require('puppeteer');
const WIDTH = 329;
const HEIGHT = 88;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const FILEPATH = process.env.IMAGE_PATH;
const THM_USERNAME = process.env.USERNAME;
const COMMITTER_USERNAME = process.env.COMMITTER_USERNAME;
const COMMITTER_EMAIL = process.env.COMMITTER_EMAIL;
const COMMIT_MESSAGE = process.env.COMMIT_MESSAGE;
const USE_STATIC_IMAGE = process.env.USE_STATIC_IMAGE === "true";
const USER_PUBLIC_ID = process.env.USER_PUBLIC_ID;
/*
* Executes a command and returns its result as promise
*/
function exec(cmd, args = [], options = {}) {
console.log(`[exec] Running command: ${cmd} ${args.join(' ')}`);
return new Promise((resolve, reject) => {
let outputData = '';
const app = spawn(cmd, args, { ...options, stdio: 'pipe' });
if (app.stdout) app.stdout.on('data', data => {
outputData += data.toString();
process.stdout.write(`[exec][stdout] ${data.toString()}`);
});
if (app.stderr) app.stderr.on('data', data => {
outputData += data.toString();
process.stderr.write(`[exec][stderr] ${data.toString()}`);
});
app.on('close', code => {
console.log(`[exec] Process exited with code: ${code}`);
if (code !== 0) return reject({ code, outputData });
resolve({ code, outputData });
});
app.on('error', err => {
console.error(`[exec] Error: ${err.message}`);
reject({ code: 1, outputData: err.message });
});
});
}
core.setSecret(GITHUB_TOKEN);
function htmlToPng(html, outputPath) {
return puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
]
})
.then(browser => {
return browser.newPage()
.then(page => {
return page.setViewport({ width: WIDTH, height: HEIGHT })
.then(() => page.setContent(html, { waitUntil: 'networkidle0' }))
.then(() => page.screenshot({
path: outputPath,
fullPage: false,
omitBackground: true,
clip: { x: 0, y: 0, width: WIDTH, height: HEIGHT }
}))
.then(() => browser.close())
.catch(err => {
return browser.close().then(() => { throw err; });
});
});
});
}
/**
* Downloads the image and commits/pushes it to GitHub.
*/
function dlImg(githubToken, filePath, username, useStaticImage, userPublicId) {
let url = "";
if (useStaticImage) {
console.log('[dlImg] Using static image URL.');
url = `https://tryhackme-badges.s3.amazonaws.com/${username}.png`;
} else {
console.log('[dlImg] Using dynamic image URL.');
url = `https://tryhackme.com/api/v2/badges/public-profile?userPublicId=${userPublicId}`;
}
console.log(`[dlImg] Downloading image from: ${url}`);
fetch(url)
.then(res => {
if (!res.ok) throw new Error(`[dlImg] Failed to download image: ${res.statusText}`);
return res.arrayBuffer();
})
.then(buffer => {
if (useStaticImage) {
fs.writeFileSync(filePath, Buffer.from(buffer));
console.log(`[dlImg] Image saved to: ${filePath}`);
} else {
const htmlContent = Buffer.from(buffer).toString('utf8');
console.log('[dlImg] Converting HTML to PNG...');
console.log(`[dlImg] Image saved to: ${filePath}`);
return htmlToPng(htmlContent, filePath);
}
})
.then(() => {
console.log('[dlImg] Setting git user configuration...');
return exec('git', ['config', '--global', 'user.email', COMMITTER_EMAIL]);
})
.then(() => exec('git', ['config', '--global', 'user.name', COMMITTER_USERNAME]))
.then(() => {
if (githubToken) {
console.log('[dlImg] Updating git remote URL...');
return exec('git', [
'remote', 'set-url', 'origin',
`https://${githubToken}@github.com/${process.env.GITHUB_REPOSITORY}.git`
]);
}
})
.then(() => {
console.log(`[dlImg] Adding file to git: ${filePath}`);
return exec('git', ['add', filePath]);
})
.then(() => {
console.log('[dlImg] Committing changes...');
return exec('git', ['commit', '-m', COMMIT_MESSAGE]);
})
.then(() => {
console.log('[dlImg] Pushing changes to remote...');
return exec('git', ['push']);
})
.then(() => {
console.log('[dlImg] Image downloaded and changes pushed successfully.');
})
.catch(error => {
if (error.code === 1 && error.outputData && error.outputData.includes('nothing to commit')) {
console.log('[dlImg] No changes to commit.');
} else {
console.error('[dlImg] Error:', error.outputData || error.message);
}
});
}
console.log('[main] Starting badge workflow...');
dlImg(
GITHUB_TOKEN,
FILEPATH,
THM_USERNAME,
USE_STATIC_IMAGE,
USER_PUBLIC_ID
)