// device_overrides.go — mutaciones manuales de dispositivo (issue #437, // #797): // // PUT /api/devices/{mac}/override → icono, nombre visible y/o tipo. // PUT /api/devices/{mac}/ban → bandas a bloquear/desbloquear (Fase 2). // // Semántica del PUT: cada campo es opcional; ausente = no tocar, vacío = // limpiar ese override. Así los clientes antiguos que solo envían {icon} // (p. ej. el alta rápida de desconocidos, #772) no borran nombre/tipo. package httpapi import ( "database/sql" "net/http" "strings" "time" "github.com/gnacho/netpulse/agent/macaddr" "github.com/gnacho/netpulse/server-go/internal/adapters" ) // validateIcon comprueba que el icono enviado es uno de los permitidos por // DEVICE_ICONS del frontend. Lista cerrada para evitar inyección de clases. func validateIcon(icon string) bool { if icon == "" { return true } allowed := map[string]bool{ "monitor": true, "laptop": true, "smartphone": true, "tablet": true, "tv": true, "gamepad": true, "camera": true, "cctv": true, "vacuum": true, "doorbell": true, "air-vent": true, "heater": true, "circuit-board": true, "speaker": true, "router": true, "server": true, "watch": true, "car": true, "home": true, "printer": true, "plug": true, "shield": true, "help-circle": true, "wifi": true, "ethernet": true, // Overrides de domótica: mantener en sincronía con ICON_OVERRIDES. "refrigerator": true, "washing-machine": true, "microwave": true, "coffee": true, "toilet": true, "droplets": true, "flame": true, "thermometer": true, "fan": true, "plug-zap": true, "battery-charging": true, "solar-panel": true, "power": true, "lightbulb": true, "lamp": true, "lamp-ceiling": true, "lock-keyhole": true, "door-closed": true, "scan-face": true, "webcam": true, "siren": true, "paw-print": true, "baby": true, "scale": true, "projector": true, "cast": true, "headphones": true, "hard-drive": true, "database": true, "cloud": true, "cpu": true, "bot": true, "antenna": true, "satellite-dish": true, "blinds": true, "gauge": true, } return allowed[icon] } // deviceNameMax cota el nombre visible personalizado (#797). const deviceNameMax = 64 // handleDeviceOverridePut: campos opcionales {"icon","name","type"}; vacío // limpia, ausente no toca. Si los tres quedan vacíos la fila se borra. func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) { mac := macaddr.Normalize(r.PathValue("mac")) if mac == "" { writeError(w, http.StatusBadRequest, "invalid_mac") return } var body struct { Icon *string `json:"icon"` Name *string `json:"name"` Type *string `json:"type"` NotifyOffline *bool `json:"notifyOffline"` // NameSource (#2163): fuente de nombre elegida para este cliente, // "auto" o vacío para volver a la precedencia del servidor. NameSource *string `json:"nameSource"` } if st := readJSONBody(w, r, &body); st != 0 { writeBodyError(w, st, "invalid_body", "body JSON inválido") return } if body.Icon != nil && !validateIcon(*body.Icon) { writeError(w, http.StatusBadRequest, "invalid_icon") return } if body.Type != nil && *body.Type != "" && !adapters.ValidDeviceTypes[*body.Type] { writeError(w, http.StatusBadRequest, "invalid_type") return } if body.NameSource != nil && *body.NameSource != "" && *body.NameSource != "auto" && !adapters.ValidNameSource(*body.NameSource) { writeError(w, http.StatusBadRequest, "invalid_name_source") return } name := "" if body.Name != nil { name = strings.TrimSpace(*body.Name) if strings.ContainsAny(name, "\r\n") { writeError(w, http.StatusBadRequest, "invalid_name") return } if len(name) > deviceNameMax { name = name[:deviceNameMax] } } // Valores actuales (los campos ausentes conservan lo persistido). var curIcon sql.NullString var curName, curType, curNameSource string var curNotifyOffline bool row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac) switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline, &curNameSource); err { case nil: case sql.ErrNoRows: default: writeError(w, http.StatusInternalServerError, "db_error", err.Error()) return } nextIcon := curIcon.String nextName, nextType := curName, curType nextNotifyOffline := curNotifyOffline nextNameSource := curNameSource if body.Icon != nil { nextIcon = *body.Icon } if body.Name != nil { nextName = name } if body.Type != nil { nextType = *body.Type } if body.NotifyOffline != nil { nextNotifyOffline = *body.NotifyOffline } if body.NameSource != nil { // "auto" es la forma explícita de limpiar la elección. if *body.NameSource == "auto" { nextNameSource = "" } else { nextNameSource = *body.NameSource } } now := time.Now().UnixMilli() if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline && nextNameSource == "" { _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac) } else { _, err := s.db.Exec( `INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, name_source, created_at, updated_at) VALUES (?, ?, ?, ?, '', ?, ?, ?, ?) ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name, device_type=excluded.device_type, notify_offline=excluded.notify_offline, name_source=excluded.name_source, updated_at=excluded.updated_at`, mac, nextIcon, nextName, nextType, nextNotifyOffline, nextNameSource, now, now, ) if err != nil { writeError(w, http.StatusInternalServerError, "db_error", err.Error()) return } } // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices. if s.pollNow != nil { s.pollNow() } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType, "notifyOffline": nextNotifyOffline, "nameSource": nextNameSource, }) } // handleDeviceOverrideGet: devuelve el override actual de un dispositivo. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) { mac := macaddr.Normalize(r.PathValue("mac")) if mac == "" { writeError(w, http.StatusBadRequest, "invalid_mac") return } var icon, name, deviceType, banned sql.NullString var notifyOffline bool var nameSource string row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac) if err := row.Scan(&icon, &name, &deviceType, &banned, ¬ifyOffline, &nameSource); err != nil && err != sql.ErrNoRows { writeError(w, http.StatusInternalServerError, "db_error", err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{ "mac": mac, "icon": icon.String, "name": name.String, "type": deviceType.String, "bannedBands": banned.String, "notifyOffline": notifyOffline, "nameSource": nameSource, }) } // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437). func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) { var body struct { Bands []string `json:"bands"` } if st := readJSONBody(w, r, &body); st != 0 { writeBodyError(w, st, "invalid_body", "body JSON inválido") return } _ = body writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437") } // handleDeviceDelete: borra un cliente del registro device_seen (#1145, // retención indefinida con control explícito). Si el cliente sigue viéndose // en vivo, el siguiente ciclo del poller lo vuelve a dar de alta: borrar // elimina el recuerdo, no el equipo físico (la UI lo documenta en el // diálogo de confirmación). func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) { raw := strings.TrimSpace(r.PathValue("mac")) mac := strings.ToUpper(strings.ReplaceAll(raw, "-", ":")) if mac == "" { writeError(w, http.StatusBadRequest, "invalid_input", "missing mac") return } // BDs legadas pueden guardar la MAC sin normalizar (con guiones): se // borran ambas formas (#1145). res, err := s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?", mac, raw) if err != nil { writeError(w, http.StatusInternalServerError, "storage_error", "") return } // #1278: lápida. Sin ella, la siguiente fuente que reporte la MAC como // online (una entrada cacheada del AP, un colector) la re-daba de alta y // el borrado "no funcionaba". if norm := macaddr.Normalize(raw); norm != "" { if err := s.db.AddDeletedClient(norm); err != nil { writeError(w, http.StatusInternalServerError, "storage_error", "") return } } if n, _ := res.RowsAffected(); n == 0 { writeError(w, http.StatusNotFound, "not_found", "") return } w.WriteHeader(http.StatusNoContent) }