Documentation
¶
Overview ¶
Package api implements the RESTful HTTP API, Gin router configuration, WebSocket WebCodecs streaming, WHEP WebRTC negotiation, HLS segment endpoints, and Prometheus metrics handlers.
Index ¶
- func SetupRouter(h *Handler, auth registry.Authenticator, debug bool, corsOrigins []string) *gin.Engine
- type CameraInfo
- type ClientInfo
- type ClientTracker
- type Handler
- func (h *Handler) AddCamera(c *gin.Context)
- func (h *Handler) AddFolder(c *gin.Context)
- func (h *Handler) AddTag(c *gin.Context)
- func (h *Handler) AddUser(c *gin.Context)
- func (h *Handler) CleanupArchiveTrigger(_ *gin.Context)
- func (h *Handler) DeleteCamera(c *gin.Context)
- func (h *Handler) DeleteFolder(c *gin.Context)
- func (h *Handler) DeleteTag(c *gin.Context)
- func (h *Handler) DeleteUser(c *gin.Context)
- func (h *Handler) EditCamera(c *gin.Context)
- func (h *Handler) EditFolder(c *gin.Context)
- func (h *Handler) EditTag(c *gin.Context)
- func (h *Handler) EditUser(c *gin.Context)
- func (h *Handler) ExportBackupJSON(c *gin.Context)
- func (h *Handler) ExportCameraArchive(c *gin.Context)
- func (h *Handler) GetArchiveHLSPlaylist(c *gin.Context)
- func (h *Handler) GetArchiveHLSSegment(c *gin.Context)
- func (h *Handler) GetCameraArchive(c *gin.Context)
- func (h *Handler) GetCameras(c *gin.Context)
- func (h *Handler) GetFolders(c *gin.Context)
- func (h *Handler) GetHLSPlaylist(c *gin.Context)
- func (h *Handler) GetHLSSegment(c *gin.Context)
- func (h *Handler) GetHLSSubsPlaylist(c *gin.Context)
- func (h *Handler) GetHLSVideoPlaylist(c *gin.Context)
- func (h *Handler) GetModel(c *gin.Context)
- func (h *Handler) GetServerStats(c *gin.Context)
- func (h *Handler) GetStreamToken(c *gin.Context)
- func (h *Handler) GetTags(c *gin.Context)
- func (h *Handler) GetUsers(c *gin.Context)
- func (h *Handler) ImportBackupJSON(c *gin.Context)
- func (h *Handler) InvalidateCamerasCache()
- func (h *Handler) LivenessCheck(c *gin.Context)
- func (h *Handler) PostWHEP(c *gin.Context)
- func (h *Handler) ReadinessCheck(c *gin.Context)
- func (h *Handler) StreamLogs(c *gin.Context)
- func (h *Handler) StreamWS(c *gin.Context)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SetupRouter ¶
func SetupRouter(h *Handler, auth registry.Authenticator, debug bool, corsOrigins []string) *gin.Engine
SetupRouter initializes and configures the Gin HTTP engine with CORS middleware, zerolog access logging, Prometheus metrics, Swagger UI endpoints, Pprof/Statsviz debugging tools, REST API routes, and embedded SPA static file serving.
Types ¶
type CameraInfo ¶
type CameraInfo struct {
ID string `json:"id"`
URL string `json:"url"`
State models.CameraState `json:"state"`
Record bool `json:"record"`
RetentionDays int `json:"retentionDays"`
Tags []string `json:"tags"`
FolderID string `json:"folderId"`
Comment string `json:"comment"`
SimPhone string `json:"simPhone"`
SimICCID string `json:"simICCID"`
TrafficLimit uint64 `json:"trafficLimit"`
TrafficUsed uint64 `json:"trafficUsed"`
Uptime uint64 `json:"uptime"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
Frames uint64 `json:"frames"`
KeyFrames uint64 `json:"keyFrames"`
Codec string `json:"codec"`
LastFrameTime int64 `json:"lastFrameTime"`
LastKeyTime int64 `json:"lastKeyTime"`
LastError string `json:"lastError"`
Reconnects uint64 `json:"reconnects"`
Bitrate float64 `json:"bitrate"`
LazyHLS bool `json:"lazyHLS"`
TokenAuth bool `json:"tokenAuth"`
Disabled bool `json:"disabled"`
DisableReason string `json:"disableReason"`
DisableHistory []config.DisableRecord `json:"disableHistory"`
RecordHistory []config.DisableRecord `json:"recordHistory"`
}
CameraInfo описывает текущее состояние камеры и статистику для API.
type ClientInfo ¶
type ClientInfo struct {
// IP is the remote client IP address.
IP string `json:"ip"`
// StreamID is the camera identifier the client is consuming.
StreamID string `json:"streamId"`
}
ClientInfo represents an active media stream viewer's IP address and viewed stream ID.
type ClientTracker ¶
type ClientTracker struct {
// contains filtered or unexported fields
}
ClientTracker maintains a sharded, thread-safe registry of active streaming viewers per camera.
func NewClientTracker ¶
func NewClientTracker() *ClientTracker
NewClientTracker allocates a new 32-shard ClientTracker.
func (*ClientTracker) GetActiveClients ¶
func (c *ClientTracker) GetActiveClients(timeout time.Duration) []ClientInfo
GetActiveClients scans all shards and returns a list of clients active within the given timeout window.
func (*ClientTracker) Mark ¶
func (c *ClientTracker) Mark(ip, streamID string)
Mark records client stream activity, updating the last seen timestamp with 5-second rate limiting.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler contains dependencies and state for processing REST and media API requests.
func NewHandler ¶
func NewHandler(manager *stream.Manager, cfg *config.Config, store registry.StateStore, webrtcEngine ...*webrtc.Engine) *Handler
NewHandler instantiates and configures a new HTTP API Handler.
func (*Handler) AddCamera ¶
@Summary Add a new camera @Description Dynamically registers a new camera and starts its stream if not disabled @Tags cameras @Accept json @Produce json @Param camera body config.CameraConfig true "Camera Configuration" @Success 200 {object} map[string]string @Failure 400 {object} map[string]string @Failure 409 {object} map[string]string @Failure 500 {object} map[string]string @Router /api/cameras [post]
func (*Handler) CleanupArchiveTrigger ¶
CleanupArchiveTrigger вручную вызывает сборщик мусора архива
func (*Handler) DeleteCamera ¶
@Summary Delete a camera @Description Stops the stream and completely removes the camera configuration @Tags cameras @Produce json @Param id path string true "Camera ID" @Success 200 {object} map[string]string @Failure 404 {object} map[string]string @Failure 500 {object} map[string]string @Router /api/cameras/{id} [delete]
func (*Handler) DeleteFolder ¶
DeleteFolder удаляет папку по ID
func (*Handler) DeleteUser ¶
DeleteUser удаляет пользователя с защитой от удаления последнего администратора.
func (*Handler) EditCamera ¶
@Summary Edit a camera @Description Updates camera settings dynamically without full restart @Tags cameras @Accept json @Produce json @Param id path string true "Camera ID" @Param camera body config.CameraConfig true "Updated Camera Configuration" @Success 200 {object} map[string]string @Failure 400 {object} map[string]string @Failure 404 {object} map[string]string @Failure 500 {object} map[string]string @Router /api/cameras/{id} [put]
func (*Handler) ExportBackupJSON ¶
ExportBackupJSON отдает дамп конфигурации (камеры и теги) в виде JSON-файла.
func (*Handler) ExportCameraArchive ¶
ExportCameraArchive скачивает фрагмент архива в виде MP4 файла
func (*Handler) GetArchiveHLSPlaylist ¶
GetArchiveHLSPlaylist отдает M3U8 манифест для конкретного файла архива
func (*Handler) GetArchiveHLSSegment ¶
GetArchiveHLSSegment отдает TS сегмент архива "на лету"
func (*Handler) GetCameraArchive ¶
GetCameraArchive возвращает список доступных отрезков архива для камеры
func (*Handler) GetCameras ¶
@Summary Get all cameras @Description Returns a list of all registered cameras along with their real-time statistics @Tags cameras @Produce json @Success 200 {array} CameraInfo @Router /api/cameras [get]
func (*Handler) GetFolders ¶
GetFolders возвращает глобальный список папок
func (*Handler) GetHLSPlaylist ¶
GetHLSPlaylist возвращает M3U8 плейлист для конкретной камеры.
func (*Handler) GetHLSSegment ¶
GetHLSSegment возвращает TS-сегмент или VTT файл для конкретной камеры.
func (*Handler) GetHLSSubsPlaylist ¶
GetHLSSubsPlaylist возвращает M3U8 плейлист субтитров для конкретной камеры.
func (*Handler) GetHLSVideoPlaylist ¶
GetHLSVideoPlaylist возвращает плейлист видео сегментов для HLS.
func (*Handler) GetModel ¶
GetModel serves or transparently proxies & caches AI ONNX models locally. Uses singleflight to coalesce concurrent requests per model file without head-of-line blocking.
func (*Handler) GetStreamToken ¶
GetStreamToken возвращает короткоживущий токен для HLS и WebRTC.
func (*Handler) ImportBackupJSON ¶
ImportBackupJSON принимает JSON-файл дампа и восстанавливает конфигурации камер и тегов.
func (*Handler) InvalidateCamerasCache ¶
func (h *Handler) InvalidateCamerasCache()
InvalidateCamerasCache invalidates the atomic camera list response cache.
func (*Handler) LivenessCheck ¶
LivenessCheck responds to liveness probes (e.g. /livez).
func (*Handler) PostWHEP ¶
PostWHEP обрабатывает WebRTC SDP Offer и возвращает SDP Answer (WHEP протокол).
func (*Handler) ReadinessCheck ¶
ReadinessCheck responds to readiness probes (e.g. /readyz) verifying the health of database, storage, and streaming subsystems.
func (*Handler) StreamLogs ¶
StreamLogs streams server logs to clients via SSE.
func (*Handler) StreamWS ¶
StreamWS handles binary WebCodecs streaming over WebSocket. Protocol Specification:
- Initial Config Header (Packet Type 0x01): [0x01] : 1 byte (Header identifier) [CodecType] : 1 byte (0x01 = H264, 0x02 = H265) [VPS Length] : 2 bytes uint16 (BigEndian) [VPS Data] : N bytes [SPS Length] : 2 bytes uint16 (BigEndian) [SPS Data] : N bytes [PPS Length] : 2 bytes uint16 (BigEndian) [PPS Data] : N bytes
- Video Data Packet (Packet Type 0x02): [0x02] : 1 byte (Data identifier) [IsKeyFrame] : 1 byte (0x01 = Keyframe, 0x00 = Delta) [Timestamp Microsecs] : 8 bytes uint64 (BigEndian) [Annex-B NALU Payload] : Remaining bytes (00 00 00 01 <NALU> ...)