import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import { JSDOM } from "jsdom"; import TempFileService from "../../storage/TempFileService.js"; import { parse } from "path"; const parseSizes = (size: string) => { if (!size) { return null; } const tokens = size.split("x").map((x) => Number(x)); if (!tokens.length) { return null; } return { width: tokens[0], height: tokens.pop() }; }; export interface IFavicon { src: string; type: string; name: string; size?: { width: number; height: number; } } @RegisterScoped export default class FaviconScrapperService { @Inject tempFileService: TempFileService; async downloadIcon(domainName: string) { const { base, icons } = await this.downloadIcons(domainName); if (!icons.length) { return await this.download(base,"/apple-touch-icon.png", domainName) ?? await this.download(base, "/favicon.ico", domainName); } const icon = icons[0]; const tf = await this.tempFileService.download(icon.src, icon.name); return tf; } async download(base, path, name) { try { const url = new URL(path, base); try { return await this.tempFileService.download(url.toString(), name); } catch (e) { console.error(`Failed to download ${url}`); return null; } } catch (ex) { console.error(`Failed to download ${base} with ${path}`); } } async downloadIcons(domainName: string) { // parse index... without javascript const { window } = await JSDOM.fromURL(`https://${domainName}`, {}); const base = window.document.baseURI; const icons = [] as IFavicon[]; for (const iterator of window.document.querySelectorAll("link")) { const type = iterator.getAttribute("type"); switch(type) { case "icon": case "shortcut icon": case "apple-touch-icon": const href = iterator.getAttribute("href"); if (href) { const size = parseSizes(iterator.getAttribute("sizes")) ?? parseSizes(iterator.getAttribute("size")); const url = new URL(base, href); const src = url.toString(); const names = parse(url.pathname); icons.push({ type, size, name: "favicon" + names.ext, src }); } break; } } icons.sort((a, b) => b.size?.height - a.size?.height); return { base, icons }; } }