Spaces:
Sleeping

File size: 9,805 Bytes
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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('<!doctype html') || headText.startsWith('<html')) {
    return { ext: '.html', mimeType: 'text/html', kind: 'html' };
  }
  if (headText.includes('<svg')) {
    return { ext: '.svg', mimeType: 'image/svg+xml', kind: 'svg', width: 512, height: 512 };
  }

  return { ext: '.bin', mimeType: 'application/octet-stream', kind: 'unknown' };
}

export async function downloadAndValidateMediaUrl(
  url: string,
  source: AssetSourceType = 'prompt_scraped',
  brandHint = ''
): Promise<ScrapedRawFile | null> {
  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, <img>, SVG logos, <video>),
 * brand colors, and visible text copy.
 */
export async function scrapeWebpageUrl(url: string): Promise<WebpageScrapeResult | null> {
  try {
    // First check if the URL itself is a direct media file
    const directMedia = await downloadAndValidateMediaUrl(url, 'prompt_scraped');
    if (directMedia) {
      return {
        url,
        pageTitle: directMedia.name,
        pageDescription: '',
        visibleTextExcerpt: '',
        extractedColors: [],
        brandNameHint: '',
        files: [directMedia],
      };
    }

    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: 'text/html,application/xhtml+xml',
      },
      signal: AbortSignal.timeout(12000),
    });

    if (!resp.ok) return null;
    const html = await resp.text();
    const baseObj = new URL(url);

    const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
    const pageTitle = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim() : baseObj.hostname;

    const descMatch =
      html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) ||
      html.match(/<meta[^>]+property=["']og:description["'][^>]+content=["']([^"']+)["']/i);
    const pageDescription = descMatch ? descMatch[1].trim() : '';

    const siteNameMatch = html.match(
      /<meta[^>]+property=["']og:site_name["'][^>]+content=["']([^"']+)["']/i
    );
    const brandNameHint = siteNameMatch
      ? siteNameMatch[1].trim()
      : baseObj.hostname.replace(/^www\./, '').split('.')[0];

    // Extract Hex colors from HTML/CSS
    const hexMatches = html.match(/#[0-9a-fA-F]{6}\b/g) || [];
    const extractedColors = Array.from(new Set(hexMatches)).slice(0, 6);

    // Collect candidate image & video URLs
    const candidateMediaUrls: string[] = [];

    const ogImgMatches = html.matchAll(
      /<meta[^>]+(?:property|name)=["'](?:og:image|twitter:image)["'][^>]+content=["']([^"']+)["']/gi
    );
    for (const m of ogImgMatches) {
      if (m[1]) candidateMediaUrls.push(m[1]);
    }

    const imgMatches = html.matchAll(/<img[^>]+src=["']([^"']+)["'][^>]*>/gi);
    for (const m of imgMatches) {
      const src = m[1];
      if (!src || src.startsWith('data:')) continue;
      if (/pixel|tracker|analytics|1x1|blank\.gif/i.test(src)) continue;
      candidateMediaUrls.push(src);
    }

    const resolvedUrls = Array.from(
      new Set(
        candidateMediaUrls
          .map((u) => {
            try {
              return new URL(u, url).toString();
            } catch {
              return '';
            }
          })
          .filter(Boolean)
      )
    ).slice(0, 8);

    const downloadedFiles: ScrapedRawFile[] = [];
    for (const mediaUrl of resolvedUrls) {
      const file = await downloadAndValidateMediaUrl(
        mediaUrl,
        'prompt_scraped',
        brandNameHint
      );
      if (file) {
        file.pageTitle = pageTitle;
        downloadedFiles.push(file);
      }
      if (downloadedFiles.length >= 5) break;
    }

    // Extract clean visible text excerpt
    const visibleTextExcerpt = html
      .replace(/<script[\s\S]*?<\/script>/gi, ' ')
      .replace(/<style[\s\S]*?<\/style>/gi, ' ')
      .replace(/<[^>]+>/g, ' ')
      .replace(/\s+/g, ' ')
      .trim()
      .slice(0, 1200);

    return {
      url,
      pageTitle,
      pageDescription,
      visibleTextExcerpt,
      extractedColors,
      brandNameHint,
      files: downloadedFiles,
    };
  } catch {
    return null;
  }
}

/**
 * Searches Wikimedia Commons open media API for fallback real-world reference images.
 */
export async function searchWebFallbackImages(
  query: string,
  limit = 2
): Promise<ScrapedRawFile[]> {
  try {
    const cleanQuery = query.trim();
    if (!cleanQuery) return [];

    const apiUrl = `https://commons.wikimedia.org/w/api.php?action=query&generator=search&gsrsearch=${encodeURIComponent(
      `filetype:bitmap ${cleanQuery}`
    )}&gsrlimit=${limit + 2}&prop=imageinfo&iiprop=url|dimensions|mime&iiurlwidth=1280&format=json&origin=*`;

    const resp = await fetch(apiUrl, { signal: AbortSignal.timeout(8000) });
    if (!resp.ok) return [];
    const data = (await resp.json()) as any;
    const pages = data?.query?.pages ? Object.values(data.query.pages) : [];

    const results: ScrapedRawFile[] = [];
    for (const p of pages as any[]) {
      const info = p?.imageinfo?.[0];
      const thumbUrl = info?.thumburl || info?.url;
      if (!thumbUrl) continue;
      const downloaded = await downloadAndValidateMediaUrl(thumbUrl, 'web_fallback');
      if (downloaded) {
        results.push(downloaded);
      }
      if (results.length >= limit) break;
    }
    return results;
  } catch {
    return [];
  }
}