newsnow/scripts/favicon.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-10-01 00:08:07 +08:00
import fs from "node:fs"
import { fileURLToPath } from "node:url"
import { join } from "node:path"
2024-10-04 15:36:28 +08:00
import { Buffer } from "node:buffer"
2024-10-01 00:08:07 +08:00
import { getLogos } from "favicons-scraper"
2024-10-05 23:56:10 +08:00
import { consola } from "consola"
2024-10-08 20:49:19 +08:00
import { originSources } from "../shared/sources"
2024-10-01 00:08:07 +08:00
const projectDir = fileURLToPath(new URL("..", import.meta.url))
const iconsDir = join(projectDir, "public", "icons")
2024-10-04 15:36:28 +08:00
async function downloadImage(url: string, outputPath: string, id: string) {
2024-10-01 00:08:07 +08:00
try {
const response = await fetch(url)
if (!response.ok) {
2024-10-04 15:36:28 +08:00
throw new Error(`${id}: could not fetch ${url}, status: ${response.status}`)
2024-10-01 00:08:07 +08:00
}
2024-10-04 15:36:28 +08:00
const image = await (await fetch(url)).arrayBuffer()
fs.writeFileSync(outputPath, Buffer.from(image))
2024-10-05 23:56:10 +08:00
consola.success(`${id}: downloaded successfully.`)
2024-10-01 00:08:07 +08:00
} catch (error) {
2024-10-05 23:56:10 +08:00
consola.error(`${id}: error downloading the image. `, error)
2024-10-01 00:08:07 +08:00
}
}
async function main() {
await Promise.all(
2024-10-08 20:49:19 +08:00
Object.entries(originSources).map(async ([id, source]) => {
2024-10-01 00:08:07 +08:00
try {
2024-10-04 15:36:28 +08:00
const icon = join(iconsDir, `${id.split("-")[0]}.png`)
if (fs.existsSync(icon)) {
2024-10-05 23:56:10 +08:00
consola.info(`${id}: icon exists. skip.`)
2024-10-04 15:36:28 +08:00
return
}
2024-10-01 00:08:07 +08:00
if (!source.home) return
const res = await getLogos(source.home)
if (res.length) {
2024-10-04 15:36:28 +08:00
await downloadImage(res[0].src, icon, id)
2024-10-01 00:08:07 +08:00
}
} catch (e) {
2024-10-05 23:56:10 +08:00
consola.error(id, "\n", e)
2024-10-01 00:08:07 +08:00
}
}),
)
}
main()