device_overrides.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // device_overrides.go — mutaciones manuales de dispositivo (issue #437,
  2. // #797):
  3. //
  4. // PUT /api/devices/{mac}/override → icono, nombre visible y/o tipo.
  5. // PUT /api/devices/{mac}/ban → bandas a bloquear/desbloquear (Fase 2).
  6. //
  7. // Semántica del PUT: cada campo es opcional; ausente = no tocar, vacío =
  8. // limpiar ese override. Así los clientes antiguos que solo envían {icon}
  9. // (p. ej. el alta rápida de desconocidos, #772) no borran nombre/tipo.
  10. package httpapi
  11. import (
  12. "database/sql"
  13. "net/http"
  14. "strings"
  15. "time"
  16. "github.com/gnacho/netpulse/agent/macaddr"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. )
  19. // validateIcon comprueba que el icono enviado es uno de los permitidos por
  20. // DEVICE_ICONS del frontend. Lista cerrada para evitar inyección de clases.
  21. func validateIcon(icon string) bool {
  22. if icon == "" {
  23. return true
  24. }
  25. allowed := map[string]bool{
  26. "monitor": true, "laptop": true, "smartphone": true, "tablet": true,
  27. "tv": true, "gamepad": true, "camera": true, "cctv": true,
  28. "vacuum": true, "doorbell": true, "air-vent": true, "heater": true,
  29. "circuit-board": true, "speaker": true,
  30. "router": true, "server": true, "watch": true, "car": true,
  31. "home": true, "printer": true, "plug": true, "shield": true,
  32. "help-circle": true, "wifi": true, "ethernet": true,
  33. // Overrides de domótica: mantener en sincronía con ICON_OVERRIDES.
  34. "refrigerator": true, "washing-machine": true, "microwave": true,
  35. "coffee": true,
  36. "toilet": true, "droplets": true, "flame": true,
  37. "thermometer": true, "fan": true,
  38. "plug-zap": true, "battery-charging": true, "solar-panel": true, "power": true,
  39. "lightbulb": true, "lamp": true, "lamp-ceiling": true,
  40. "lock-keyhole": true, "door-closed": true, "scan-face": true,
  41. "webcam": true, "siren": true,
  42. "paw-print": true, "baby": true, "scale": true,
  43. "projector": true, "cast": true, "headphones": true,
  44. "hard-drive": true, "database": true, "cloud": true, "cpu": true,
  45. "bot": true, "antenna": true, "satellite-dish": true,
  46. "blinds": true, "gauge": true,
  47. }
  48. return allowed[icon]
  49. }
  50. // deviceNameMax cota el nombre visible personalizado (#797).
  51. const deviceNameMax = 64
  52. // handleDeviceOverridePut: campos opcionales {"icon","name","type"}; vacío
  53. // limpia, ausente no toca. Si los tres quedan vacíos la fila se borra.
  54. func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) {
  55. mac := macaddr.Normalize(r.PathValue("mac"))
  56. if mac == "" {
  57. writeError(w, http.StatusBadRequest, "invalid_mac")
  58. return
  59. }
  60. var body struct {
  61. Icon *string `json:"icon"`
  62. Name *string `json:"name"`
  63. Type *string `json:"type"`
  64. NotifyOffline *bool `json:"notifyOffline"`
  65. }
  66. if st := readJSONBody(w, r, &body); st != 0 {
  67. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  68. return
  69. }
  70. if body.Icon != nil && !validateIcon(*body.Icon) {
  71. writeError(w, http.StatusBadRequest, "invalid_icon")
  72. return
  73. }
  74. if body.Type != nil && *body.Type != "" && !adapters.ValidDeviceTypes[*body.Type] {
  75. writeError(w, http.StatusBadRequest, "invalid_type")
  76. return
  77. }
  78. name := ""
  79. if body.Name != nil {
  80. name = strings.TrimSpace(*body.Name)
  81. if strings.ContainsAny(name, "\r\n") {
  82. writeError(w, http.StatusBadRequest, "invalid_name")
  83. return
  84. }
  85. if len(name) > deviceNameMax {
  86. name = name[:deviceNameMax]
  87. }
  88. }
  89. // Valores actuales (los campos ausentes conservan lo persistido).
  90. var curIcon sql.NullString
  91. var curName, curType string
  92. var curNotifyOffline bool
  93. row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline FROM device_overrides WHERE mac = ?", mac)
  94. switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline); err {
  95. case nil:
  96. case sql.ErrNoRows:
  97. default:
  98. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  99. return
  100. }
  101. nextIcon := curIcon.String
  102. nextName, nextType := curName, curType
  103. nextNotifyOffline := curNotifyOffline
  104. if body.Icon != nil {
  105. nextIcon = *body.Icon
  106. }
  107. if body.Name != nil {
  108. nextName = name
  109. }
  110. if body.Type != nil {
  111. nextType = *body.Type
  112. }
  113. if body.NotifyOffline != nil {
  114. nextNotifyOffline = *body.NotifyOffline
  115. }
  116. now := time.Now().UnixMilli()
  117. if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline {
  118. _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
  119. } else {
  120. _, err := s.db.Exec(
  121. `INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at)
  122. VALUES (?, ?, ?, ?, '', ?, ?, ?)
  123. ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
  124. device_type=excluded.device_type, notify_offline=excluded.notify_offline,
  125. updated_at=excluded.updated_at`,
  126. mac, nextIcon, nextName, nextType, nextNotifyOffline, now, now,
  127. )
  128. if err != nil {
  129. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  130. return
  131. }
  132. }
  133. // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices.
  134. if s.pollNow != nil {
  135. s.pollNow()
  136. }
  137. writeJSON(w, http.StatusOK, map[string]any{
  138. "ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
  139. "notifyOffline": nextNotifyOffline,
  140. })
  141. }
  142. // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
  143. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
  144. mac := macaddr.Normalize(r.PathValue("mac"))
  145. if mac == "" {
  146. writeError(w, http.StatusBadRequest, "invalid_mac")
  147. return
  148. }
  149. var icon, name, deviceType, banned sql.NullString
  150. var notifyOffline bool
  151. row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline FROM device_overrides WHERE mac = ?", mac)
  152. if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline); err != nil && err != sql.ErrNoRows {
  153. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  154. return
  155. }
  156. writeJSON(w, http.StatusOK, map[string]any{
  157. "mac": mac,
  158. "icon": icon.String,
  159. "name": name.String,
  160. "type": deviceType.String,
  161. "bannedBands": banned.String,
  162. "notifyOffline": notifyOffline,
  163. })
  164. }
  165. // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}.
  166. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437).
  167. func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
  168. var body struct {
  169. Bands []string `json:"bands"`
  170. }
  171. if st := readJSONBody(w, r, &body); st != 0 {
  172. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  173. return
  174. }
  175. _ = body
  176. writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
  177. }
  178. // handleDeviceDelete: borra un cliente del registro device_seen (#1145,
  179. // retención indefinida con control explícito). Si el cliente sigue viéndose
  180. // en vivo, el siguiente ciclo del poller lo vuelve a dar de alta: borrar
  181. // elimina el recuerdo, no el equipo físico (la UI lo documenta en el
  182. // diálogo de confirmación).
  183. func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) {
  184. raw := strings.TrimSpace(r.PathValue("mac"))
  185. mac := strings.ToUpper(strings.ReplaceAll(raw, "-", ":"))
  186. if mac == "" {
  187. writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
  188. return
  189. }
  190. // BDs legadas pueden guardar la MAC sin normalizar (con guiones): se
  191. // borran ambas formas (#1145).
  192. res, err := s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?", mac, raw)
  193. if err != nil {
  194. writeError(w, http.StatusInternalServerError, "storage_error", "")
  195. return
  196. }
  197. // #1278: lápida. Sin ella, la siguiente fuente que reporte la MAC como
  198. // online (una entrada cacheada del AP, un colector) la re-daba de alta y
  199. // el borrado "no funcionaba".
  200. if norm := macaddr.Normalize(raw); norm != "" {
  201. if err := s.db.AddDeletedClient(norm); err != nil {
  202. writeError(w, http.StatusInternalServerError, "storage_error", "")
  203. return
  204. }
  205. }
  206. if n, _ := res.RowsAffected(); n == 0 {
  207. writeError(w, http.StatusNotFound, "not_found", "")
  208. return
  209. }
  210. w.WriteHeader(http.StatusNoContent)
  211. }