diff --git a/static/js/WebSocketChannel.js b/static/js/WebSocketChannel.js index 7edbfd5..9e0797d 100644 --- a/static/js/WebSocketChannel.js +++ b/static/js/WebSocketChannel.js @@ -1,4 +1,6 @@ +import { getStats } from './api.js'; + class WebSocketChannel { constructor(){ this.wsUrl = window.location.protocol.replace("http", "ws") + @@ -44,9 +46,26 @@ class WebSocketChannel { } }; + function fallbackPolling(){ + getStats() + .then(function(stats){ + if (!stats){ + // no stats (yet) + return; + } + + var listeners = self.listenerMap["minetest-info"]; + if (listeners){ + listeners.forEach(function(listener){ + listener(stats); + }); + } + }); + } + ws.onerror = function(){ - //reconnect after some time - setTimeout(self.connect.bind(self), 1000); + //fallback to polling stats + setInterval(fallbackPolling, 2000); }; } } diff --git a/static/js/api.js b/static/js/api.js index f83f4f5..3de10e6 100644 --- a/static/js/api.js +++ b/static/js/api.js @@ -10,3 +10,7 @@ export function getMapObjects(query){ export function getConfig(){ return m.request("api/config"); } + +export function getStats(){ + return m.request("api/stats"); +} diff --git a/web/minetest.go b/web/minetest.go index 924d66f..ee142bd 100644 --- a/web/minetest.go +++ b/web/minetest.go @@ -68,6 +68,8 @@ type Minetest struct { ctx *app.App } +var LastStats *MinetestInfo + func (this *Minetest) ServeHTTP(resp http.ResponseWriter, req *http.Request) { if req.Header.Get("Authorization") != this.ctx.Config.WebApi.SecretKey { resp.WriteHeader(403) @@ -91,6 +93,7 @@ func (this *Minetest) ServeHTTP(resp http.ResponseWriter, req *http.Request) { mintestPlayers.Set(float64(len(data.Players))) mintestMaxLag.Set(data.MaxLag) + LastStats = data this.ctx.WebEventbus.Emit("minetest-info", data) json.NewEncoder(resp).Encode("stub") diff --git a/web/serve.go b/web/serve.go index 940a098..150fa90 100644 --- a/web/serve.go +++ b/web/serve.go @@ -25,6 +25,7 @@ func Serve(ctx *app.App) { tiles.Init() mux.Handle("/api/tile/", tiles) mux.Handle("/api/config", &ConfigHandler{ctx: ctx}) + mux.Handle("/api/stats", &StatsHandler{ctx: ctx}) mux.Handle("/api/media/", &MediaHandler{ctx: ctx}) mux.Handle("/api/minetest", &Minetest{ctx: ctx}) mux.Handle("/api/mapobjects/", &MapObjects{ctx: ctx}) diff --git a/web/stats.go b/web/stats.go new file mode 100644 index 0000000..13b88cf --- /dev/null +++ b/web/stats.go @@ -0,0 +1,16 @@ +package web + +import ( + "encoding/json" + "mapserver/app" + "net/http" +) + +type StatsHandler struct { + ctx *app.App +} + +func (h *StatsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + resp.Header().Add("content-type", "application/json") + json.NewEncoder(resp).Encode(LastStats) +}