feat: split camera credentials and persist profiles (#50)

This commit is contained in:
QiuSW
2026-08-13 12:12:19 +08:00
parent 7523dfb1d6
commit 1a632649f3
16 changed files with 359 additions and 54 deletions
@@ -9,6 +9,7 @@ import (
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
@@ -82,9 +83,32 @@ func (c *HTTPClient) Profiles(ctx context.Context, address string, credential Cr
if err != nil {
return nil, err
}
profiles[i].StreamURI, err = normalizeStreamURI(deviceEndpoint, profiles[i].StreamURI)
if err != nil {
return nil, err
}
}
return profiles, nil
}
func normalizeStreamURI(deviceEndpoint, streamURI string) (string, error) {
device, err := url.Parse(deviceEndpoint)
if err != nil || device.Hostname() == "" {
return "", fmt.Errorf("invalid ONVIF address")
}
stream, err := url.Parse(streamURI)
if err != nil || stream.Scheme != "rtsp" || stream.Host == "" || stream.User != nil {
return "", fmt.Errorf("invalid RTSP stream URI")
}
if !strings.EqualFold(stream.Hostname(), device.Hostname()) {
port := stream.Port()
stream.Host = device.Hostname()
if port != "" {
stream.Host = net.JoinHostPort(device.Hostname(), port)
}
}
return stream.String(), nil
}
func (c *HTTPClient) soap(ctx context.Context, endpoint string, credential Credential, body string) ([]byte, error) {
return c.soapAttempt(ctx, endpoint, credential, body, "")
}
@@ -43,7 +43,8 @@ func TestProfilesDiscoversMediaServiceAndUsesDigest(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(profiles) != 1 || profiles[0].Width != 1920 || profiles[0].StreamURI != "rtsp://camera.invalid/live" {
serverURL, _ := url.Parse(server.URL)
if len(profiles) != 1 || profiles[0].Width != 1920 || profiles[0].StreamURI != "rtsp://"+serverURL.Hostname()+"/live" {
t.Fatalf("profiles=%#v", profiles)
}
if digestRequests.Load() != 2 {
@@ -80,6 +81,19 @@ func TestNormalizeServiceEndpoint(t *testing.T) {
}
}
func TestNormalizeStreamURI(t *testing.T) {
got, err := normalizeStreamURI("http://192.0.2.10:80/onvif/device_service", "rtsp://unusable.local:8554/live/main?channel=1")
if err != nil || got != "rtsp://192.0.2.10:8554/live/main?channel=1" {
t.Fatalf("got=%q err=%v", got, err)
}
if _, err := normalizeStreamURI("http://camera.local/onvif", "rtsp://user:pass@camera.local/live"); err == nil {
t.Fatal("credential stream URI accepted")
}
if _, err := normalizeStreamURI("http://camera.local/onvif", "http://camera.local/live"); err == nil {
t.Fatal("non-RTSP URI accepted")
}
}
func TestRejectUnsupportedDigestChallenge(t *testing.T) {
for _, challenge := range []string{
`Digest realm="camera", nonce="n", algorithm=SHA-512, qop="auth"`,
@@ -0,0 +1,25 @@
package admission
const MigrationSQL = `
CREATE TABLE IF NOT EXISTS sense_admission_results (
device_id TEXT PRIMARY KEY REFERENCES sense_devices(id),
address TEXT NOT NULL,
status TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
checked_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS sense_admission_profiles (
device_id TEXT NOT NULL REFERENCES sense_devices(id),
token TEXT NOT NULL,
name TEXT NOT NULL,
width INTEGER NOT NULL,
height INTEGER NOT NULL,
encoding TEXT NOT NULL,
stream_uri TEXT NOT NULL,
kind TEXT NOT NULL,
verification_status TEXT NOT NULL,
verification_latency_ms BIGINT NOT NULL DEFAULT 0,
verification_detail TEXT NOT NULL DEFAULT '',
PRIMARY KEY(device_id, token)
);
`
+28 -19
View File
@@ -5,7 +5,6 @@ import (
"fmt"
"sort"
"strings"
"sync"
"time"
"yovision.local/sense/app/sense/adapters/onvif"
@@ -37,13 +36,16 @@ type Service struct {
rtsp rtsp.Verifier
discoveryIP string
discoveryTimeout time.Duration
mu sync.RWMutex
results map[string]Result
store Store
now func() time.Time
}
func NewService(client onvif.Client, verifier rtsp.Verifier, discoveryIP string) *Service {
return &Service{onvif: client, rtsp: verifier, discoveryIP: discoveryIP, discoveryTimeout: 3 * time.Second, results: map[string]Result{}, now: time.Now}
func NewService(client onvif.Client, verifier rtsp.Verifier, discoveryIP string, stores ...Store) *Service {
var store Store = NewMemoryStore()
if len(stores) > 0 && stores[0] != nil {
store = stores[0]
}
return &Service{onvif: client, rtsp: verifier, discoveryIP: discoveryIP, discoveryTimeout: 3 * time.Second, store: store, now: time.Now}
}
func (s *Service) Discover(ctx context.Context) ([]string, error) {
if strings.TrimSpace(s.discoveryIP) == "" {
@@ -52,21 +54,25 @@ func (s *Service) Discover(ctx context.Context) ([]string, error) {
return onvif.Discover(ctx, s.discoveryIP, s.discoveryTimeout)
}
func (s *Service) Probe(ctx context.Context, actor identity.Principal, deviceID, address string) (Result, error) {
credential, err := device.ReadCredential(ctx, deviceID)
onvifCredential, err := device.ReadONVIFCredential(ctx, deviceID)
if err != nil {
return Result{}, fmt.Errorf("credential_required")
}
profiles, err := s.onvif.Profiles(ctx, address, onvif.Credential{Username: credential.Username, Password: credential.Password})
profiles, err := s.onvif.Profiles(ctx, address, onvif.Credential{Username: onvifCredential.Username, Password: onvifCredential.Password})
if err != nil {
status, detail := classify(err)
result := Result{DeviceID: deviceID, Address: address, Status: status, Detail: detail, CheckedAt: s.now().UTC()}
s.save(result)
_ = s.store.Save(ctx, result)
identity.RecordAudit(ctx, actor.UserID, "admission.probe", deviceID, "failure", map[string]any{"status": status})
return result, nil
}
rtspCredential, err := device.ReadRTSPCredential(ctx, deviceID)
if err != nil {
return Result{}, fmt.Errorf("rtsp_credential_required")
}
items := make([]Profile, 0, len(profiles))
for _, profile := range profiles {
verification, verifyErr := s.rtsp.Verify(ctx, profile.StreamURI, rtsp.Credential{Username: credential.Username, Password: credential.Password})
verification, verifyErr := s.rtsp.Verify(ctx, profile.StreamURI, rtsp.Credential{Username: rtspCredential.Username, Password: rtspCredential.Password})
if verifyErr != nil {
verification = rtsp.Result{Status: "failed", Detail: "视频地址格式不正确"}
}
@@ -89,20 +95,23 @@ func (s *Service) Probe(ctx context.Context, actor identity.Principal, deviceID,
}
}
result := Result{DeviceID: deviceID, Address: address, Status: status, Detail: detail, Profiles: items, CheckedAt: s.now().UTC()}
s.save(result)
if err := s.store.Save(ctx, result); err != nil {
return Result{}, err
}
for _, item := range items {
if item.Verification.Status == "ready" {
if err := device.MarkActive(ctx, deviceID); err != nil {
return Result{}, err
}
break
}
}
identity.RecordAudit(ctx, actor.UserID, "admission.probe", deviceID, "success", map[string]any{"profile_count": len(items), "status": status})
return result, nil
}
func (s *Service) Get(deviceID string) (Result, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
value, ok := s.results[deviceID]
return value, ok
}
func (s *Service) save(result Result) {
s.mu.Lock()
defer s.mu.Unlock()
s.results[result.DeviceID] = result
value, err := s.store.Get(context.Background(), deviceID)
return value, err == nil
}
func classify(err error) (string, string) {
value := strings.ToLower(err.Error())
@@ -22,6 +22,20 @@ type fakeRTSP struct{}
func (fakeRTSP) Verify(context.Context, string, rtsp.Credential) (rtsp.Result, error) {
return rtsp.Result{Status: "ready"}, nil
}
type credentialCapturingONVIF struct{ got onvif.Credential }
func (f *credentialCapturingONVIF) Profiles(_ context.Context, _ string, credential onvif.Credential) ([]onvif.Profile, error) {
f.got = credential
return fakeONVIF{}.Profiles(context.Background(), "", credential)
}
type credentialCapturingRTSP struct{ got rtsp.Credential }
func (f *credentialCapturingRTSP) Verify(_ context.Context, _ string, credential rtsp.Credential) (rtsp.Result, error) {
f.got = credential
return rtsp.Result{Status: "ready"}, nil
}
func TestProbeProfilesWithoutCredentialURI(t *testing.T) {
vault, err := device.NewCredentialVault(base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef")), false)
if err != nil {
@@ -44,3 +58,40 @@ func TestProbeProfilesWithoutCredentialURI(t *testing.T) {
t.Fatalf("result=%#v err=%v", result, err)
}
}
func TestProbeUsesSeparateCredentialsPersistsProfilesAndActivatesDevice(t *testing.T) {
vault, err := device.NewCredentialVault(base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef")), false)
if err != nil {
t.Fatal(err)
}
deviceStore := device.NewMemoryStore()
deviceService := device.NewService(deviceStore, vault)
device.NewModule(deviceService).Register(platform.NewApp(platform.Config{DatabaseMode: platform.DatabaseModeMemory}, nil, nil))
item, err := deviceService.Create(context.Background(), identity.Principal{}, "camera", "gate", device.ModalityVideo, nil)
if err != nil {
t.Fatal(err)
}
if _, err = deviceService.SetCredentials(context.Background(), identity.Principal{}, item.ID, "onvif-user", "onvif-password", false, "rtsp-user", "rtsp-password"); err != nil {
t.Fatal(err)
}
onvifClient := &credentialCapturingONVIF{}
rtspVerifier := &credentialCapturingRTSP{}
store := NewMemoryStore()
service := NewService(onvifClient, rtspVerifier, "", store)
result, err := service.Probe(context.Background(), identity.Principal{}, item.ID, "http://camera.invalid/onvif/device_service")
if err != nil {
t.Fatal(err)
}
if onvifClient.got.Username != "onvif-user" || rtspVerifier.got.Username != "rtsp-user" {
t.Fatal("credentials were not separated")
}
restarted := NewService(onvifClient, rtspVerifier, "", store)
persisted, ok := restarted.Get(item.ID)
if !ok || len(persisted.Profiles) != len(result.Profiles) {
t.Fatalf("persisted=%#v", persisted)
}
updated, err := deviceService.Get(context.Background(), item.ID)
if err != nil || updated.Status != device.StatusActive {
t.Fatalf("device=%#v err=%v", updated, err)
}
}
+85
View File
@@ -0,0 +1,85 @@
package admission
import (
"context"
"database/sql"
"errors"
"sync"
)
var ErrNotFound = errors.New("admission result not found")
type Store interface {
Save(context.Context, Result) error
Get(context.Context, string) (Result, error)
}
type MemoryStore struct {
mu sync.RWMutex
results map[string]Result
}
func NewMemoryStore() *MemoryStore { return &MemoryStore{results: map[string]Result{}} }
func (s *MemoryStore) Save(_ context.Context, result Result) error {
s.mu.Lock()
defer s.mu.Unlock()
s.results[result.DeviceID] = result
return nil
}
func (s *MemoryStore) Get(_ context.Context, deviceID string) (Result, error) {
s.mu.RLock()
defer s.mu.RUnlock()
result, ok := s.results[deviceID]
if !ok {
return Result{}, ErrNotFound
}
return result, nil
}
type PostgresStore struct{ database *sql.DB }
func NewPostgresStore(database *sql.DB) *PostgresStore { return &PostgresStore{database: database} }
func (s *PostgresStore) Save(ctx context.Context, result Result) error {
tx, err := s.database.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.ExecContext(ctx, `INSERT INTO sense_admission_results(device_id,address,status,detail,checked_at) VALUES($1,$2,$3,$4,$5) ON CONFLICT(device_id) DO UPDATE SET address=EXCLUDED.address,status=EXCLUDED.status,detail=EXCLUDED.detail,checked_at=EXCLUDED.checked_at`, result.DeviceID, result.Address, result.Status, result.Detail, result.CheckedAt)
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `DELETE FROM sense_admission_profiles WHERE device_id=$1`, result.DeviceID); err != nil {
return err
}
for _, profile := range result.Profiles {
_, err = tx.ExecContext(ctx, `INSERT INTO sense_admission_profiles(device_id,token,name,width,height,encoding,stream_uri,kind,verification_status,verification_latency_ms,verification_detail) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, result.DeviceID, profile.Token, profile.Name, profile.Width, profile.Height, profile.Encoding, profile.StreamURI, profile.Kind, profile.Verification.Status, profile.Verification.LatencyMS, profile.Verification.Detail)
if err != nil {
return err
}
}
return tx.Commit()
}
func (s *PostgresStore) Get(ctx context.Context, deviceID string) (Result, error) {
var result Result
err := s.database.QueryRowContext(ctx, `SELECT device_id,address,status,detail,checked_at FROM sense_admission_results WHERE device_id=$1`, deviceID).Scan(&result.DeviceID, &result.Address, &result.Status, &result.Detail, &result.CheckedAt)
if errors.Is(err, sql.ErrNoRows) {
return Result{}, ErrNotFound
}
if err != nil {
return Result{}, err
}
rows, err := s.database.QueryContext(ctx, `SELECT token,name,width,height,encoding,stream_uri,kind,verification_status,verification_latency_ms,verification_detail FROM sense_admission_profiles WHERE device_id=$1 ORDER BY width*height DESC`, deviceID)
if err != nil {
return Result{}, err
}
defer rows.Close()
for rows.Next() {
var profile Profile
if err := rows.Scan(&profile.Token, &profile.Name, &profile.Width, &profile.Height, &profile.Encoding, &profile.StreamURI, &profile.Kind, &profile.Verification.Status, &profile.Verification.LatencyMS, &profile.Verification.Detail); err != nil {
return Result{}, err
}
result.Profiles = append(result.Profiles, profile)
}
return result, rows.Err()
}
@@ -16,6 +16,9 @@ var activeService atomic.Pointer[Service]
// ReadCredential is an internal adapter port. Credentials must never be
// returned from HTTP handlers, logged, or placed in a URL.
func ReadCredential(ctx context.Context, id string) (Credential, error) {
return ReadONVIFCredential(ctx, id)
}
func ReadONVIFCredential(ctx context.Context, id string) (Credential, error) {
service := activeService.Load()
if service == nil {
return Credential{}, fmt.Errorf("device service is not ready")
@@ -30,3 +33,38 @@ func ReadCredential(ctx context.Context, id string) (Credential, error) {
username, password, err := service.vault.Decrypt(item.CredentialCiphertext)
return Credential{Username: username, Password: password}, err
}
func ReadRTSPCredential(ctx context.Context, id string) (Credential, error) {
service := activeService.Load()
if service == nil {
return Credential{}, fmt.Errorf("device service is not ready")
}
item, err := service.store.Get(ctx, id)
if err != nil {
return Credential{}, err
}
if len(item.RTSPCredentialCiphertext) == 0 {
return Credential{}, fmt.Errorf("RTSP credential is not configured")
}
username, password, err := service.vault.Decrypt(item.RTSPCredentialCiphertext)
return Credential{Username: username, Password: password}, err
}
func MarkActive(ctx context.Context, id string) error {
service := activeService.Load()
if service == nil {
return fmt.Errorf("device service is not ready")
}
item, err := service.store.Get(ctx, id)
if err != nil {
return err
}
if item.Status == StatusDisabled || item.Status == StatusActive {
return nil
}
expected := item.Version
item.Status = StatusActive
item.Version++
item.UpdatedAt = service.now().UTC()
return service.store.Update(ctx, item, expected)
}
+18 -3
View File
@@ -78,15 +78,30 @@ func (m *Module) update(w http.ResponseWriter, r *http.Request) {
}
func (m *Module) credential(w http.ResponseWriter, r *http.Request) {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
Username string `json:"username"`
Password string `json:"password"`
ONVIFUsername string `json:"onvif_username"`
ONVIFPassword string `json:"onvif_password"`
RTSPSameAsONVIF *bool `json:"rtsp_same_as_onvif"`
RTSPUsername string `json:"rtsp_username"`
RTSPPassword string `json:"rtsp_password"`
}
if err := platform.DecodeJSON(r, &req); err != nil {
platform.WriteError(w, err)
return
}
actor, _ := identity.PrincipalFromContext(r.Context())
item, err := m.service.SetCredential(r.Context(), actor, r.PathValue("id"), req.Username, req.Password)
if req.ONVIFUsername == "" {
req.ONVIFUsername = req.Username
}
if req.ONVIFPassword == "" {
req.ONVIFPassword = req.Password
}
rtspSame := true
if req.RTSPSameAsONVIF != nil {
rtspSame = *req.RTSPSameAsONVIF
}
item, err := m.service.SetCredentials(r.Context(), actor, r.PathValue("id"), req.ONVIFUsername, req.ONVIFPassword, rtspSame, req.RTSPUsername, req.RTSPPassword)
if err != nil {
writeDeviceError(w, err)
return
@@ -1,3 +1,5 @@
package device
const MigrationSQL = `CREATE TABLE IF NOT EXISTS sense_devices(id TEXT PRIMARY KEY,name TEXT NOT NULL,location TEXT NOT NULL DEFAULT '',modality TEXT NOT NULL,capabilities TEXT NOT NULL DEFAULT '',status TEXT NOT NULL,adapter_status TEXT NOT NULL,credential_ciphertext BYTEA NULL,version BIGINT NOT NULL,created_at TIMESTAMPTZ NOT NULL,updated_at TIMESTAMPTZ NOT NULL);CREATE INDEX IF NOT EXISTS sense_devices_created_idx ON sense_devices(created_at DESC);`
const SplitCredentialMigrationSQL = `ALTER TABLE sense_devices ADD COLUMN IF NOT EXISTS rtsp_credential_ciphertext BYTEA NULL;ALTER TABLE sense_devices ADD COLUMN IF NOT EXISTS rtsp_credential_same_as_onvif BOOLEAN NOT NULL DEFAULT TRUE;UPDATE sense_devices SET rtsp_credential_ciphertext=credential_ciphertext WHERE rtsp_credential_ciphertext IS NULL AND credential_ciphertext IS NOT NULL AND rtsp_credential_same_as_onvif=TRUE;`
+28 -4
View File
@@ -34,7 +34,7 @@ func (s *Service) Create(ctx context.Context, actor identity.Principal, name, lo
adapter = AdapterReady
}
now := s.now().UTC()
item := Device{ID: newID(), Name: name, Location: strings.TrimSpace(location), Modality: modality, Capabilities: capabilities, Status: StatusPending, AdapterStatus: adapter, Version: 1, CreatedAt: now, UpdatedAt: now}
item := Device{ID: newID(), Name: name, Location: strings.TrimSpace(location), Modality: modality, Capabilities: capabilities, Status: StatusPending, AdapterStatus: adapter, RTSPCredentialSameAsONVIF: true, Version: 1, CreatedAt: now, UpdatedAt: now}
if err := s.store.Create(ctx, item); err != nil {
return Device{}, err
}
@@ -45,7 +45,9 @@ func (s *Service) Get(ctx context.Context, id string) (Device, error) {
item, err := s.store.Get(ctx, id)
if err == nil {
item.CredentialConfigured = len(item.CredentialCiphertext) > 0
item.RTSPCredentialConfigured = len(item.RTSPCredentialCiphertext) > 0
item.CredentialCiphertext = nil
item.RTSPCredentialCiphertext = nil
}
return item, err
}
@@ -53,6 +55,7 @@ func (s *Service) List(ctx context.Context, filter ListFilter) (Page, error) {
page, err := s.store.List(ctx, filter)
for i := range page.Items {
page.Items[i].CredentialCiphertext = nil
page.Items[i].RTSPCredentialCiphertext = nil
}
return page, err
}
@@ -74,31 +77,50 @@ func (s *Service) Update(ctx context.Context, actor identity.Principal, id, name
}
identity.RecordAudit(ctx, actor.UserID, "device.update", id, "success", map[string]any{"version": item.Version})
item.CredentialConfigured = len(item.CredentialCiphertext) > 0
item.RTSPCredentialConfigured = len(item.RTSPCredentialCiphertext) > 0
item.CredentialCiphertext = nil
item.RTSPCredentialCiphertext = nil
return item, nil
}
func (s *Service) SetCredential(ctx context.Context, actor identity.Principal, id, username, password string) (Device, error) {
if strings.TrimSpace(username) == "" || password == "" {
return s.SetCredentials(ctx, actor, id, username, password, true, "", "")
}
func (s *Service) SetCredentials(ctx context.Context, actor identity.Principal, id, onvifUsername, onvifPassword string, rtspSame bool, rtspUsername, rtspPassword string) (Device, error) {
if strings.TrimSpace(onvifUsername) == "" || onvifPassword == "" {
return Device{}, fmt.Errorf("用户名和密码不能为空")
}
if !rtspSame && (strings.TrimSpace(rtspUsername) == "" || rtspPassword == "") {
return Device{}, fmt.Errorf("RTSP 用户名和密码不能为空")
}
item, err := s.store.Get(ctx, id)
if err != nil {
return Device{}, err
}
ciphertext, err := s.vault.Encrypt(username, password)
ciphertext, err := s.vault.Encrypt(onvifUsername, onvifPassword)
if err != nil {
return Device{}, err
}
expected := item.Version
item.CredentialCiphertext = ciphertext
item.RTSPCredentialSameAsONVIF = rtspSame
if rtspSame {
item.RTSPCredentialCiphertext = append([]byte(nil), ciphertext...)
} else {
item.RTSPCredentialCiphertext, err = s.vault.Encrypt(rtspUsername, rtspPassword)
if err != nil {
return Device{}, err
}
}
item.CredentialConfigured = true
item.RTSPCredentialConfigured = true
item.Version++
item.UpdatedAt = s.now().UTC()
if err := s.store.Update(ctx, item, expected); err != nil {
return Device{}, err
}
identity.RecordAudit(ctx, actor.UserID, "device.credential.update", id, "success", map[string]any{"configured": true})
identity.RecordAudit(ctx, actor.UserID, "device.credential.update", id, "success", map[string]any{"configured": true, "rtsp_same_as_onvif": rtspSame})
item.CredentialCiphertext = nil
item.RTSPCredentialCiphertext = nil
return item, nil
}
func (s *Service) Disable(ctx context.Context, actor identity.Principal, id string, expected int64) (Device, error) {
@@ -114,7 +136,9 @@ func (s *Service) Disable(ctx context.Context, actor identity.Principal, id stri
}
identity.RecordAudit(ctx, actor.UserID, "device.disable", id, "success", nil)
item.CredentialConfigured = len(item.CredentialCiphertext) > 0
item.RTSPCredentialConfigured = len(item.RTSPCredentialCiphertext) > 0
item.CredentialCiphertext = nil
item.RTSPCredentialCiphertext = nil
return item, nil
}
func newID() string {
+6 -5
View File
@@ -89,22 +89,23 @@ type PostgresStore struct{ database *sql.DB }
func NewPostgresStore(database *sql.DB) *PostgresStore { return &PostgresStore{database: database} }
func (s *PostgresStore) Create(ctx context.Context, item Device) error {
_, err := s.database.ExecContext(ctx, `INSERT INTO sense_devices(id,name,location,modality,capabilities,status,adapter_status,credential_ciphertext,version,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, item.ID, item.Name, item.Location, item.Modality, strings.Join(item.Capabilities, ","), item.Status, item.AdapterStatus, item.CredentialCiphertext, item.Version, item.CreatedAt, item.UpdatedAt)
_, err := s.database.ExecContext(ctx, `INSERT INTO sense_devices(id,name,location,modality,capabilities,status,adapter_status,credential_ciphertext,rtsp_credential_ciphertext,rtsp_credential_same_as_onvif,version,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`, item.ID, item.Name, item.Location, item.Modality, strings.Join(item.Capabilities, ","), item.Status, item.AdapterStatus, item.CredentialCiphertext, item.RTSPCredentialCiphertext, item.RTSPCredentialSameAsONVIF, item.Version, item.CreatedAt, item.UpdatedAt)
return err
}
func (s *PostgresStore) Get(ctx context.Context, id string) (Device, error) {
var item Device
var capabilities string
err := s.database.QueryRowContext(ctx, `SELECT id,name,location,modality,capabilities,status,adapter_status,credential_ciphertext,version,created_at,updated_at FROM sense_devices WHERE id=$1`, id).Scan(&item.ID, &item.Name, &item.Location, &item.Modality, &capabilities, &item.Status, &item.AdapterStatus, &item.CredentialCiphertext, &item.Version, &item.CreatedAt, &item.UpdatedAt)
err := s.database.QueryRowContext(ctx, `SELECT id,name,location,modality,capabilities,status,adapter_status,credential_ciphertext,rtsp_credential_ciphertext,rtsp_credential_same_as_onvif,version,created_at,updated_at FROM sense_devices WHERE id=$1`, id).Scan(&item.ID, &item.Name, &item.Location, &item.Modality, &capabilities, &item.Status, &item.AdapterStatus, &item.CredentialCiphertext, &item.RTSPCredentialCiphertext, &item.RTSPCredentialSameAsONVIF, &item.Version, &item.CreatedAt, &item.UpdatedAt)
if errors.Is(err, sql.ErrNoRows) {
return Device{}, ErrNotFound
}
item.Capabilities = splitCapabilities(capabilities)
item.CredentialConfigured = len(item.CredentialCiphertext) > 0
item.RTSPCredentialConfigured = len(item.RTSPCredentialCiphertext) > 0
return item, err
}
func (s *PostgresStore) Update(ctx context.Context, item Device, expected int64) error {
result, err := s.database.ExecContext(ctx, `UPDATE sense_devices SET name=$2,location=$3,modality=$4,capabilities=$5,status=$6,adapter_status=$7,credential_ciphertext=$8,version=$9,updated_at=$10 WHERE id=$1 AND version=$11`, item.ID, item.Name, item.Location, item.Modality, strings.Join(item.Capabilities, ","), item.Status, item.AdapterStatus, item.CredentialCiphertext, item.Version, item.UpdatedAt, expected)
result, err := s.database.ExecContext(ctx, `UPDATE sense_devices SET name=$2,location=$3,modality=$4,capabilities=$5,status=$6,adapter_status=$7,credential_ciphertext=$8,rtsp_credential_ciphertext=$9,rtsp_credential_same_as_onvif=$10,version=$11,updated_at=$12 WHERE id=$1 AND version=$13`, item.ID, item.Name, item.Location, item.Modality, strings.Join(item.Capabilities, ","), item.Status, item.AdapterStatus, item.CredentialCiphertext, item.RTSPCredentialCiphertext, item.RTSPCredentialSameAsONVIF, item.Version, item.UpdatedAt, expected)
if err != nil {
return err
}
@@ -121,7 +122,7 @@ func (s *PostgresStore) List(ctx context.Context, filter ListFilter) (Page, erro
if err := s.database.QueryRowContext(ctx, `SELECT count(*) FROM sense_devices WHERE name ILIKE $1 OR location ILIKE $1`, keyword).Scan(&total); err != nil {
return Page{}, err
}
rows, err := s.database.QueryContext(ctx, `SELECT id,name,location,modality,capabilities,status,adapter_status,(credential_ciphertext IS NOT NULL),version,created_at,updated_at FROM sense_devices WHERE name ILIKE $1 OR location ILIKE $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`, keyword, size, (page-1)*size)
rows, err := s.database.QueryContext(ctx, `SELECT id,name,location,modality,capabilities,status,adapter_status,(credential_ciphertext IS NOT NULL),(rtsp_credential_ciphertext IS NOT NULL),rtsp_credential_same_as_onvif,version,created_at,updated_at FROM sense_devices WHERE name ILIKE $1 OR location ILIKE $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`, keyword, size, (page-1)*size)
if err != nil {
return Page{}, err
}
@@ -130,7 +131,7 @@ func (s *PostgresStore) List(ctx context.Context, filter ListFilter) (Page, erro
for rows.Next() {
var item Device
var caps string
if err := rows.Scan(&item.ID, &item.Name, &item.Location, &item.Modality, &caps, &item.Status, &item.AdapterStatus, &item.CredentialConfigured, &item.Version, &item.CreatedAt, &item.UpdatedAt); err != nil {
if err := rows.Scan(&item.ID, &item.Name, &item.Location, &item.Modality, &caps, &item.Status, &item.AdapterStatus, &item.CredentialConfigured, &item.RTSPCredentialConfigured, &item.RTSPCredentialSameAsONVIF, &item.Version, &item.CreatedAt, &item.UpdatedAt); err != nil {
return Page{}, err
}
item.Capabilities = splitCapabilities(caps)
+15 -12
View File
@@ -13,18 +13,21 @@ const (
)
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Location string `json:"location"`
Modality string `json:"modality"`
Capabilities []string `json:"capabilities"`
Status string `json:"status"`
AdapterStatus string `json:"adapter_status"`
CredentialConfigured bool `json:"credential_configured"`
CredentialCiphertext []byte `json:"-"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
Name string `json:"name"`
Location string `json:"location"`
Modality string `json:"modality"`
Capabilities []string `json:"capabilities"`
Status string `json:"status"`
AdapterStatus string `json:"adapter_status"`
CredentialConfigured bool `json:"credential_configured"`
CredentialCiphertext []byte `json:"-"`
RTSPCredentialConfigured bool `json:"rtsp_credential_configured"`
RTSPCredentialSameAsONVIF bool `json:"rtsp_credential_same_as_onvif"`
RTSPCredentialCiphertext []byte `json:"-"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ListFilter struct {
+8 -1
View File
@@ -11,7 +11,14 @@ import (
func init() {
registerModule(func(app *platform.App) error {
service := admission.NewService(onvif.NewHTTPClient(8*time.Second), rtsp.NetVerifier{Timeout: 5 * time.Second}, os.Getenv("SENSE_ONVIF_DISCOVERY_IP"))
var store admission.Store
if app.Config().DatabaseMode == platform.DatabaseModeMemory {
store = admission.NewMemoryStore()
} else {
store = admission.NewPostgresStore(app.Database())
}
app.RegisterMigration(platform.Migration{Version: 2026081302, Name: "sense_admission_profiles", SQL: admission.MigrationSQL})
service := admission.NewService(onvif.NewHTTPClient(8*time.Second), rtsp.NetVerifier{Timeout: 5 * time.Second}, os.Getenv("SENSE_ONVIF_DISCOVERY_IP"), store)
admission.NewModule(service).Register(app)
return nil
})
+1
View File
@@ -20,6 +20,7 @@ func init() {
store = device.NewPostgresStore(app.Database())
}
app.RegisterMigration(platform.Migration{Version: 2026081202, Name: "sense_device", SQL: device.MigrationSQL})
app.RegisterMigration(platform.Migration{Version: 2026081301, Name: "sense_device_split_credentials", SQL: device.SplitCredentialMigrationSQL})
device.NewModule(device.NewService(store, vault)).Register(app)
return nil
})