73 lines
3.7 KiB
JavaScript
73 lines
3.7 KiB
JavaScript
/* Афиша Visit Astana: извлекаем только опубликованные события и их даты. */
|
||
const SOURCE = "https://visitastana.kz/ru/about-city/where-to-go/";
|
||
let cache = null;
|
||
let pending = null;
|
||
function stripHtml(value) {
|
||
const entities = {"&":"&",""":'"',"'":"'","«":"«","»":"»"," ":" "};
|
||
return String(value||"").replace(/<[^>]+>/g," ").replace(/&(amp|quot|#039|laquo|raquo|nbsp);/g,x=>entities[x]).replace(/&#(\d+);/g,(_,n)=>String.fromCharCode(Number(n))).replace(/\s+/g," ").trim();
|
||
}
|
||
function iso(value) {
|
||
const [day,month,year] = value.split(".");
|
||
return `${year}-${month}-${day}`;
|
||
}
|
||
function dateKey(date = new Date()) {
|
||
const parts = new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Almaty",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(date);
|
||
const get = type => parts.find(x=>x.type===type).value;
|
||
return `${get("year")}-${get("month")}-${get("day")}`;
|
||
}
|
||
function parseEvents(html) {
|
||
const events = [];
|
||
for (const block of html.split('<div class="upcoming">').slice(1)) {
|
||
const title = block.match(/<h5 class="upcoming__title">([\s\S]*?)<\/h5>/);
|
||
const dates = block.match(/upcoming__date">\s*(\d{2}\.\d{2}\.\d{4})\s*-\s*(\d{2}\.\d{2}\.\d{4})/);
|
||
const link = block.match(/<a href="([^"]+)" class="upcoming__buy"/);
|
||
const address = block.match(/<div class="upcoming__address">([\s\S]*?)<\/div>/);
|
||
if (!title || !dates || !link) continue;
|
||
const event = {
|
||
id:events.length+1,title:stripHtml(title[1]),start:iso(dates[1]),end:iso(dates[2]),
|
||
dateLabel:`${dates[1]}–${dates[2]}`,address:stripHtml(address && address[1]),
|
||
url:link[1].replace(/&/g,"&"),source:"Visit Astana"
|
||
};
|
||
if (!events.some(x=>x.title===event.title && x.start===event.start)) events.push(event);
|
||
}
|
||
if (!events.length) throw new Error("Афиша получена, но события не распознаны");
|
||
return events;
|
||
}
|
||
async function updateEvents() {
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(()=>controller.abort(),18000);
|
||
let response;
|
||
try {
|
||
response = await fetch(SOURCE+"?start="+dateKey(),{signal:controller.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; AuadaPersonalApp/1.0)"}});
|
||
} finally { clearTimeout(timer); }
|
||
if (!response.ok) throw new Error("Visit Astana HTTP "+response.status);
|
||
const events = parseEvents(await response.text());
|
||
cache = {events,fetchedAt:new Date().toISOString(),time:Date.now(),live:true,stale:false};
|
||
return cache;
|
||
}
|
||
async function getEvents() {
|
||
if (cache && Date.now()-cache.time < 60*60*1000) return cache;
|
||
if (pending) return pending;
|
||
pending = updateEvents();
|
||
try { return await pending; }
|
||
catch (error) {
|
||
if (cache) return {...cache,live:false,stale:true};
|
||
throw error;
|
||
} finally { pending = null; }
|
||
}
|
||
function activeEvents(events,date) {
|
||
return events.filter(x=>x.start<=date && x.end>=date);
|
||
}
|
||
function chooseEvening(events,weather,date) {
|
||
const todays = activeEvents(events,date);
|
||
const dayIndex = Math.floor(new Date(date+"T12:00:00Z").getTime()/86400000);
|
||
const weatherKind = weather.aqi !== null && weather.aqi > 40 ? "air" : weather.temp <= 0 || weather.feels <= -3 ? "cold" : weather.wind >= 12 ? "wind" : "mild";
|
||
if (todays.length && dayIndex%2===0) {
|
||
const event = todays[Math.floor(dayIndex/2)%todays.length];
|
||
return {kind:"event",event,weatherKind,date,source:"Visit Astana"};
|
||
}
|
||
const warmIds = weatherKind === "air" ? [2,0,4,6] : weatherKind === "cold" ? [0,1,2,6] : [3,4,5,6,0,1,2];
|
||
return {kind:"home",homeId:warmIds[dayIndex%warmIds.length],weatherKind,date};
|
||
}
|
||
module.exports = {getEvents,parseEvents,activeEvents,chooseEvening,dateKey,SOURCE};
|