4
0

device_overrides.go 8.3 KB

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