announcements.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // announcements.go — avisos externos para todas las instancias: el server
  2. // consulta announcements.json del repo (raw de GitHub, como hace el updater)
  3. // y expone el aviso activo en /api/announcement. La UI lo pinta con el
  4. // estilo del ribbon de actualizar. Override de la fuente con
  5. // NETPULSE_ANNOUNCEMENTS_URL (pruebas); fail-silent: sin red, sin aviso.
  6. package httpapi
  7. import (
  8. "context"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "log"
  13. "net/http"
  14. "os"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. defaultAnnouncementsURL = "https://netpulse.cloudless.club/announcements.json"
  20. announcementsRefresh = 6 * time.Hour
  21. announcementsTimeout = 5 * time.Second
  22. announcementsMaxBytes = 64 << 10
  23. )
  24. // Announcement es un aviso publicado en announcements.json. Title/Body van
  25. // por idioma (es/en; el cliente cae a en). Starts/Expires ("YYYY-MM-DD",
  26. // opcionales) delimitan la ventana de vigencia. Goal (opcional) añade una
  27. // barra de progreso de campaña (p.ej. estrellas de GitHub): Current/Target
  28. // se publican a mano en el JSON; no hay contador en vivo.
  29. type Announcement struct {
  30. ID string `json:"id"`
  31. Urgency string `json:"urgency"` // "info" | "warn"
  32. Title map[string]string `json:"title"`
  33. Body map[string]string `json:"body,omitempty"`
  34. URL string `json:"url,omitempty"`
  35. URLLabel map[string]string `json:"urlLabel,omitempty"`
  36. Goal *AnnouncementGoal `json:"goal,omitempty"`
  37. Starts string `json:"starts,omitempty"`
  38. Expires string `json:"expires,omitempty"`
  39. }
  40. // AnnouncementGoal: meta visible de campaña con barra de progreso.
  41. type AnnouncementGoal struct {
  42. Current int `json:"current"`
  43. Target int `json:"target"`
  44. }
  45. type announcementsFile struct {
  46. Announcements []Announcement `json:"announcements"`
  47. }
  48. type announcementCache struct {
  49. mu sync.Mutex
  50. now func() time.Time
  51. url string
  52. cur *Announcement
  53. }
  54. func (c *announcementCache) set(a *Announcement) {
  55. c.mu.Lock()
  56. defer c.mu.Unlock()
  57. c.cur = a
  58. }
  59. func (c *announcementCache) get() *Announcement {
  60. c.mu.Lock()
  61. defer c.mu.Unlock()
  62. return c.cur
  63. }
  64. // activeAnnouncement elige el primer aviso vigente (starts <= hoy < expires).
  65. func activeAnnouncement(list []Announcement, now time.Time) *Announcement {
  66. today := now.Format("2006-01-02")
  67. for i := range list {
  68. a := list[i]
  69. if a.ID == "" {
  70. continue
  71. }
  72. if a.Starts != "" && today < a.Starts {
  73. continue
  74. }
  75. if a.Expires != "" && today >= a.Expires {
  76. continue
  77. }
  78. return &a
  79. }
  80. return nil
  81. }
  82. func fetchAnnouncements(ctx context.Context, url string) (*Announcement, error) {
  83. ctx, cancel := context.WithTimeout(ctx, announcementsTimeout)
  84. defer cancel()
  85. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  86. if err != nil {
  87. return nil, err
  88. }
  89. req.Header.Set("User-Agent", "netpulse-announcements")
  90. res, err := http.DefaultClient.Do(req)
  91. if err != nil {
  92. return nil, err
  93. }
  94. defer res.Body.Close()
  95. if res.StatusCode != http.StatusOK {
  96. return nil, fmt.Errorf("announcements: HTTP %d", res.StatusCode)
  97. }
  98. var file announcementsFile
  99. if err := json.NewDecoder(io.LimitReader(res.Body, announcementsMaxBytes)).Decode(&file); err != nil {
  100. return nil, err
  101. }
  102. return activeAnnouncement(file.Announcements, time.Now()), nil
  103. }
  104. // startAnnouncements lanza el bucle de refresco (daemon; vive con el server).
  105. func (s *server) startAnnouncements() {
  106. url := defaultAnnouncementsURL
  107. if v := os.Getenv("NETPULSE_ANNOUNCEMENTS_URL"); v != "" {
  108. url = v
  109. }
  110. c := &announcementCache{now: time.Now, url: url}
  111. s.announcements = c
  112. refresh := func() {
  113. a, err := fetchAnnouncements(context.Background(), c.url)
  114. if err != nil {
  115. log.Printf("[netpulse] announcements: fetch failed: %v", err)
  116. return
  117. }
  118. c.set(a)
  119. }
  120. go func() {
  121. refresh()
  122. t := time.NewTicker(announcementsRefresh)
  123. defer t.Stop()
  124. for range t.C {
  125. refresh()
  126. }
  127. }()
  128. }
  129. func (s *server) registerAnnouncementRoutes(mux *http.ServeMux) {
  130. // Sin sesión no hay aviso (igual que el overview); en demo la sesión
  131. // pública de la demo lo recibe igual: el aviso va a todas las instancias.
  132. mux.HandleFunc("GET /api/announcement", func(w http.ResponseWriter, r *http.Request) {
  133. c := s.announcements
  134. if c == nil {
  135. writeJSON(w, http.StatusOK, map[string]any{"active": false})
  136. return
  137. }
  138. a := c.get()
  139. if a == nil {
  140. writeJSON(w, http.StatusOK, map[string]any{"active": false})
  141. return
  142. }
  143. writeJSON(w, http.StatusOK, map[string]any{"active": true, "announcement": a})
  144. })
  145. }