const months = [ "январ", "феврал", "март", "апрел", "ма", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр", ]; function russianDates(text) { const dates = []; for (const match of text.matchAll(/(\d{1,2})\s+([а-яё]+)\s+(20\d{2})/gi)) { const month = months.findIndex((prefix) => match[2].toLowerCase().startsWith(prefix), ); if (month >= 0) dates.push( `${match[3]}-${String(month + 1).padStart(2, "0")}-${match[1].padStart(2, "0")}`, ); } return dates; } function organizerUrl(value) { try { const url = new URL(value.replace(/&/g, "&")); if ( !["https:", "http:"].includes(url.protocol) || url.username || url.password || !/^[a-z0-9-]+(?:\.[a-z0-9-]+)+\.[a-z][a-z0-9-]*$|^[a-z0-9-]+\.[a-z][a-z0-9-]*$/i.test( url.hostname, ) ) return null; if (/\.(?:local|localhost|internal|test|invalid)$/i.test(url.hostname)) return null; return url.href; } catch { return null; } } // The Crocus index is an accordion of exhibition records. Its detail_theme links are topic filters. export function crocusCalendar(body, day, clean) { const blocks = body .split(/]*class=["']list-item["'][^>]*>/i) .slice(1); if (!blocks.length) throw Error("В календаре Крокус Экспо отсутствуют блоки выставок"); const rows = []; for (const block of blocks) { const label = block.match( /]*class=["']leftimg-exhibition-about["'][^>]*>([\s\S]*?)<\/p>/i, )?.[1]; if (!label) continue; const title = clean(label.match(/]*>([\s\S]*?)<\/span>/i)?.[1]); const dates = russianDates( clean(label.match(/]*>([\s\S]*?)<\/b>/i)?.[1]), ); if (!title || !dates.length || day < dates[0] || day > dates.at(-1)) continue; const address = block.match( /\s*Сайт:\s*<\/strong>\s*]*href\s*=\s*["']([^"']+)["']/i, )?.[1]; const url = address && organizerUrl(address); if (!url) continue; const description = clean(label.match(/]*>([\s\S]*?)<\/em>/i)?.[1]); const venue = clean( block.match( /Место проведения:\s*<\/b>[\s\S]{0,150}?
([\s\S]*?)<\/div>/i, )?.[1], ).slice(0, 230); rows.push({ url, title, event: true, calendar: true, ends: dates.at(-1), excerpt: `${title}. ${description}. Даты по календарю Крокус Экспо: ${dates.join(" — ")}. ${venue}`, }); } return rows.sort((a, b) => a.ends.localeCompare(b.ends)).slice(0, 8); } function dereference(nodes, pointer, depth = 0) { if (!Number.isInteger(pointer) || pointer < 0 || depth > 6) return null; const value = nodes[pointer]; if (Array.isArray(value)) return value.map((index) => dereference(nodes, index, depth + 1)); if (value && typeof value === "object") return Object.fromEntries( Object.entries(value).map(([key, index]) => [ key, dereference(nodes, index, depth + 1), ]), ); return value; } function activeEvent(schedule, day) { if (!schedule || schedule.show === false) return null; const weekday = new Date(day + "T12:00:00Z").getUTCDay(); const date = day.split("-").reverse().join("-"); const items = Array.isArray(schedule.items) ? schedule.items.filter(Boolean) : []; if (items.some((row) => row.type === 3 && row.date?.includes(date))) return null; if (items.some((row) => row.type === 2 && row.date?.includes(date))) return { end: day, text: `Отдельная дата проведения в расписании ВДНХ: ${day}.`, }; const start = String(schedule.action_start_date || "").slice(0, 10); const end = String(schedule.action_end_date || "").slice(0, 10); if (!start || !end || day < start || day > end) return null; const matchesWeekday = (row) => row.week_days?.includes(7) || row.week_days?.includes(weekday); if (items.some((row) => row.type === 3 && matchesWeekday(row))) return null; if ( items.length && !items.some((row) => row.type === 2 && matchesWeekday(row)) ) return null; return { end, text: `Период проведения по расписанию ВДНХ: ${start} — ${end}.`, }; } // The official Nuxt page serializes linked event records and their calendars as a flat pointer array. export function vdnhCalendar(body, day) { const json = body.match( /]*\bid=["']__NUXT_DATA__["'][^>]*>([\s\S]*?)<\/script>/i, )?.[1]; if (!json) throw Error("Не удалось прочитать календарь ВДНХ"); const nodes = JSON.parse(json); if (!Array.isArray(nodes)) throw Error("Неверный формат календаря ВДНХ"); let eventRecords = 0; const rows = new Map(); for (const record of nodes) { if ( !record || typeof record !== "object" || !( "eventThemes" in record && "schedule" in record && "url" in record && "name" in record ) ) continue; eventRecords++; const slug = nodes[record.url], title = nodes[record.name]; if ( typeof slug !== "string" || typeof title !== "string" || !/^[\w-]+$/.test(slug) || rows.has(slug) ) continue; const slot = activeEvent(dereference(nodes, record.schedule), day); if (slot) rows.set(slug, { title, url: `https://vdnh.ru/events/${slug}/`, excerpt: `${title}. ${slot.text}`, ends: slot.end, event: true, calendar: true, }); } if (!eventRecords) throw Error("В календаре ВДНХ отсутствуют записи событий"); return [...rows.values()] .sort((a, b) => a.ends.localeCompare(b.ends)) .slice(0, 8); } export function vdnhDetails(body, url, clean) { const json = body.match( /]*\bid=["']__NUXT_DATA__["'][^>]*>([\s\S]*?)<\/script>/i, )?.[1]; if (!json) return ""; const nodes = JSON.parse(json); const slug = new URL(url).pathname.split("/").filter(Boolean).at(-1); const record = nodes.find( (v) => v && typeof v === "object" && "constructors" in v && nodes[v.url] === slug, ); if (!record) return ""; const parts = []; for (const name of ["badges", "places"]) { for (const ref of nodes[record[name]] || []) { const text = nodes[nodes[ref]?.name]; if (typeof text === "string") parts.push(text); } } for (const ref of nodes[record.constructors] || []) { const content = nodes[nodes[ref]?.content]; for (const key of ["announcement", "description", "text"]) { const value = nodes[content?.[key]]; if (typeof value === "string" && value.trim()) parts.push(clean(value)); } } return parts.join(". ").slice(0, 4000); } export function organizerDetails(body, clean) { // External organizer pages vary in markup. Restrict evidence to short practical passages. const text = clean(body.replace(//g, " ")); const patterns = [ /возраст(?:ная категория|ное ограничение|ное ограничени[ея])|\b(?:0|6|12|16|18)\+/i, /(?:билет|билеты|стоимость|цена)[^.!?]{0,80}\d[\d\s\u00a0]*(?:₽|руб)/i, /(?:станци[яи]|метро)\s*«?[А-ЯЁ][а-яё]{3,}/, /\d+\s*(?:метров|минут)\s+(?:пешком|ходьбы)/i, ]; const result = []; for (const pattern of patterns) { const m = pattern.exec(text); if (m) result.push( text.slice(Math.max(0, m.index - 50), m.index + m[0].length + 110), ); } return result.join(" ... "); }