import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { UPLOADS_DIR } from '../db/database.js';
import type { AssetSourceType } from '@olokaflow/shared';
export interface ScrapedRawFile {
id: string;
name: string;
type: 'image' | 'svg' | 'video' | 'audio';
source: AssetSourceType;
sourceUrl: string;
relativePath: string;
publicUrl: string;
mimeType: string;
sizeBytes: number;
width: number;
height: number;
brandHint?: string;
pageTitle?: string;
}
export interface WebpageScrapeResult {
url: string;
pageTitle: string;
pageDescription: string;
visibleTextExcerpt: string;
extractedColors: string[];
brandNameHint: string;
files: ScrapedRawFile[];
}
export function extractUrlsFromPrompt(prompt: string): string[] {
if (!prompt) return [];
const regex = /https?:\/\/[^\s"'<>)\]]+/gi;
const matches = prompt.match(regex) || [];
return Array.from(new Set(matches.map((u) => u.replace(/[.,;!?]+$/, ''))));
}
/**
* Inspects Magic Bytes of a buffer to detect true file format and prevent HTML/corrupt image bugs.
*/
export function inspectBinaryMagicBytes(buf: Buffer): {
ext: string;
mimeType: string;
kind: 'image' | 'svg' | 'video' | 'audio' | 'html' | 'unknown';
width?: number;
height?: number;
} {
if (!buf || buf.length < 8) {
return { ext: '.bin', mimeType: 'application/octet-stream', kind: 'unknown' };
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
const width = buf.length >= 24 ? buf.readUInt32BE(16) : 1080;
const height = buf.length >= 24 ? buf.readUInt32BE(20) : 1080;
return { ext: '.png', mimeType: 'image/png', kind: 'image', width, height };
}
// JPEG: FF D8 FF
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
return { ext: '.jpg', mimeType: 'image/jpeg', kind: 'image', width: 1280, height: 720 };
}
// GIF: GIF87a or GIF89a
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) {
const width = buf.readUInt16LE(6);
const height = buf.readUInt16LE(8);
return { ext: '.gif', mimeType: 'image/gif', kind: 'image', width, height };
}
// WEBP: RIFF....WEBP
if (
buf.toString('ascii', 0, 4) === 'RIFF' &&
buf.toString('ascii', 8, 12) === 'WEBP'
) {
return { ext: '.webp', mimeType: 'image/webp', kind: 'image', width: 1280, height: 720 };
}
// MP4: ....ftyp
if (buf.toString('ascii', 4, 8) === 'ftyp') {
return { ext: '.mp4', mimeType: 'video/mp4', kind: 'video', width: 1920, height: 1080 };
}
// MP3: ID3 or FF FB
if (
buf.toString('ascii', 0, 3) === 'ID3' ||
(buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0)
) {
return { ext: '.mp3', mimeType: 'audio/mpeg', kind: 'audio' };
}
const headText = buf.subarray(0, 512).toString('utf8').trim().toLowerCase();
if (headText.startsWith(' {
try {
const resp = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
Accept: 'image/*,video/*,audio/*,*/*;q=0.8',
},
signal: AbortSignal.timeout(12000),
});
if (!resp.ok) return null;
const buf = Buffer.from(await resp.arrayBuffer());
if (buf.length < 256) return null; // Skip 1x1 tracking pixels
const magic = inspectBinaryMagicBytes(buf);
if (magic.kind === 'html' || magic.kind === 'unknown') {
return null;
}
const id = `ast-${crypto.randomUUID().slice(0, 8)}`;
const urlPathName = new URL(url).pathname.split('/').pop() || 'scraped-media';
const baseCleanName = urlPathName
.replace(/\.[a-z0-9]+$/i, '')
.replace(/[^a-zA-Z0-9_-]/g, '_')
.slice(0, 48);
const fileName = `${id}-${baseCleanName || 'asset'}${magic.ext}`;
const fullPath = path.join(UPLOADS_DIR, fileName);
fs.writeFileSync(fullPath, buf);
return {
id,
name: baseCleanName || fileName,
type: magic.kind,
source,
sourceUrl: url,
relativePath: `uploads/${fileName}`,
publicUrl: `/media/uploads/${fileName}`,
mimeType: magic.mimeType,
sizeBytes: buf.length,
width: magic.width || 1080,
height: magic.height || 1080,
brandHint,
};
} catch {
return null;
}
}
/**
* Scrapes a webpage URL for high-res images (og:image, twitter:image,
, SVG logos,