← Files Sulekha EventsARCHIVED FILE

source/src/data/events.js

9.9 KB · Nov 30, 2026 · 07:53 UTC

↓ Download file

import { createHmac, randomUUID } from "node:crypto";

function getSearchUrl() {
  // API settings confirmed by the app owner. Keep these independent of
  // the MCP hosting domain; Azure environment variables may override them.
  const baseUrl = process.env.SULEKHA_EVENTS_WEB_BASE_URL?.trim()
    || "https://sulnriwebapps.azurewebsites.net/";
  const searchPath = process.env.SULEKHA_EVENTS_WEB_SEARCH_PATH?.trim()
    || "api/1.0/plugai/getsearchresultsnriai";
  return new URL(searchPath, baseUrl);
}

function optionalString(value) {
  if (value === undefined || value === null || value === "") return undefined;
  return String(value);
}

function optionalCoordinate(value) {
  if (value === undefined || value === null || value === "") return undefined;
  const number = Number(value);
  return Number.isFinite(number) ? number : undefined;
}

function optionalUrl(value) {
  const candidate = optionalString(value);
  if (!candidate) return undefined;
  try {
    const url = new URL(candidate);
    return url.protocol === "http:" || url.protocol === "https:" ? url.href : undefined;
  } catch {
    return undefined;
  }
}

const COUNTRY_REGIONS = {
  US: new Set("AL AK AZ AR CA CO CT DE DC FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY AS GU MP PR VI".split(" ")),
  CA: new Set("AB BC MB NB NL NS NT NU ON PE QC SK YT".split(" "))
};

const CITY_COORDINATES = {
  "san-jose-ca": [37.3738, -121.793],
  "new-york-ny": [40.7128, -74.006],
  "ny": [40.7128, -74.006],
  "new-york": [40.7128, -74.006]
};

function resolveCoordinates(cityUrl, latitude, longitude) {
  if (latitude !== undefined && longitude !== undefined) return { latitude, longitude };
  const key = String(cityUrl ?? "").trim().toLowerCase();
  const coordinates = CITY_COORDINATES[key];
  return coordinates ? { latitude: coordinates[0], longitude: coordinates[1] } : { latitude, longitude };
}

export function normalizeEvent(row) {
  const id = row?.eventid ?? row?.contentid;
  if (id === undefined || id === null) return null;

  return {
    id: String(id),
    title: optionalString(row.title ?? row.eventtitle) ?? "Untitled event",
    city: optionalString(row.cityname ?? row.city) ?? "",
    region: optionalString(row.statecode ?? row.state) ?? "",
    dateTime: optionalString(row.formateddate ?? row.eventdatetime) ?? "",
    startsAt: optionalString(row.eventdate),
    imageUrl: optionalUrl(row.eveimageurl) ?? optionalUrl(row.imageUrl) ?? optionalUrl(row.imageurl),
    price: optionalString(row.price),
    startPrice: optionalString(row.startprice),
    soldOut: row.soldout === 1 || row.soldout === "1" || row.soldout === true
      ? true : row.soldout === 0 || row.soldout === "0" || row.soldout === false ? false : undefined,
    status: optionalString(row.eventtrend),
    organizer: optionalString(row.hostedby),
    url: optionalUrl(row.trackurl ?? row.mapurl),
    latitude: optionalCoordinate(row.latitude),
    longitude: optionalCoordinate(row.longitude)
  };
}

function withinRadius(event, latitude, longitude, radius) {
  if (latitude === undefined || longitude === undefined) return true;
  if (event.latitude === undefined || event.longitude === undefined) return false;
  const radians = degrees => degrees * Math.PI / 180;
  const deltaLat = radians(event.latitude - latitude);
  const deltaLon = radians(event.longitude - longitude);
  const a = Math.sin(deltaLat / 2) ** 2
    + Math.cos(radians(latitude)) * Math.cos(radians(event.latitude)) * Math.sin(deltaLon / 2) ** 2;
  const miles = 3958.8 * 2 * Math.asin(Math.sqrt(Math.min(1, a)));
  return miles <= radius;
}

export async function searchEventResults(
  {
    query = "",
    rawQuery,
    cityUrl = "",
    stateCode,
    country = "US",
    latitude,
    longitude,
    distance = 50,
    limit = 10,
    omitLocation = false
  },
  { fetchImpl = fetch, platform = "unknown" } = {}
) {
  stateCode = stateCode?.trim().toUpperCase();
  if (!COUNTRY_REGIONS[country] || (stateCode && !COUNTRY_REGIONS[country].has(stateCode))) {
    throw Object.assign(new Error("Choose a state or province that matches the requested country (US or Canada)."), { code: "SEARCH_INVALID_LOCATION" });
  }
  ({ latitude, longitude } = resolveCoordinates(cityUrl, latitude, longitude));
  const url = getSearchUrl();
  const callback = "fncommonsearchsEventHeader";
  url.search = new URLSearchParams({
    rno: String(Math.random()), holderid: "txtuspopupsearch", type: "commonsearch",
    searchtxt: query, platform, callback, lat: latitude ?? "", long: longitude ?? "",
    radius: String(distance), perflat: latitude ?? "", perflong: longitude ?? "",
    meturl: "", cityurl: cityUrl, passingcityurl: cityUrl, srvtech: "Events"
  });

  if (omitLocation) {
    for (const key of ["lat", "long", "radius", "perflat", "perflong", "meturl", "cityurl", "passingcityurl"]) {
      url.searchParams.delete(key);
    }
  }

  // Preserve the original message independently of the extracted search keywords.
  // Older clients can omit it; do not manufacture an original message from query.
  if (rawQuery !== undefined) url.searchParams.set("rawQuery", rawQuery);

  const clientId = process.env.SearchApiAuth__ClientId;
  const secret = process.env.SearchApiAuth__Secret;
  if (!clientId?.trim() || !secret?.trim()) {
    throw Object.assign(new Error("Sulekha Events API authentication is not configured. Set SearchApiAuth__ClientId and SearchApiAuth__Secret."), { code: "SEARCH_AUTH_NOT_CONFIGURED" });
  }
  const timestamp = String(Math.floor(Date.now() / 1000));
  const nonce = randomUUID();
  // Sign the completed query using its exact wire encoding.
  const payload = [timestamp, nonce, "GET", url.pathname + url.search].join("\n");
  const signature = createHmac("sha256", secret).update(payload, "utf8").digest("hex");
  const response = await fetchImpl(url, {
    method: "GET",
    redirect: "error",
    headers: {
      accept: "application/javascript, application/json",
      "X-Client-Id": clientId,
      "X-Timestamp": timestamp,
      "X-Nonce": nonce,
      "X-Signature": signature
    },
    signal: AbortSignal.timeout(15_000)
  });

  if (!response.ok) {
    throw Object.assign(new Error(`Sulekha Events API returned HTTP ${response.status}.`), {
      code: [401, 403].includes(response.status) ? "SEARCH_AUTH_REJECTED" : "SEARCH_UPSTREAM_ERROR"
    });
  }

  const body = (await response.text()).trim().replace(/;$/, "").trimEnd();
  const prefix = callback + "(";
  const encoded = body.startsWith(prefix) && body.endsWith(")")
    ? body.slice(prefix.length, -1)
    : body;
  let rows;
  try {
    const payload = JSON.parse(encoded);
    rows = typeof payload === "string" ? JSON.parse(payload) : payload;
  } catch {
    throw new Error("Sulekha Events API returned an unexpected response.");
  }
  if (!Array.isArray(rows)) throw new Error("Sulekha Events API returned an unexpected response.");

  const eventsById = new Map();
  const events = rows
    .filter(row => {
      const kind = String(row?.search ?? "").trim().toLowerCase();
      // Explicit suggestion types must never be rescued by an event-like URL.
      return ["event", "hostedbyevent", "latlong"].includes(kind)
        || (!kind && /_event-in_/i.test(row?.mapurl ?? row?.trackurl ?? ""));
    })
    .map(normalizeEvent);
  for (const event of events) {
    if (!omitLocation && !COUNTRY_REGIONS[country].has(event?.region.trim().toUpperCase())) continue;
    if (stateCode && event?.region.trim().toUpperCase() !== stateCode) continue;
    if (!event || !withinRadius(event, latitude, longitude, distance)) continue;
    const existing = eventsById.get(event.id);
    if (!existing) {
      eventsById.set(event.id, event);
      continue;
    }
    // Search sections can repeat an event with different optional fields.
    // Preserve the first result's ordering, but don't discard later media/prices.
    for (const [key, value] of Object.entries(event)) {
      if ((existing[key] === undefined || existing[key] === "") && value !== undefined) {
        existing[key] = value;
      }
    }
  }
  const relatedByUrl = new Map();
  for (const row of rows) {
    const item = normalizeRelated(row);
    if (!item) continue;
    const existing = relatedByUrl.get(item.url);
    if (!existing) relatedByUrl.set(item.url, item);
    else {
      if (!existing.imageUrl && item.imageUrl) existing.imageUrl = item.imageUrl;
      if (existing.eventCount === undefined && item.eventCount !== undefined) existing.eventCount = item.eventCount;
    }
  }
  return { events: [...eventsById.values()].slice(0, limit), related: [...relatedByUrl.values()].slice(0, limit) };
}

// Retain the event-only interface for callers that do not render profiles.
export async function searchEvents(args, options) {
  return (await searchEventResults(args, options)).events;
}

export function normalizeRelated(row) {
  const source = String(row?.search ?? "").trim().toLowerCase();
  if (!["artist", "tour", "venue", "yoursearch"].includes(source) || String(row.isdisplay) === "0") return null;
  const value = optionalUrl(row.trackurl) ?? optionalUrl(row.mapurl);
  if (!value) return null;
  const url = new URL(value);
  if (url.origin !== "https://events.sulekha.com" || url.username || url.password) return null;
  // Search suggestions can link to profiles; their dates/locations are placeholders.
  const kind = source === "yoursearch"
    ? /_tickets_artist_/.test(url.pathname) ? "artist" : /(?:_tour_|_tickets_tour_|\/tour\/)/.test(url.pathname) ? "tour" : /_venue_/.test(url.pathname) ? "venue" : null
    : source;
  if (!kind || row.contentid == null) return null;
  const count = row.artisteventcount;
  return {
    id: String(row.contentid), kind, title: optionalString(row.title) ?? ({ artist: "Artist", tour: "Tour", venue: "Venue" }[kind]),
    imageUrl: optionalUrl(row.imageUrl) ?? optionalUrl(row.imageurl), url: url.href,
    ...(count !== undefined && count !== null && count !== "" && Number.isInteger(Number(count)) && Number(count) >= 0
      ? { eventCount: Number(count) } : {})
  };
}

SHA-256: 93a8392a5f38638873804809a7c21b49d6ae4307a117c815b6d4ba71607ca879