view src/scheduleLcd.ts @ 5:d97a5930db7e

closer
author drewp@bigasterisk.com
date Wed, 06 Mar 2024 16:38:58 -0800
parents e273cc60b389
children affb3c8f3f58
line wrap: on
line source

import { addHours, endOfToday, endOfTomorrow, format, isAfter, isBefore, isToday, isTomorrow, isWithinInterval, parseISO, startOfToday } from "date-fns";
import { css, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators.js";
import { sortBy } from "lodash";
import { DataFactory, NamedNode, Parser, Quad_Predicate, Quad_Subject, Store, Term } from "n3";
import { hideFeeds, hideTitles } from "./private";
import { shared } from "./shared";
const { namedNode } = DataFactory;
export { WeekGuide } from "./WeekGuide";
const EV = "http://bigasterisk.com/event#";
const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

function updateTime() {
  document.querySelector("#time").innerText = new Date().toTimeString().slice(0, 8);
}
setInterval(updateTime, 1000)
updateTime()

// Function to send a POST request
function sendPostRequest(data) {
  fetch('https://example.com/api', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('POST request successful');
    // Handle response data if needed
  })
  .catch(error => {
    console.error('There was a problem with the POST request:', error);
  });
}

// Callback function to handle DOM changes
function handleDomChanges(mutationsList, observer) {
  // Send a POST request whenever the DOM changes
  sendPostRequest({ domChanges: mutationsList });
}

// Create a MutationObserver instance
const observer = new MutationObserver(handleDomChanges);

// Start observing the DOM for changes
observer.observe(document.body, { subtree: true, childList: true, attributes: true });


function getLiteral(store: Store, graph: Term, subj: Quad_Subject, pred: Quad_Predicate, missing: string | null): string {
  let out = null;
  store.getObjects(subj, pred, graph).forEach((attr) => {
    out = attr.value;
  });
  if (!out) {
    if (missing === null) {
      throw new Error();
    }
    return missing;
  }
  return out;
}

class DisplayEvent {
  constructor(private store: Store, private graph: Term, public uri: Quad_Subject) {}
  get title(): string {
    return getLiteral(this.store, this.graph, this.uri, namedNode(EV + "title"), "(unnamed)");
  }
  get start(): string {
    return getLiteral(this.store, this.graph, this.uri, namedNode(EV + "start"), null);
  }
  get feed(): NamedNode {
    return namedNode(getLiteral(this.store, this.graph, this.uri, namedNode(EV + "feed"), null));
  }
  shortDate(): TemplateResult {
    const t = parseISO(this.start);
    return html`<span class="d">${format(t, "EEE, MMM d,")}</span> <span class="t">${format(t, "HH:mm")}</span>`;
  }
  show(): boolean {
    const now = new Date();
    const t = parseISO(this.start);

    const start = startOfToday();
    let end = endOfToday();
    if (isAfter(now, addHours(startOfToday(), 18))) {
      end = endOfTomorrow();
    }

    return isWithinInterval(t, { start, end }) && !hideTitles.has(this.title) && !hideFeeds.has(this.feed.value);
  }
  toHtml(): TemplateResult {
    return html`
      <li>
        <span class="date">${this.shortDate()}</span> ${this.title}
        <!--${this.feed}-->
      </li>
    `;
  }
}

@customElement("fd-upcoming-events")
export class UpcomingEvents extends LitElement {
  @property() evs: DisplayEvent[];
  constructor() {
    super();
    this.evs = [];
    this.load();
    setInterval(this.load.bind(this), 5 * 60 * 1000);
  }

  async load() {
    const store = new Store();
    const r = await fetch("/gcalendarwatch/graph/calendar/upcoming",
    
    {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'X-Pomerium-Authorization': document.cookie.substring(
          document.cookie.indexOf('=') + 1,
        ),
      },
    }
    
    );
    const n3txt = await r.text();
    const parser = new Parser({ format: "application/trig" });
    parser.parse(n3txt, (error, quad, prefixes) => {
      if (quad) {
        store.addQuad(quad);
      } else {
        const graph = namedNode(EV + "gcalendar");
        this.evs = [];
        store.getSubjects(namedNode(RDF + "type"), namedNode(EV + "Event"), graph).forEach((ev: Quad_Subject) => {
          const de = new DisplayEvent(store, graph, ev);
          if (de.show()) {
            this.evs = [...this.evs, de];
          }
        });
        this.evs = sortBy(this.evs, "start");
      }
    });
  }
  static styles = [
    shared,
    css`
      ol {
        list-style-type: circle;
        font-size: 16px;
        background: #cd66bb2e;
        padding: 9px;
        width: fit-content;
        position: relative;
        top: -21px;
        border-radius: 14px;
      }
      span.d {
        opacity: 0.5;
      }
      span.t {
        color: #50fa7b;
      }
    `,
  ];
  render() {
    return html`
      <h1 data-text="Calendar">Calendar</h1>
      <ol>
        ${this.evs.map((d) => d.toHtml())}
      </ol>
    `;
  }
}