ntfy_settings.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // ntfy_settings.go - ajustes del canal ntfy (#766): GET (sin token nunca),
  2. // PUT (token vacío = conservar) y test de publicación real.
  3. package httpapi
  4. import (
  5. "net/http"
  6. "github.com/gnacho/netpulse/server-go/internal/auth"
  7. "github.com/gnacho/netpulse/server-go/internal/ntfy"
  8. )
  9. type ntfyConfigResponse struct {
  10. Server string `json:"server"`
  11. Topic string `json:"topic"`
  12. TokenSet bool `json:"tokenSet"`
  13. Enabled bool `json:"enabled"`
  14. UrgentOnly bool `json:"urgentOnly"`
  15. }
  16. func (s *server) registerNtfyRoutes(mux *http.ServeMux) {
  17. adapter := &dbKVAdapter{db: s.db.DB}
  18. mux.Handle("GET /api/settings/ntfy", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. cfg := ntfy.LoadConfig(adapter)
  20. writeJSON(w, http.StatusOK, ntfyConfigResponse{
  21. Server: cfg.Server,
  22. Topic: cfg.Topic,
  23. TokenSet: cfg.Token != "",
  24. Enabled: cfg.Enabled,
  25. UrgentOnly: cfg.UrgentOnly,
  26. })
  27. })))
  28. mux.Handle("PUT /api/settings/ntfy", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  29. var body struct {
  30. Server string `json:"server"`
  31. Topic string `json:"topic"`
  32. Token string `json:"token"`
  33. Enabled bool `json:"enabled"`
  34. // UrgentOnly (#874): nil = no tocar (los bool planos no distinguen
  35. // "no mandado" de false).
  36. UrgentOnly *bool `json:"urgentOnly"`
  37. // Clear: desactivar y limpiar el canal entero (como el disable de
  38. // telegram): el PUT normal con enabled=false solo apaga.
  39. Clear bool `json:"clear"`
  40. }
  41. if st := readJSONBody(w, r, &body); st != 0 {
  42. return
  43. }
  44. cfg := ntfy.LoadConfig(adapter)
  45. if body.Clear {
  46. cfg = ntfy.Config{Server: ntfy.DefaultServer, UrgentOnly: true}
  47. } else {
  48. if body.Server != "" {
  49. cfg.Server = body.Server
  50. }
  51. if body.Topic != "" {
  52. cfg.Topic = body.Topic
  53. }
  54. if body.Token != "" {
  55. cfg.Token = body.Token
  56. }
  57. cfg.Enabled = body.Enabled
  58. if body.UrgentOnly != nil {
  59. cfg.UrgentOnly = *body.UrgentOnly
  60. }
  61. }
  62. if err := ntfy.SaveConfig(adapter, cfg); err != nil {
  63. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  64. return
  65. }
  66. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  67. })))
  68. mux.Handle("POST /api/settings/ntfy/test", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  69. if err := ntfy.SendTest(adapter); err != nil {
  70. writeError(w, http.StatusBadRequest, "ntfy_test_failed", err.Error())
  71. return
  72. }
  73. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  74. })))
  75. }