| 1 | // Navegación: fetch directo si el sitio lo permite (CORS); si no, cae al |
| 2 | // proxy del servidor (/proxy?url=…) que sirve server/serve.py o el nginx |
| 3 | // de producción. |
| 4 | // |
| 5 | // Cada herramienta recibe la señal de parada del turno ({ signal }, ver |
| 6 | // tools/index.js): con ■, la descarga en curso se corta en vez de seguir por |
| 7 | // detrás hasta el final. |
| 8 | import { require as requirePerm } from '../permissions.js'; |
| 9 | import { t } from '../i18n.js'; |
| 10 | |
| 11 | const MAX = 8000; // caracteres devueltos al agente |
| 12 | |
| 13 | function toText(html) { |
| 14 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 15 | doc.querySelectorAll('script,style,noscript,svg,iframe').forEach(n => n.remove()); |
| 16 | const text = (doc.body?.innerText || doc.body?.textContent || '') |
| 17 | .replace(/\n{3,}/g, '\n\n').trim(); |
| 18 | return text || html.slice(0, MAX); |
| 19 | } |
| 20 | |
| 21 | const parado = (e, signal) => signal?.aborted || e?.name === 'AbortError'; |
| 22 | const hostDe = url => { try { return new URL(url).host; } catch { return url; } }; |
| 23 | |
| 24 | // Lee una URL: directa si el sitio permite CORS y, si no, por el proxy del |
| 25 | // servidor. Cuando las dos fallan, el error dice POR QUÉ. En especial si el |
| 26 | // proxy no existe en este servidor (404): antes salía «HTTP 404» a secas, que |
| 27 | // se lee como «esa página no existe», y la búsqueda lo convertía en «Sin |
| 28 | // resultados», como si internet no tuviera nada que decir. Así estuvo |
| 29 | // producción semanas sin que nadie lo notara. |
| 30 | // |
| 31 | // Y sin decir más de lo que se sabe. Si el sitio contestó al fetch directo (con |
| 32 | // CORS el navegador deja ver su estado), lo que importa es lo que dijo: su 404 |
| 33 | // es que la página no existe, haya proxy o no. Si el fetch directo falló sin |
| 34 | // respuesta, desde el navegador no se distingue un sitio sin CORS de uno que no |
| 35 | // existe o no resuelve: se dicen las dos cosas y no se afirma que la página |
| 36 | // exista. (Lo mismo que la copia de Elffuss Code.) |
| 37 | async function proxyGet(url, { signal } = {}) { |
| 38 | let directo, estado = 0; |
| 39 | try { |
| 40 | const r = await fetch(url, { signal }); |
| 41 | if (r.ok) return await r.text(); |
| 42 | estado = r.status; directo = new Error('HTTP ' + r.status); |
| 43 | } catch (e) { |
| 44 | if (parado(e, signal)) throw e; // ■: no se prueba el proxy |
| 45 | directo = e; |
| 46 | } |
| 47 | if (estado === 404 || estado === 410) throw new Error(t('webGone', { url, status: estado })); |
| 48 | let r; |
| 49 | try { r = await fetch('/proxy?url=' + encodeURIComponent(url), { signal }); } |
| 50 | catch (e) { |
| 51 | if (parado(e, signal)) throw e; |
| 52 | throw new Error(t('webBoth', { host: hostDe(url), direct: directo?.message || t('webNoAnswer'), proxy: e?.message || t('webNoAnswer') })); |
| 53 | } |
| 54 | if (r.ok) return await r.text(); |
| 55 | if (r.status === 404 || r.status === 405 || r.status === 501) { |
| 56 | const e = new Error(estado |
| 57 | ? t('webNoProxyStatus', { host: hostDe(url), status: estado, proxy: r.status }) |
| 58 | : t('webNoProxy', { host: hostDe(url), proxy: r.status })); |
| 59 | e.sinProxy = true; |
| 60 | throw e; |
| 61 | } |
| 62 | throw new Error(t('webBoth', { host: hostDe(url), direct: directo?.message || t('webNoAnswer'), proxy: 'HTTP ' + r.status })); |
| 63 | } |
| 64 | |
| 65 | export async function fetchUrl({ url } = {}, { signal } = {}) { |
| 66 | if (!/^https?:\/\//.test(url || '')) throw new Error(t('webBadUrl')); |
| 67 | await requirePerm('web', url); |
| 68 | const text = toText(await proxyGet(url, { signal })); |
| 69 | return `[${url}]\n` + (text.length > MAX ? text.slice(0, MAX) + '\n' + t('webCut') : text); |
| 70 | } |
| 71 | |
| 72 | // Búsqueda web REAL. Parseo TOLERANTE (independiente de clases): DuckDuckGo |
| 73 | // envuelve cada resultado en un enlace con ?uddg=<url real>. Buscamos esos. |
| 74 | // Si ningún buscador contesta se dice por qué, en vez de «Sin resultados» (que |
| 75 | // solo vale cuando el buscador SÍ contestó y no encontró nada). Y la página de |
| 76 | // verificación anti-bot de DuckDuckGo no es una lista vacía: es un bloqueo. |
| 77 | const BLOQUEO_DDG = /anomaly|unusual traffic|are you a human|bots use duckduckgo/i; |
| 78 | export async function search({ query } = {}, { signal } = {}) { |
| 79 | if (!query) throw new Error(t('webNoQuery')); |
| 80 | await requirePerm('web', t('pdWebSearch', { q: query })); |
| 81 | let html = '', ultimoError = null, bloqueado = false; |
| 82 | for (const ep of ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q=']) { |
| 83 | try { |
| 84 | const h = await proxyGet(ep + encodeURIComponent(query), { signal }); |
| 85 | if (!h.includes('uddg=') && BLOQUEO_DDG.test(h)) { bloqueado = true; continue; } |
| 86 | html = h; |
| 87 | if (html.includes('uddg=') || html.includes('result')) break; |
| 88 | } catch (e) { |
| 89 | if (parado(e, signal)) throw e; |
| 90 | ultimoError = e; |
| 91 | } |
| 92 | } |
| 93 | if (!html) { |
| 94 | if (bloqueado) throw new Error(t('webSearchBlocked', { q: query })); |
| 95 | throw ultimoError || new Error(t('webSearchFailed', { q: query })); |
| 96 | } |
| 97 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 98 | const seen = new Set(), out = []; |
| 99 | for (const a of doc.querySelectorAll('a[href*="uddg="]')) { |
| 100 | const m = a.getAttribute('href').match(/uddg=([^&]+)/); |
| 101 | if (!m) continue; |
| 102 | const href = decodeURIComponent(m[1]); |
| 103 | const title = a.textContent.trim(); |
| 104 | if (!title || title.length < 3 || seen.has(href)) continue; |
| 105 | seen.add(href); |
| 106 | // fragmento: el texto del contenedor del resultado, sin el título |
| 107 | const block = a.closest('tr, div, article') || a.parentElement; |
| 108 | const snip = (block?.textContent || '').replace(title, '').replace(/\s+/g, ' ').trim().slice(0, 160); |
| 109 | out.push(`• ${title}\n ${href}${snip ? '\n ' + snip : ''}`); |
| 110 | if (out.length >= 8) break; |
| 111 | } |
| 112 | return out.length ? t('webResults', { q: query }) + '\n\n' + out.join('\n\n') : t('webNoResults', { q: query }); |
| 113 | } |
| 114 | |
| 115 | // Búsqueda de IMÁGENES (Openverse, CC) → URLs para montar una galería. |
| 116 | export async function images({ query } = {}, { signal } = {}) { |
| 117 | if (!query) throw new Error(t('webNoQuery')); |
| 118 | await requirePerm('web', t('pdWebImages', { q: query })); |
| 119 | const raw = await proxyGet('https://api.openverse.org/v1/images/?q=' + encodeURIComponent(query) + '&page_size=12', { signal }); |
| 120 | let data; |
| 121 | try { data = JSON.parse(raw); } catch { throw new Error(t('webImagesBad')); } |
| 122 | const imgs = (data.results || []).map(r => ({ url: r.url, thumb: r.thumbnail || r.url, title: (r.title || '').slice(0, 60), by: r.creator || '' })) |
| 123 | .filter(i => i.url); |
| 124 | if (!imgs.length) return t('webNoImages', { q: query }); |
| 125 | return JSON.stringify({ query, images: imgs }); |
| 126 | } |