configdb

package
v0.0.0-...-b7e086b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LoginModeCookie               = "Cookie"
	LoginModeBearerToken          = "BearerToken"
	LoginModeCookieAndBearerToken = "CookieAndBearerToken"
)
View Source
const KeyMain = "main"
View Source
const SessionCookie = "session"

SYNC-CYCLOPS-SESSION-COOKIE

Variables

View Source
var AllVariables []VariableDef
View Source
var AllVariablesByKey map[VariableKey]*VariableDef

Functions

func GuessDefaultVariableValue

func GuessDefaultVariableValue(v VariableKey) string

Guess a default variable value, or return an empty string if we can't make a good guess

func IsValidPermission

func IsValidPermission(p string) bool

func Migrations

func Migrations(log log.Log) []migration.Migrator

func NormalizeUsername

func NormalizeUsername(username string) string

func RestartNeeded

func RestartNeeded(c1, c2 *ConfigJSON) bool

func ValidateConfig

func ValidateConfig(c *ConfigJSON) error

Returns an error if there is anything invalid about the config, or nil if everything is OK

func ValidateRecordingConfig

func ValidateRecordingConfig(isDefaults bool, c *RecordingJSON) error

func ValidateVariable

func ValidateVariable(v VariableKey, value string) error

func VariableSetNeedsRestart

func VariableSetNeedsRestart(v VariableKey) bool

If true, then the system must be restarted after setting this variable

Types

type BaseModel

type BaseModel struct {
	ID int64 `gorm:"primaryKey" json:"id"`
}

BaseModel is our base class for a GORM model. The default GORM Model uses int, but we prefer int64

type Camera

type Camera struct {
	BaseModel
	Model            string      `json:"model"`                                // eg HikVision (actually CameraModels enum)
	Name             string      `json:"name"`                                 // Friendly name
	Host             string      `json:"host"`                                 // Hostname such as 192.168.1.33
	Port             int         `json:"port" gorm:"default:null"`             // if 0, then default is 554
	Username         string      `json:"username"`                             // RTSP username
	Password         string      `json:"password"`                             // RTSP password
	HighResURLSuffix string      `json:"highResURLSuffix" gorm:"default:null"` // eg Streaming/Channels/101 for HikVision. Can leave blank if Model is a known type.
	LowResURLSuffix  string      `json:"lowResURLSuffix" gorm:"default:null"`  // eg Streaming/Channels/102 for HikVision. Can leave blank if Model is a known type.
	CreatedAt        dbh.IntTime `json:"createdAt" gorm:"autoCreateTime:milli"`
	UpdatedAt        dbh.IntTime `json:"updatedAt" gorm:"autoUpdateTime:milli"`

	// The long lived name is used to identify the camera in the storage archive.
	// If necessary, we can make this configurable.
	// At present, it is equal to the camera ID. But in future, we could allow
	// the user to override this. For example, if their system goes down, but their
	// archive is on another disk, and they want to restore all the cameras, and
	// still have the history intact, and matching up to the new (but same) cameras.
	// Or perhaps you have to replace a camera, but want to retain the logical identify.
	LongLivedName string `json:"longLivedName"`
}

SYNC-RECORD-CAMERA

func (*Camera) DeepEquals

func (c *Camera) DeepEquals(x *Camera) bool

func (*Camera) EqualsConnection

func (c *Camera) EqualsConnection(newCam *Camera) bool

Compare the current camera config against the new camera config, and return true if the connection details refer to the exact same camera host and config.

type ConfigDB

type ConfigDB struct {
	Log        log.Log
	DB         *gorm.DB
	PrivateKey wgtypes.Key
	PublicKey  wgtypes.Key
	// contains filtered or unexported fields
}

func NewConfigDB

func NewConfigDB(logger log.Log, dbFilename, explicitPrivateKey string) (*ConfigDB, error)

func (*ConfigDB) GenerateNewID

func (c *ConfigDB) GenerateNewID(tx *gorm.DB, key string) (int64, error)

Generate a new ID from the 'next_id' table in the database

func (*ConfigDB) GetConfig

func (c *ConfigDB) GetConfig() ConfigJSON

func (*ConfigDB) GetUser

func (c *ConfigDB) GetUser(r *http.Request) *User

Returns the user or nil

func (*ConfigDB) GetUserID

func (c *ConfigDB) GetUserID(r *http.Request, allowBasic bool) int64

Returns the user id, or zero. You should only set allowBasic to true if this is a rate limited endpoint.

func (*ConfigDB) GuessDefaultVariables

func (c *ConfigDB) GuessDefaultVariables() error

Guess reasonable defaults for mandatory system variables that are not set

func (*ConfigDB) Login

func (c *ConfigDB) Login(w http.ResponseWriter, r *http.Request)

func (*ConfigDB) LoginInternal

func (c *ConfigDB) LoginInternal(w http.ResponseWriter, userID int64, expiresAt time.Time, mode string)

func (*ConfigDB) Logout

func (c *ConfigDB) Logout(w http.ResponseWriter, r *http.Request)

func (*ConfigDB) MustGetUserID

func (c *ConfigDB) MustGetUserID(w http.ResponseWriter, r *http.Request) int64

Returns the user id, or zero On failure, sends a 401 to 'w'

func (*ConfigDB) NumAdminUsers

func (c *ConfigDB) NumAdminUsers() (int, error)

func (*ConfigDB) PurgeExpiredSessions

func (c *ConfigDB) PurgeExpiredSessions()

func (*ConfigDB) SetConfig

func (c *ConfigDB) SetConfig(cfg ConfigJSON) (bool, error)

Return true if the system needs to be restarted for the config changes to take effect

type ConfigJSON

type ConfigJSON struct {
	Recording    RecordingJSON `json:"recording"`    // Recording settings. We aim to make some settings overridable per-camera, such as recording mode.
	TempFilePath string        `json:"tempFilePath"` // Temporary file path
	ArcServer    string        `json:"arcServer"`    // Arc server URL
	ArcApiKey    string        `json:"arcApiKey"`    // Arc API key
}

Root system config SYNC-SYSTEM-CONFIG-JSON

type Key

type Key struct {
	Name  string `gorm:"primaryKey"`
	Value string // normal (not URL-safe) base64 encoded (same as Wireguard)
}

type RecordInstruction

type RecordInstruction struct {
	BaseModel
	StartAt    dbh.IntTime `json:"startAt"`
	FinishAt   dbh.IntTime `json:"finishAt"`
	Resolution string      `json:"resolution" gorm:"default:null"` // One of defs.Resolution (LD or HD)
}

type RecordMode

type RecordMode string

What causes us to record video

const (
	RecordModeAlways      RecordMode = "always"
	RecordModeOnMovement  RecordMode = "movement"
	RecordModeOnDetection RecordMode = "detection"
)

type RecordingJSON

type RecordingJSON struct {
	Mode              RecordMode `json:"mode,omitempty"`
	Path              string     `json:"path,omitempty"`              // Root directory of fsv archive
	MaxStorageSize    string     `json:"maxStorageSize,omitempty"`    // Maximum storage with optional "gb", "mb", "tb" suffix. If no suffix, then bytes.
	RecordBeforeEvent int        `json:"recordBeforeEvent,omitempty"` // Record this many seconds before an event
	RecordAfterEvent  int        `json:"recordAfterEvent,omitempty"`  // Record this many seconds after an event
}

Recording config SYNC-SYSTEM-RECORDING-CONFIG-JSON

func (*RecordingJSON) RecordAfterEventDuration

func (r *RecordingJSON) RecordAfterEventDuration() time.Duration

func (*RecordingJSON) RecordBeforeEventDuration

func (r *RecordingJSON) RecordBeforeEventDuration() time.Duration

type Session

type Session struct {
	CreatedAt dbh.IntTime `gorm:"autoCreateTime:milli"`
	Key       []byte
	UserID    int64
	ExpiresAt dbh.IntTime `gorm:"default:null"`
}

type SystemConfig

type SystemConfig struct {
	Key   string `gorm:"primaryKey"`
	Value *dbh.JSONField[ConfigJSON]
}

type User

type User struct {
	BaseModel
	Username           string `json:"username"`
	UsernameNormalized string `json:"username_normalized"`
	Permissions        string `json:"permissions"`
	Name               string `json:"name" gorm:"default:null"`
	Password           []byte `json:"-" gorm:"default:null"`
}

SYNC-RECORD-USER

func (*User) HasPermission

func (u *User) HasPermission(p UserPermissions) bool

type UserPermissions

type UserPermissions string

UserPermissions are single characters that are present in the user's Permissions field

const (
	UserPermissionAdmin  UserPermissions = "a"
	UserPermissionViewer UserPermissions = "v"
)

type Variable

type Variable struct {
	Key   string `gorm:"primaryKey" json:"key"`
	Value string `json:"value"`
}

type VariableDef

type VariableDef struct {
	Key         VariableKey `json:"key"`
	Title       string      `json:"title"`       // eg "Permanent Storage Path"
	Explanation string      `json:"explanation"` // eg "Recordings that you want to keep forever are stored on Permanent Storage..."
	Required    bool        `json:"required"`    // True if the variable must be set before the system can run
	UIGroup     string      `json:"uiGroup"`     // Used to group UI elements together
	Type        string      `json:"type"`        // One of ["path", "text"]
}

VariableDef defines a system variable. This is used to drive the configuration UI.

type VariableKey

type VariableKey string

VariableKey is global configuration variable that can be set on the system

const (
	// SYNC-ALL-VARIABLES
	VarPermanentStoragePath   VariableKey = "PermanentStoragePath"
	VarRecentEventStoragePath VariableKey = "RecentEventStoragePath"
	VarTempFilePath           VariableKey = "TempFilePath"
	// The following 2 are here because I haven't figured out the authentication strategy yet.
	// How does a person authenticate from their home cyclops server to an Arc server?
	// It feels like it should be some kind of OAuth thing.
	VarArcServer VariableKey = "ArcServer"
	VarArcApiKey VariableKey = "ArcApiKey"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL