From 5600bff4299ff15c15b17276c47a57ad8c3728db Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Mon, 23 Nov 2020 11:34:08 +0100 Subject: [PATCH] Add support for custom alerts --- api.go | 33 ++++++++++++++++++++++++++++++--- public/app.js | 11 +++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/api.go b/api.go index 8c4a86c..1bef544 100644 --- a/api.go +++ b/api.go @@ -2,6 +2,7 @@ package main import ( "crypto/sha256" + "encoding/json" "fmt" "net/http" "strings" @@ -89,12 +90,38 @@ var upgrader = websocket.Upgrader{ } func registerAPI(r *mux.Router) { - r.HandleFunc("/api/follows/clear-last", handleSetLastFollower) - r.HandleFunc("/api/follows/set-last/{name}", handleSetLastFollower) - r.HandleFunc("/api/subscribe", handleUpdateSocket) + r.HandleFunc("/api/custom-alert", handleCustomAlert).Methods(http.MethodPost) + r.HandleFunc("/api/follows/clear-last", handleSetLastFollower).Methods(http.MethodPut) + r.HandleFunc("/api/follows/set-last/{name}", handleSetLastFollower).Methods(http.MethodPut) + r.HandleFunc("/api/subscribe", handleUpdateSocket).Methods(http.MethodGet) r.HandleFunc("/api/webhook/{type}", handleWebHookPush) } +func handleCustomAlert(w http.ResponseWriter, r *http.Request) { + var alert struct { + Sound *string `json:"sound"` + Text string `json:"text"` + Title string `json:"title"` + } + + if err := json.NewDecoder(r.Body).Decode(&alert); err != nil { + http.Error(w, errors.Wrap(err, "parse request body").Error(), http.StatusBadRequest) + return + } + + if alert.Title == "" || alert.Text == "" { + http.Error(w, "empty title or text", http.StatusBadRequest) + return + } + + if err := subscriptions.SendAllSockets("alert", alert); err != nil { + http.Error(w, errors.Wrap(err, "send to sockets").Error(), http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusCreated) +} + func handleSetLastFollower(w http.ResponseWriter, r *http.Request) { name := mux.Vars(r)["name"] diff --git a/public/app.js b/public/app.js index b978019..1d75eaa 100644 --- a/public/app.js +++ b/public/app.js @@ -52,11 +52,11 @@ const app = new Vue({ this.sound.src = soundUrl }, - showAlert(title, text) { + showAlert(title, text, variant) { this.$bvToast.toast(text, { title, toaster: 'b-toaster-top-right', - variant: 'primary', + variant: variant || 'primary', }) }, @@ -83,6 +83,13 @@ const app = new Vue({ } switch (data.type) { + case 'alert': + this.showAlert(data.payload.title, data.payload.text, data.payload.variant) + if (data.payload.sound) { + this.playSound(data.payload.sound) + } + break + case 'store': this.store = data.payload break