|
| 1 | +/** |
| 2 | + * Logo cache service — downloads script logos to public/logos/ so they can be |
| 3 | + * served locally by Next.js instead of fetching from remote CDNs on every request. |
| 4 | + * |
| 5 | + * Logos are stored as `public/logos/{slug}.webp` (keeping original extension when not webp). |
| 6 | + * ScriptCard / ScriptDetailModal can then use `/logos/{slug}.{ext}` as the src. |
| 7 | + */ |
| 8 | + |
| 9 | +import { existsSync, mkdirSync } from 'fs'; |
| 10 | +import { writeFile, readdir, unlink } from 'fs/promises'; |
| 11 | +import { join, extname } from 'path'; |
| 12 | + |
| 13 | +const LOGOS_DIR = join(process.cwd(), 'public', 'logos'); |
| 14 | + |
| 15 | +/** Ensure the logos directory exists. */ |
| 16 | +function ensureLogosDir(): void { |
| 17 | + if (!existsSync(LOGOS_DIR)) { |
| 18 | + mkdirSync(LOGOS_DIR, { recursive: true }); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/** Extract a reasonable file extension from a logo URL. */ |
| 23 | +function getExtension(url: string): string { |
| 24 | + try { |
| 25 | + const pathname = new URL(url).pathname; |
| 26 | + const ext = extname(pathname).toLowerCase(); |
| 27 | + if (['.png', '.jpg', '.jpeg', '.svg', '.webp', '.gif', '.ico'].includes(ext)) { |
| 28 | + return ext; |
| 29 | + } |
| 30 | + } catch { /* invalid URL */ } |
| 31 | + return '.webp'; // default |
| 32 | +} |
| 33 | + |
| 34 | +export interface LogoEntry { |
| 35 | + slug: string; |
| 36 | + url: string; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Download logos for the given scripts to `public/logos/`. |
| 41 | + * Skips logos that already exist locally unless `force` is set. |
| 42 | + * Returns the number of newly downloaded logos. |
| 43 | + */ |
| 44 | +export async function cacheLogos( |
| 45 | + entries: LogoEntry[], |
| 46 | + options?: { force?: boolean; concurrency?: number } |
| 47 | +): Promise<{ downloaded: number; skipped: number; errors: number }> { |
| 48 | + ensureLogosDir(); |
| 49 | + |
| 50 | + const force = options?.force ?? false; |
| 51 | + const concurrency = options?.concurrency ?? 10; |
| 52 | + let downloaded = 0; |
| 53 | + let skipped = 0; |
| 54 | + let errors = 0; |
| 55 | + |
| 56 | + // Process in batches of `concurrency` |
| 57 | + for (let i = 0; i < entries.length; i += concurrency) { |
| 58 | + const batch = entries.slice(i, i + concurrency); |
| 59 | + const results = await Promise.allSettled( |
| 60 | + batch.map(async (entry) => { |
| 61 | + if (!entry.url) { |
| 62 | + skipped++; |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + const ext = getExtension(entry.url); |
| 67 | + const filename = `${entry.slug}${ext}`; |
| 68 | + const filepath = join(LOGOS_DIR, filename); |
| 69 | + |
| 70 | + if (!force && existsSync(filepath)) { |
| 71 | + skipped++; |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + const response = await fetch(entry.url, { |
| 76 | + signal: AbortSignal.timeout(10_000), |
| 77 | + }); |
| 78 | + if (!response.ok) { |
| 79 | + throw new Error(`HTTP ${response.status} for ${entry.url}`); |
| 80 | + } |
| 81 | + const buffer = Buffer.from(await response.arrayBuffer()); |
| 82 | + await writeFile(filepath, buffer); |
| 83 | + downloaded++; |
| 84 | + }), |
| 85 | + ); |
| 86 | + |
| 87 | + for (const r of results) { |
| 88 | + if (r.status === 'rejected') { |
| 89 | + errors++; |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + return { downloaded, skipped, errors }; |
| 95 | +} |
| 96 | + |
| 97 | +/** |
| 98 | + * Given a remote logo URL and a slug, return the local path if the logo |
| 99 | + * has been cached, otherwise return the original URL. |
| 100 | + */ |
| 101 | +export function getLocalLogoPath(slug: string, remoteUrl: string | null): string | null { |
| 102 | + if (!remoteUrl) return null; |
| 103 | + const ext = getExtension(remoteUrl); |
| 104 | + const filename = `${slug}${ext}`; |
| 105 | + const filepath = join(LOGOS_DIR, filename); |
| 106 | + if (existsSync(filepath)) { |
| 107 | + return `/logos/${filename}`; |
| 108 | + } |
| 109 | + return remoteUrl; |
| 110 | +} |
| 111 | + |
| 112 | +/** |
| 113 | + * Clean up logos for scripts that no longer exist. |
| 114 | + */ |
| 115 | +export async function cleanupOrphanedLogos(activeSlugs: Set<string>): Promise<number> { |
| 116 | + ensureLogosDir(); |
| 117 | + let removed = 0; |
| 118 | + try { |
| 119 | + const files = await readdir(LOGOS_DIR); |
| 120 | + for (const file of files) { |
| 121 | + const slug = file.replace(/\.[^.]+$/, ''); |
| 122 | + if (!activeSlugs.has(slug)) { |
| 123 | + await unlink(join(LOGOS_DIR, file)); |
| 124 | + removed++; |
| 125 | + } |
| 126 | + } |
| 127 | + } catch { /* directory may not exist yet */ } |
| 128 | + return removed; |
| 129 | +} |
0 commit comments