alertlang.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Package alertlang traduce server-side las alertas para los canales de
  2. // notificación externa (#888 / #889 / #1014).
  3. //
  4. // El motor de alertas compone título/descripción/hint con literales en
  5. // INGLÉS (idioma canónico desde #1014) y la web los traduce en render
  6. // (#671). Los canales ntfy/telegram/webhook reciben el evento ya localizado
  7. // por este paquete: con alerts.lang=en (default) se compone contra el
  8. // catálogo EN; con alerts.lang=es se traduce al catálogo ES. En ambos casos
  9. // se reutilizan los MISMOS catálogos de la app embebidos en el binario
  10. // (dist/locales/<lang>/translation.json, claves alerts.types.<slug>.title|
  11. // .description|.results.* y alerts.hints.*), sin duplicar textos, y el
  12. // fallback cuando falta la clave es el literal EN del evento.
  13. //
  14. // El idioma es un ajuste GLOBAL del servidor (kv "alerts.lang", default "en"):
  15. // las alertas no llevan usuario emisor, son server-wide.
  16. package alertlang
  17. import (
  18. "encoding/json"
  19. "io/fs"
  20. "log"
  21. "strings"
  22. "sync"
  23. "github.com/gnacho/netpulse/server-go/internal/alerts"
  24. )
  25. // KV es el mínimo de store que necesita el paquete (mismo contrato que usan
  26. // ntfy/telegram: Get(key) (string, bool)).
  27. type KV interface {
  28. Get(key string) (string, bool)
  29. }
  30. const (
  31. // KeyLang: idioma de las notificaciones push del servidor.
  32. KeyLang = "alerts.lang"
  33. // DefaultLang: un usuario que no toca nada recibe pushes en inglés (el
  34. // reporte de #888 pedía exactamente eso; la UI sigue auto-detectando).
  35. DefaultLang = "en"
  36. )
  37. var (
  38. localesFS fs.FS
  39. mu sync.Mutex
  40. cache = map[string]*catalog{} // lang → catálogo parseado
  41. supported = map[string]bool{} // idiomas presentes en el dist
  42. )
  43. type typeEntry struct {
  44. Title string `json:"title"`
  45. Description string `json:"description"`
  46. DescriptionUnit string `json:"descriptionUnit"`
  47. Results map[string]string `json:"results"`
  48. }
  49. type catalog struct {
  50. Alerts struct {
  51. Types map[string]typeEntry `json:"types"`
  52. Hints map[string]string `json:"hints"`
  53. } `json:"alerts"`
  54. }
  55. // SetLocalesFS fija el FS de catálogos ("<lang>/translation.json"). Se llama
  56. // una vez al arrancar (staticspa.LocalesFS).
  57. func SetLocalesFS(f fs.FS) {
  58. localesFS = f
  59. entries, err := fs.ReadDir(f, ".")
  60. if err != nil {
  61. log.Printf("[netpulse] alertlang: could not list locales: %v", err)
  62. return
  63. }
  64. for _, e := range entries {
  65. if e.IsDir() {
  66. supported[e.Name()] = true
  67. }
  68. }
  69. log.Printf("[netpulse] alertlang: languages available for push: %v", keys(supported))
  70. }
  71. func keys(m map[string]bool) []string {
  72. out := make([]string, 0, len(m))
  73. for k := range m {
  74. out = append(out, k)
  75. }
  76. return out
  77. }
  78. // Supported devuelve los idiomas disponibles (los del dist).
  79. func Supported() []string { return keys(supported) }
  80. func load(lang string) *catalog {
  81. mu.Lock()
  82. defer mu.Unlock()
  83. if c, ok := cache[lang]; ok {
  84. return c
  85. }
  86. if localesFS == nil {
  87. return nil
  88. }
  89. raw, err := fs.ReadFile(localesFS, lang+"/translation.json")
  90. if err != nil {
  91. log.Printf("[netpulse] alertlang: catalog not found: lang=%s (%v)", lang, err)
  92. return nil
  93. }
  94. var c catalog
  95. if err := json.Unmarshal(raw, &c); err != nil {
  96. log.Printf("[netpulse] alertlang: invalid catalog: lang=%s (%v)", lang, err)
  97. return nil
  98. }
  99. cache[lang] = &c
  100. return &c
  101. }
  102. // Lang devuelve el idioma efectivo de las notificaciones (kv alerts.lang,
  103. // validado contra los disponibles; default en).
  104. func Lang(kv KV) string {
  105. if kv != nil {
  106. if v, ok := kv.Get(KeyLang); ok && supported[v] {
  107. return v
  108. }
  109. }
  110. return DefaultLang
  111. }
  112. // interpolate replica el formato de i18next usado por la app ({{var}}).
  113. func interpolate(tpl string, vars map[string]string) string {
  114. if vars == nil {
  115. return tpl
  116. }
  117. return strings.NewReplacer(pairs(vars)...).Replace(tpl)
  118. }
  119. func pairs(vars map[string]string) []string {
  120. out := make([]string, 0, len(vars)*2)
  121. for k, v := range vars {
  122. out = append(out, "{{"+k+"}}", v)
  123. }
  124. return out
  125. }
  126. // LocalizeLang es el núcleo de Localize con el idioma EXPLÍCITO. Permite
  127. // traducir un evento a un idioma concreto por suscriptor (#1334: el idioma
  128. // efectivo de la UI en el alta de la suscripción de push), sin depender del
  129. // ajuste global. Idioma no soportado o evento sin type: se devuelve tal cual.
  130. func LocalizeLang(ev alerts.AlertEvent, lang string) alerts.AlertEvent {
  131. if ev.Type == "" || !supported[lang] {
  132. return ev
  133. }
  134. c := load(lang)
  135. if c == nil {
  136. return ev
  137. }
  138. entry, ok := c.Alerts.Types[ev.Type]
  139. if !ok {
  140. return ev
  141. }
  142. out := ev
  143. if entry.Title != "" {
  144. out.Title = interpolate(entry.Title, ev.Vars)
  145. }
  146. body := entry.Description
  147. if r := ev.Vars["result"]; r != "" && entry.Results != nil && entry.Results[r] != "" {
  148. body = entry.Results[r]
  149. }
  150. if body != "" {
  151. out.Description = interpolate(body, ev.Vars)
  152. }
  153. if ev.Hint != "" {
  154. if h := c.Alerts.Hints[ev.Type]; h != "" {
  155. out.Hint = h
  156. }
  157. }
  158. return out
  159. }
  160. // Localize devuelve una copia del evento con title/description/hint en el
  161. // idioma efectivo, compuestos desde el catálogo de ese idioma. Cae a los
  162. // literales del server (inglés canónico, #1014) si el evento no tiene type,
  163. // falta la clave o no hay catálogo: nunca peor que el literal nativo.
  164. func Localize(ev alerts.AlertEvent, kv KV) alerts.AlertEvent {
  165. return LocalizeLang(ev, Lang(kv))
  166. }
  167. // notifier traduce cada evento antes de pasarlo a la cadena real.
  168. type notifier struct {
  169. kv KV
  170. next alerts.Notifier
  171. }
  172. // Notifier envuelve la cadena ntfy/telegram/webhook/push para que los pushes
  173. // salgan en el idioma del ajuste alerts.lang (#888, núcleo de #889).
  174. func Notifier(kv KV, next alerts.Notifier) alerts.Notifier {
  175. return notifier{kv: kv, next: next}
  176. }
  177. func (n notifier) Notify(ev alerts.AlertEvent) {
  178. if n.next != nil {
  179. n.next.Notify(Localize(ev, n.kv))
  180. }
  181. }