Changeset - a10f0f0e4dae
[Not reviewed]
default
0 3 0
drewp@bigasterisk.com - 20 months ago 2023-05-31 20:34:06
drewp@bigasterisk.com
update web ui with one SSE, not repeated requests
3 files changed with 29 insertions and 49 deletions:
0 comments (0 inline, 0 general)
light9/ascoltami/main.py
Show inline comments
 
@@ -47,12 +47,13 @@ class Ascoltami:
 
            return
 

	
 
        self.player.setSong(webapp.songLocation(self.graph, nextSong), play=False)
 

	
 

	
 
def main():
 
    logging.getLogger('sse_starlette.sse').setLevel(logging.INFO)
 
    Gst.init(None)
 

	
 
    graph = showconfig.getGraph()
 
    asco = Ascoltami(graph, showconfig.showUri())
 

	
 
    app = Starlette(
light9/ascoltami/main.ts
Show inline comments
 
@@ -14,25 +14,50 @@ export interface TimingUpdate {
 
}
 

	
 
(window as any).finishOldStyleSetup = async (times: { intro: number; post: number }, updateFreq: number, timingUpdate: (data: TimingUpdate) => void) => {
 
  let currentHighlightedSong = "";
 
  // let lastPlaying = false;
 

	
 
  async function updateCurrent() {
 
    const data: TimingUpdate = await (await fetch("api/time")).json();
 
  
 
  const events = new EventSource("api/time/stream");
 
  events.addEventListener("message", (m)=>{
 
    const update = JSON.parse(m.data) as TimingUpdate
 
    updateCurrent(update)
 
    markUpdateTiming();
 
  })
 

	
 
  async function updateCurrent(data:TimingUpdate) {
 
    byId("currentSong").innerText = data.song;
 
    if (data.song != currentHighlightedSong) {
 
      showCurrentSong(data.song);
 
    }
 
    byId("currentTime").innerText = data.t.toFixed(1);
 
    byId("leftTime").innerText = (data.duration - data.t).toFixed(1);
 
    byId("leftAutoStopTime").innerText = Math.max(0, data.duration - times.post - data.t).toFixed(1);
 
    byId("states").innerText = JSON.stringify(data.state);
 
    //   document.querySelector("#timeSlider").slider({ value: data.t, max: data.duration });
 
    timingUpdate(data);
 
  }
 
  let recentUpdates: Array<number> = [];
 
  function markUpdateTiming() {
 
    recentUpdates.push(+new Date());
 
    recentUpdates = recentUpdates.slice(Math.max(recentUpdates.length - 5, 0));
 
  }
 

	
 
  function refreshUpdateFreqs() {
 
    if (recentUpdates.length > 1) {
 
      if (+new Date() - recentUpdates[recentUpdates.length - 1] > 1000) {
 
        byId("updateActual").innerText = "(stalled)";
 
        return;
 
      }
 

	
 
      var avgMs = (recentUpdates[recentUpdates.length - 1] - recentUpdates[0]) / (recentUpdates.length - 1);
 
      byId("updateActual").innerText = "" + Math.round(1000 / avgMs);
 
    }
 
  }
 
  setInterval(refreshUpdateFreqs, 2000);
 

	
 
  function showCurrentSong(uri: string) {
 
    document.querySelectorAll(".songs div").forEach((row: Element, i: number) => {
 
      if (row.querySelector("button")!.dataset.uri == uri) {
 
        row.classList.add("currentSong");
 
      } else {
 
@@ -69,53 +94,7 @@ export interface TimingUpdate {
 
    });
 
    const dv = document.createElement("div");
 
    dv.appendChild(button);
 
    document.querySelector(".songs")!.appendChild(dv);
 
  });
 

	
 
  //   var pendingSlide = false;
 
  //   $("#timeSlider").slider({
 
  //     step: 0.01,
 
  //     slide: function (event, ui) {
 
  //       if (pendingSlide) {
 
  //         return;
 
  //       }
 
  //       pendingSlide = true;
 
  //       $.post("time", '{"t" : ' + ui.value + "}", function (data, status, xhr) {
 
  //         pendingSlide = false;
 
  //       });
 
  //     },
 
  //   });
 

	
 
  let recentUpdates: Array<number> = [];
 
  function onUpdate() {
 
    recentUpdates.push(+new Date());
 
    recentUpdates = recentUpdates.slice(Math.max(recentUpdates.length - 5, 0));
 
    refreshUpdateFreqs();
 
  }
 

	
 
  function refreshUpdateFreqs() {
 
    if (recentUpdates.length > 1) {
 
      if (+new Date() - recentUpdates[recentUpdates.length - 1] > 1000) {
 
        byId("updateActual").innerText = "(stalled)";
 
        document.querySelectorAll(".dimStalled").forEach((el) => el.classList.add("stalled"));
 
        return;
 
      }
 

	
 
      var avgMs = (recentUpdates[recentUpdates.length - 1] - recentUpdates[0]) / (recentUpdates.length - 1);
 
      byId("updateActual").innerText = "" + Math.round(1000 / avgMs);
 
    }
 
  }
 
  setInterval(refreshUpdateFreqs, 2000);
 

	
 
  async function updateLoop() {
 
    var whenDone = function () {
 
      setTimeout(function () {
 
        requestAnimationFrame(updateLoop);
 
      }, 1000 / updateFreq);
 
    };
 
    onUpdate();
 
    await updateCurrent();
 
    whenDone();
 
  }
 
  updateLoop();
 
};
light9/ascoltami/webapp.py
Show inline comments
 
@@ -106,13 +106,13 @@ async def timeStream(request: Request):
 
            if msg != last_sent or now > last_sent_time + 2:
 
                event_data = json.dumps(msg)
 
                yield event_data
 
                last_sent = msg
 
                last_sent_time = now
 

	
 
            await asyncio.sleep(0.2)
 
            await asyncio.sleep(0.1)
 

	
 
    return EventSourceResponse(event_generator())
 

	
 

	
 
async def get_songs(request: Request) -> JSONResponse:
 
    graph = cast(Graph, request.app.state.graph)
0 comments (0 inline, 0 general)