Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285import dns from 'node:dns/promises'import net from 'node:net'import { env } from '../env.ts'import { TtlCache, getProfile, getRecord, isDid } from '../atproto/identity.ts'
const UA = 'superbot (Streamplace chat bot)'
function isPrivateIp(ip: string): boolean { if (net.isIPv4(ip)) { const [a, b] = ip.split('.').map(Number) return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224 } const v = ip.toLowerCase() return v === '::1' || v === '::' || v.startsWith('fc') || v.startsWith('fd') || v.startsWith('fe80') || v.startsWith('::ffff:127.') || v.startsWith('::ffff:10.') || v.startsWith('::ffff:192.168.')}
/** Reject URLs that point at this machine or a private network (SSRF guard for $(customapi) and !filesay). */export async function assertPublicUrl(raw: string): Promise<URL> { let url: URL try { url = new URL(raw) } catch { throw new Error('Invalid URL.') } if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('Only http and https URLs are allowed.') const host = url.hostname.replace(/^\[|\]$/g, '') const addrs = net.isIP(host) ? [host] : (await dns.lookup(host, { all: true })).map((a) => a.address) if (!addrs.length || addrs.some(isPrivateIp)) throw new Error('That address is not allowed.') return url}
/** GET a public URL as text, following up to 3 redirects, capped in size and time. */export async function fetchPublicText(raw: string, maxChars = 400, timeoutMs = 5000): Promise<string> { let url = await assertPublicUrl(raw) for (let hop = 0; hop < 4; hop++) { const res = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(timeoutMs), headers: { 'user-agent': UA, accept: 'text/plain, */*' } }) if (res.status >= 300 && res.status < 400 && res.headers.get('location')) { url = await assertPublicUrl(new URL(res.headers.get('location')!, url).toString()) continue } const reader = res.body?.getReader() if (!reader) return '' const decoder = new TextDecoder() let text = '' while (text.length < maxChars * 4) { const { done, value } = await reader.read() if (done) break text += decoder.decode(value, { stream: true }) } reader.cancel().catch(() => {}) return text.trim().slice(0, maxChars) } throw new Error('Too many redirects.')}
async function getJson<T>(url: string, init: RequestInit = {}): Promise<T> { const res = await fetch(url, { ...init, signal: AbortSignal.timeout(6000), headers: { 'user-agent': UA, accept: 'application/json', ...(init.headers ?? {}) } }) if (!res.ok) throw new Error(`Request failed with ${res.status}`) return (await res.json()) as T}
const lastfmCache = new TtlCache<{ artist: string; track: string } | null>(20_000)export async function lastfmNowPlaying(user: string): Promise<{ artist: string; track: string } | null> { if (!env.lastfmApiKey) throw new Error('Last.fm is not configured on this server.') return lastfmCache.getOrLoad(user.toLowerCase(), async () => { const data = await getJson<{ recenttracks?: { track?: { name: string; artist: { '#text': string }; '@attr'?: { nowplaying?: string } }[] } }>( `https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${encodeURIComponent(user)}&api_key=${env.lastfmApiKey}&format=json&limit=1`, ) const t = data.recenttracks?.track?.[0] if (!t || t['@attr']?.nowplaying !== 'true') return null return { artist: t.artist['#text'], track: t.name } })}
export interface TealStatus { time?: string expiry?: string item?: { trackName?: string; artists?: { artistName?: string }[]; releaseName?: string; originUrl?: string }}
/** What a teal.fm status record says is playing: nothing once it has expired or the track is blank. */export function nowPlayingFromStatus(status: TealStatus | undefined, now = Date.now()): { artist: string; track: string } | null { const item = status?.item if (!item?.trackName) return null if (status?.expiry && Date.parse(status.expiry) < now) return null const artist = (item.artists ?? []).map((a) => a.artistName).filter(Boolean).join(', ') return { artist: artist || 'Unknown artist', track: item.trackName }}
const TEAL_STATUS_COLLECTIONS = ['fm.teal.actor.status', 'fm.teal.alpha.actor.status']const tealCache = new TtlCache<{ artist: string; track: string } | null>(20_000)
/** Now playing from teal.fm, read straight from the listener's repo. No API key needed. */export async function tealfmNowPlaying(actor: string): Promise<{ artist: string; track: string } | null> { const key = actor.trim().replace(/^@/, '').toLowerCase() return tealCache.getOrLoad(key, async () => { const did = isDid(key) ? key : (await getProfile(key))?.did if (!did) throw new Error('teal.fm user not found.') // Clients write either the current or the older alpha collection; use whichever is newer. const records = await Promise.all(TEAL_STATUS_COLLECTIONS.map((c) => getRecord<TealStatus>(`at://${did}/${c}/self`))) const latest = records .filter((r): r is NonNullable<typeof r> => r !== null) .sort((a, b) => (Date.parse(b.value.time ?? '') || 0) - (Date.parse(a.value.time ?? '') || 0))[0] return nowPlayingFromStatus(latest?.value) })}
const WEATHER_CODES: Record<number, string> = { 0: 'clear sky ☀️', 1: 'mainly clear 🌤️', 2: 'partly cloudy ⛅', 3: 'overcast ☁️', 45: 'fog 🌫️', 48: 'freezing fog 🌫️', 51: 'light drizzle 🌦️', 53: 'drizzle 🌦️', 55: 'heavy drizzle 🌧️', 61: 'light rain 🌧️', 63: 'rain 🌧️', 65: 'heavy rain 🌧️', 66: 'freezing rain 🧊', 67: 'freezing rain 🧊', 71: 'light snow 🌨️', 73: 'snow 🌨️', 75: 'heavy snow ❄️', 77: 'snow grains ❄️', 80: 'rain showers 🌦️', 81: 'rain showers 🌧️', 82: 'violent rain showers ⛈️', 85: 'snow showers 🌨️', 86: 'heavy snow showers ❄️', 95: 'thunderstorm ⛈️', 96: 'thunderstorm with hail ⛈️', 99: 'thunderstorm with hail ⛈️',}
/** Current weather via Open-Meteo (no API key needed). */export async function weather(location: string): Promise<string> { const geo = await getJson<{ results?: { name: string; country?: string; latitude: number; longitude: number }[] }>( `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(location)}&count=1`, ) const place = geo.results?.[0] if (!place) return `[Error: Couldn’t find “${location}”.]` const w = await getJson<{ current: { temperature_2m: number; weather_code: number; wind_speed_10m: number; relative_humidity_2m: number } }>( `https://api.open-meteo.com/v1/forecast?latitude=${place.latitude}&longitude=${place.longitude}¤t=temperature_2m,weather_code,wind_speed_10m,relative_humidity_2m`, ) const c = w.current const f = Math.round(c.temperature_2m * 1.8 + 32) return `${place.name}${place.country ? `, ${place.country}` : ''}: ${WEATHER_CODES[c.weather_code] ?? 'unknown conditions'}, ${Math.round(c.temperature_2m)}°C (${f}°F), humidity ${c.relative_humidity_2m}%, wind ${Math.round(c.wind_speed_10m)} km/h`}
export async function dadJoke(): Promise<string> { const res = await fetch('https://icanhazdadjoke.com/', { headers: { accept: 'text/plain', 'user-agent': UA }, signal: AbortSignal.timeout(5000) }) return (await res.text()).trim()}
export async function randomFact(): Promise<string> { const data = await getJson<{ text: string }>('https://uselessfacts.jsph.pl/api/v2/facts/random?language=en') return data.text.trim()}
export async function dictionary(word: string): Promise<string> { try { const data = await getJson<{ word: string; meanings: { partOfSpeech: string; definitions: { definition: string }[] }[] }[]>( `https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`, ) const m = data[0]?.meanings[0] if (!m) return `No definition found for “${word}”.` return `(${m.partOfSpeech}) ${data[0].word}: ${m.definitions[0].definition}` } catch { return `No definition found for “${word}”.` }}
export async function urbanDictionary(term: string): Promise<string> { const data = await getJson<{ list: { word: string; definition: string }[] }>(`https://api.urbandictionary.com/v0/define?term=${encodeURIComponent(term)}`) const top = data.list[0] if (!top) return `No Urban Dictionary definition for “${term}”.` return `${top.word}: ${top.definition.replace(/[[\]]/g, '').replace(/\s+/g, ' ').slice(0, 250)}`}
// --- media request lookups ---------------------------------------------------
export interface MediaInfo { provider: 'youtube' | 'soundcloud' mediaId: string url: string title: string author: string duration: number | null thumbnail: string}
export function parseYouTubeId(input: string): string | null { const m = /(?:youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)|youtu\.be\/|music\.youtube\.com\/watch\?(?:.*&)?v=)([\w-]{11})/i.exec(input) if (m) return m[1] return /^[\w-]{11}$/.test(input) ? input : null}
function isoDuration(iso: string): number { const m = /PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/.exec(iso) return m ? Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0) : 0}
async function youtubeById(id: string): Promise<MediaInfo | null> { if (env.youtubeApiKey) { const data = await getJson<{ items: { snippet: { title: string; channelTitle: string; thumbnails: { medium?: { url: string } } }; contentDetails: { duration: string }; status: { embeddable: boolean } }[] }>( `https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,status&id=${id}&key=${env.youtubeApiKey}`, ) const v = data.items[0] if (!v || !v.status.embeddable) return null return { provider: 'youtube', mediaId: id, url: `https://www.youtube.com/watch?v=${id}`, title: v.snippet.title, author: v.snippet.channelTitle, duration: isoDuration(v.contentDetails.duration), thumbnail: v.snippet.thumbnails.medium?.url ?? `https://i.ytimg.com/vi/${id}/mqdefault.jpg`, } } try { const o = await getJson<{ title: string; author_name: string }>(`https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(`https://www.youtube.com/watch?v=${id}`)}`) return { provider: 'youtube', mediaId: id, url: `https://www.youtube.com/watch?v=${id}`, title: o.title, author: o.author_name, duration: null, thumbnail: `https://i.ytimg.com/vi/${id}/mqdefault.jpg` } } catch { return null }}
async function youtubeSearch(q: string): Promise<MediaInfo | null> { if (!env.youtubeApiKey) return null const data = await getJson<{ items: { id: { videoId: string } }[] }>( `https://www.googleapis.com/youtube/v3/search?part=id&type=video&videoEmbeddable=true&maxResults=1&q=${encodeURIComponent(q)}&key=${env.youtubeApiKey}`, ) const id = data.items[0]?.id.videoId return id ? youtubeById(id) : null}
async function soundcloud(url: string): Promise<MediaInfo | null> { try { const o = await getJson<{ title: string; author_name: string; thumbnail_url?: string }>(`https://soundcloud.com/oembed?format=json&url=${encodeURIComponent(url)}`) const clean = url.split('?')[0] return { provider: 'soundcloud', mediaId: clean, url: clean, title: o.title, author: o.author_name, duration: null, thumbnail: o.thumbnail_url ?? '' } } catch { return null }}
/** Resolve a !sr argument (a URL or search text) to playable media. */export async function lookupMedia(input: string, providers: string[]): Promise<MediaInfo | null> { const trimmed = input.trim() if (/soundcloud\.com\//i.test(trimmed)) return providers.includes('soundcloud') ? soundcloud(trimmed) : null if (!providers.includes('youtube')) return null const id = parseYouTubeId(trimmed) if (id) return youtubeById(id) if (/^https?:\/\//i.test(trimmed)) return null return youtubeSearch(trimmed)}
export const canSearchYouTube = () => !!env.youtubeApiKey
// --- malware hosts -----------------------------------------------------------
let malwareHosts = new Set<string>()let malwareLoadedAt = 0
/** Known-malicious hostnames from URLhaus, refreshed every 6 hours. */export function getMalwareHosts(): ReadonlySet<string> { if (Date.now() - malwareLoadedAt > 6 * 3600_000) { malwareLoadedAt = Date.now() fetch('https://urlhaus.abuse.ch/downloads/hostfile/', { signal: AbortSignal.timeout(30_000), headers: { 'user-agent': UA } }) .then((r) => r.text()) .then((text) => { const next = new Set<string>() for (const line of text.split('\n')) { const host = line.trim().split(/\s+/)[1] if (host && !line.startsWith('#')) next.add(host.toLowerCase()) } if (next.size) malwareHosts = next }) .catch((err) => console.warn('[malware] could not refresh URLhaus list:', err.message)) } return malwareHosts}