56 lines
2.3 KiB
JavaScript
56 lines
2.3 KiB
JavaScript
const fs = require('node:fs/promises');
|
|
const path = require('node:path');
|
|
const { createHash } = require('node:crypto');
|
|
|
|
const targetDir = path.join(__dirname, '..', 'public', 'images');
|
|
const repo = 'antonndev/adcdn';
|
|
const revision = encodeURIComponent(process.argv[2] || 'main');
|
|
const mediaExtension = /\.(?:avif|gif|ico|jpe?g|png|svg|webm|webp)$/i;
|
|
|
|
async function fetchAsset(url) {
|
|
const response = await fetch(url, { signal: AbortSignal.timeout(20_000) });
|
|
if (!response.ok) throw new Error(`${response.status} fetching ${url}`);
|
|
return response;
|
|
}
|
|
|
|
async function main() {
|
|
const response = await fetchAsset(`https://api.github.com/repos/${repo}/git/trees/${revision}?recursive=1`);
|
|
const { tree, truncated } = await response.json();
|
|
if (truncated || !Array.isArray(tree)) throw new Error('Incomplete GitHub asset listing');
|
|
|
|
let downloaded = 0;
|
|
let skipped = 0;
|
|
for (const entry of tree) {
|
|
if (entry.type !== 'blob' || !/^100(?:644|755)$/.test(entry.mode) || !mediaExtension.test(entry.path)) continue;
|
|
const segments = entry.path.split('/');
|
|
if (segments.some(segment => !segment || segment === '.' || segment === '..' || segment.includes('\\'))) {
|
|
throw new Error(`Invalid asset path: ${entry.path}`);
|
|
}
|
|
const dest = path.join(targetDir, ...segments);
|
|
const existing = await fs.lstat(dest).catch(error => {
|
|
if (error.code !== 'ENOENT') throw error;
|
|
});
|
|
if (existing?.isFile() && existing.size > 0) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
if (existing) throw new Error(`Cannot replace existing asset: ${dest}`);
|
|
|
|
const url = `https://raw.githubusercontent.com/${repo}/${revision}/${segments.map(encodeURIComponent).join('/')}`;
|
|
const asset = await fetchAsset(url);
|
|
const data = Buffer.from(await asset.arrayBuffer());
|
|
const hash = createHash('sha1').update(`blob ${data.length}\0`).update(data).digest('hex');
|
|
if (hash !== entry.sha) throw new Error(`Blob hash mismatch: ${entry.path}`);
|
|
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
await fs.writeFile(dest, data, { flag: 'wx' });
|
|
console.log(`Downloaded: ${entry.path}`);
|
|
downloaded++;
|
|
}
|
|
console.log(`${downloaded} downloaded, ${skipped} already present.`);
|
|
}
|
|
|
|
main().catch(error => {
|
|
console.error(error.message);
|
|
process.exitCode = 1;
|
|
});
|