device_overrides.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. // NameSource (#2163): fuente de nombre elegida para este cliente,
  66. // "auto" o vacío para volver a la precedencia del servidor.
  67. NameSource *string `json:"nameSource"`
  68. }
  69. if st := readJSONBody(w, r, &body); st != 0 {
  70. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  71. return
  72. }
  73. if body.Icon != nil && !validateIcon(*body.Icon) {
  74. writeError(w, http.StatusBadRequest, "invalid_icon")
  75. return
  76. }
  77. if body.Type != nil && *body.Type != "" && !adapters.ValidDeviceTypes[*body.Type] {
  78. writeError(w, http.StatusBadRequest, "invalid_type")
  79. return
  80. }
  81. if body.NameSource != nil && *body.NameSource != "" && *body.NameSource != "auto" && !adapters.ValidNameSource(*body.NameSource) {
  82. writeError(w, http.StatusBadRequest, "invalid_name_source")
  83. return
  84. }
  85. name := ""
  86. if body.Name != nil {
  87. name = strings.TrimSpace(*body.Name)
  88. if strings.ContainsAny(name, "\r\n") {
  89. writeError(w, http.StatusBadRequest, "invalid_name")
  90. return
  91. }
  92. if len(name) > deviceNameMax {
  93. name = name[:deviceNameMax]
  94. }
  95. }
  96. // Valores actuales (los campos ausentes conservan lo persistido).
  97. var curIcon sql.NullString
  98. var curName, curType, curNameSource string
  99. var curNotifyOffline bool
  100. row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac)
  101. switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline, &curNameSource); err {
  102. case nil:
  103. case sql.ErrNoRows:
  104. default:
  105. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  106. return
  107. }
  108. nextIcon := curIcon.String
  109. nextName, nextType := curName, curType
  110. nextNotifyOffline := curNotifyOffline
  111. nextNameSource := curNameSource
  112. if body.Icon != nil {
  113. nextIcon = *body.Icon
  114. }
  115. if body.Name != nil {
  116. nextName = name
  117. }
  118. if body.Type != nil {
  119. nextType = *body.Type
  120. }
  121. if body.NotifyOffline != nil {
  122. nextNotifyOffline = *body.NotifyOffline
  123. }
  124. if body.NameSource != nil {
  125. // "auto" es la forma explícita de limpiar la elección.
  126. if *body.NameSource == "auto" {
  127. nextNameSource = ""
  128. } else {
  129. nextNameSource = *body.NameSource
  130. }
  131. }
  132. now := time.Now().UnixMilli()
  133. if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline && nextNameSource == "" {
  134. _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
  135. } else {
  136. _, err := s.db.Exec(
  137. `INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, name_source, created_at, updated_at)
  138. VALUES (?, ?, ?, ?, '', ?, ?, ?, ?)
  139. ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
  140. device_type=excluded.device_type, notify_offline=excluded.notify_offline,
  141. name_source=excluded.name_source, updated_at=excluded.updated_at`,
  142. mac, nextIcon, nextName, nextType, nextNotifyOffline, nextNameSource, now, now,
  143. )
  144. if err != nil {
  145. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  146. return
  147. }
  148. }
  149. // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices.
  150. if s.pollNow != nil {
  151. s.pollNow()
  152. }
  153. writeJSON(w, http.StatusOK, map[string]any{
  154. "ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
  155. "notifyOffline": nextNotifyOffline, "nameSource": nextNameSource,
  156. })
  157. }
  158. // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
  159. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
  160. mac := macaddr.Normalize(r.PathValue("mac"))
  161. if mac == "" {
  162. writeError(w, http.StatusBadRequest, "invalid_mac")
  163. return
  164. }
  165. var icon, name, deviceType, banned sql.NullString
  166. var notifyOffline bool
  167. var nameSource string
  168. row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac)
  169. if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline, &nameSource); err != nil && err != sql.ErrNoRows {
  170. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  171. return
  172. }
  173. writeJSON(w, http.StatusOK, map[string]any{
  174. "mac": mac,
  175. "icon": icon.String,
  176. "name": name.String,
  177. "type": deviceType.String,
  178. "bannedBands": banned.String,
  179. "notifyOffline": notifyOffline,
  180. "nameSource": nameSource,
  181. })
  182. }
  183. // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}.
  184. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437).
  185. func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
  186. var body struct {
  187. Bands []string `json:"bands"`
  188. }
  189. if st := readJSONBody(w, r, &body); st != 0 {
  190. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  191. return
  192. }
  193. _ = body
  194. writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
  195. }
  196. // handleDeviceDelete: borra un cliente del registro device_seen (#1145,
  197. // retención indefinida con control explícito). Si el cliente sigue viéndose
  198. // en vivo, el siguiente ciclo del poller lo vuelve a dar de alta: borrar
  199. // elimina el recuerdo, no el equipo físico (la UI lo documenta en el
  200. // diálogo de confirmación).
  201. func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) {
  202. raw := strings.TrimSpace(r.PathValue("mac"))
  203. mac := strings.ToUpper(strings.ReplaceAll(raw, "-", ":"))
  204. if mac == "" {
  205. writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
  206. return
  207. }
  208. // BDs legadas pueden guardar la MAC sin normalizar (con guiones): se
  209. // borran ambas formas (#1145).
  210. res, err := s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?", mac, raw)
  211. if err != nil {
  212. writeError(w, http.StatusInternalServerError, "storage_error", "")
  213. return
  214. }
  215. // #1278: lápida. Sin ella, la siguiente fuente que reporte la MAC como
  216. // online (una entrada cacheada del AP, un colector) la re-daba de alta y
  217. // el borrado "no funcionaba".
  218. if norm := macaddr.Normalize(raw); norm != "" {
  219. if err := s.db.AddDeletedClient(norm); err != nil {
  220. writeError(w, http.StatusInternalServerError, "storage_error", "")
  221. return
  222. }
  223. }
  224. if n, _ := res.RowsAffected(); n == 0 {
  225. writeError(w, http.StatusNotFound, "not_found", "")
  226. return
  227. }
  228. w.WriteHeader(http.StatusNoContent)
  229. }