current song as server side event
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Marvin Preuss 2021-08-26 14:09:02 +02:00
parent abdce361b5
commit 07743e46cd
6 changed files with 90 additions and 6 deletions

View File

@ -1,5 +1 @@
# schnutibox
## TODO
- raspi configuration script

View File

@ -1,6 +1,6 @@
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/log");
source.onmessage = function(event) {
var logSource = new EventSource("/log");
logSource.onmessage = function(event) {
var j = JSON.parse(event.data);
/* eslint-disable no-prototype-builtins */
if (j.hasOwnProperty("message")) {
@ -11,6 +11,15 @@ if(typeof(EventSource) !== "undefined") {
document.getElementById("log").innerHTML = "Sorry, your browser does not support server-sent events...";
}
if(typeof(EventSource) !== "undefined") {
var currentsongSource = new EventSource("/currentsong");
currentsongSource.onmessage = function(event){
document.getElementById("currentsong").innerHTML = event.data
};
} else {
document.getElementById("currentsong").innerHTML = "Sorry, your browser does not support server-sent events...";
};
function handleSubmit(event, url) {
event.preventDefault()

View File

@ -11,6 +11,9 @@
<div class="container">
<h1>schnutibox</h1>
<h2>Currently playing</h2>
<div id="currentsong"></div>
<h2>Timer</h2>
Takes only seconds. Example: 600s
<form id="timerForm">

View File

@ -0,0 +1,56 @@
package currentsong
import (
"fmt"
"net/http"
"go.xsfx.dev/logginghandler"
)
var recvs = make(map[chan string]struct{}) // nolint:gochecknoglobals
// Write writes current track to the receivers.
func Write(track string) {
for k := range recvs {
k <- track
}
}
func Handler(w http.ResponseWriter, r *http.Request) {
logger := logginghandler.Logger(r)
logger.Debug().Msg("got a new receiver")
flusher, ok := w.(http.Flusher)
if !ok {
logger.Error().Msg("streaming unsupported")
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// TODO: has to be something else!
w.Header().Set("Access-Control-Allow-Origin", "*")
cChan := make(chan string)
recvs[cChan] = struct{}{}
for {
select {
case e := <-cChan:
// Send event to client.
fmt.Fprintf(w, "data: %s\n\n", e)
// Send it right now and not buffering it.
flusher.Flush()
case <-r.Context().Done():
close(cChan)
delete(recvs, cChan)
return
}
}
}

View File

@ -1,10 +1,12 @@
package watcher
import (
"fmt"
"time"
"github.com/rs/zerolog/log"
"go.xsfx.dev/schnutibox/internal/metrics"
"go.xsfx.dev/schnutibox/pkg/currentsong"
"go.xsfx.dev/schnutibox/pkg/mpc"
"go.xsfx.dev/schnutibox/pkg/timer"
)
@ -51,6 +53,20 @@ func Run() {
return
}
currentSong, err := m.CurrentSong()
if err != nil {
log.Error().Err(err).Msg("could not get current song")
metrics.BoxErrors.Inc()
return
}
if len(currentSong) != 0 {
currentsong.Write(fmt.Sprintf("%s - %s", currentSong["Artist"], currentSong["Track"]))
} else {
currentsong.Write("")
}
// Sets the metrics.
metrics.Set(uris, s["state"])
}()

View File

@ -17,6 +17,7 @@ import (
assets "go.xsfx.dev/schnutibox/assets/web"
"go.xsfx.dev/schnutibox/internal/config"
api "go.xsfx.dev/schnutibox/pkg/api/v1"
"go.xsfx.dev/schnutibox/pkg/currentsong"
"go.xsfx.dev/schnutibox/pkg/sselog"
"go.xsfx.dev/schnutibox/pkg/timer"
"golang.org/x/net/http2"
@ -96,6 +97,8 @@ func (t TimerServer) Get(ctx context.Context, req *api.TimerEmpty) (*api.Timer,
return timer.T.Req, nil
}
func currentSong(w http.ResponseWriter, r *http.Request) {}
func gw(s *grpc.Server, conn string) *runtime.ServeMux {
ctx := context.Background()
gopts := []grpc.DialOption{grpc.WithInsecure()}
@ -133,6 +136,7 @@ func Run(command *cobra.Command, args []string) {
mux.Handle("/", http.HandlerFunc(root))
mux.Handle("/log", http.HandlerFunc(sselog.LogHandler))
mux.Handle("/currentsong", http.HandlerFunc(currentsong.Handler))
mux.Handle(
"/static/",