api

package
v2.1.5 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 37 Imported by: 0

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

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

func (h *Handler) AddCamera(c *gin.Context)

@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) AddFolder

func (h *Handler) AddFolder(c *gin.Context)

AddFolder добавляет новую папку

func (*Handler) AddTag

func (h *Handler) AddTag(c *gin.Context)

AddTag добавляет новый тег

func (*Handler) AddUser

func (h *Handler) AddUser(c *gin.Context)

AddUser добавляет нового пользователя.

func (*Handler) CleanupArchiveTrigger

func (h *Handler) CleanupArchiveTrigger(_ *gin.Context)

CleanupArchiveTrigger вручную вызывает сборщик мусора архива

func (*Handler) DeleteCamera

func (h *Handler) DeleteCamera(c *gin.Context)

@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

func (h *Handler) DeleteFolder(c *gin.Context)

DeleteFolder удаляет папку по ID

func (*Handler) DeleteTag

func (h *Handler) DeleteTag(c *gin.Context)

DeleteTag удаляет тег по ID

func (*Handler) DeleteUser

func (h *Handler) DeleteUser(c *gin.Context)

DeleteUser удаляет пользователя с защитой от удаления последнего администратора.

func (*Handler) EditCamera

func (h *Handler) EditCamera(c *gin.Context)

@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) EditFolder

func (h *Handler) EditFolder(c *gin.Context)

EditFolder изменяет папку

func (*Handler) EditTag

func (h *Handler) EditTag(c *gin.Context)

EditTag изменяет тег

func (*Handler) EditUser

func (h *Handler) EditUser(c *gin.Context)

EditUser обновляет пользователя (пароль и/или роль).

func (*Handler) ExportBackupJSON

func (h *Handler) ExportBackupJSON(c *gin.Context)

ExportBackupJSON отдает дамп конфигурации (камеры и теги) в виде JSON-файла.

func (*Handler) ExportCameraArchive

func (h *Handler) ExportCameraArchive(c *gin.Context)

ExportCameraArchive скачивает фрагмент архива в виде MP4 файла

func (*Handler) GetArchiveHLSPlaylist

func (h *Handler) GetArchiveHLSPlaylist(c *gin.Context)

GetArchiveHLSPlaylist отдает M3U8 манифест для конкретного файла архива

func (*Handler) GetArchiveHLSSegment

func (h *Handler) GetArchiveHLSSegment(c *gin.Context)

GetArchiveHLSSegment отдает TS сегмент архива "на лету"

func (*Handler) GetCameraArchive

func (h *Handler) GetCameraArchive(c *gin.Context)

GetCameraArchive возвращает список доступных отрезков архива для камеры

func (*Handler) GetCameras

func (h *Handler) GetCameras(c *gin.Context)

@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

func (h *Handler) GetFolders(c *gin.Context)

GetFolders возвращает глобальный список папок

func (*Handler) GetHLSPlaylist

func (h *Handler) GetHLSPlaylist(c *gin.Context)

GetHLSPlaylist возвращает M3U8 плейлист для конкретной камеры.

func (*Handler) GetHLSSegment

func (h *Handler) GetHLSSegment(c *gin.Context)

GetHLSSegment возвращает TS-сегмент или VTT файл для конкретной камеры.

func (*Handler) GetHLSSubsPlaylist

func (h *Handler) GetHLSSubsPlaylist(c *gin.Context)

GetHLSSubsPlaylist возвращает M3U8 плейлист субтитров для конкретной камеры.

func (*Handler) GetHLSVideoPlaylist

func (h *Handler) GetHLSVideoPlaylist(c *gin.Context)

GetHLSVideoPlaylist возвращает плейлист видео сегментов для HLS.

func (*Handler) GetModel

func (h *Handler) GetModel(c *gin.Context)

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) GetServerStats

func (h *Handler) GetServerStats(c *gin.Context)

GetServerStats

func (*Handler) GetStreamToken

func (h *Handler) GetStreamToken(c *gin.Context)

GetStreamToken возвращает короткоживущий токен для HLS и WebRTC.

func (*Handler) GetTags

func (h *Handler) GetTags(c *gin.Context)

GetTags возвращает глобальный список тегов

func (*Handler) GetUsers

func (h *Handler) GetUsers(c *gin.Context)

GetUsers возвращает список всех пользователей.

func (*Handler) ImportBackupJSON

func (h *Handler) ImportBackupJSON(c *gin.Context)

ImportBackupJSON принимает JSON-файл дампа и восстанавливает конфигурации камер и тегов.

func (*Handler) InvalidateCamerasCache

func (h *Handler) InvalidateCamerasCache()

InvalidateCamerasCache invalidates the atomic camera list response cache.

func (*Handler) LivenessCheck

func (h *Handler) LivenessCheck(c *gin.Context)

LivenessCheck responds to liveness probes (e.g. /livez).

func (*Handler) PostWHEP

func (h *Handler) PostWHEP(c *gin.Context)

PostWHEP обрабатывает WebRTC SDP Offer и возвращает SDP Answer (WHEP протокол).

func (*Handler) ReadinessCheck

func (h *Handler) ReadinessCheck(c *gin.Context)

ReadinessCheck responds to readiness probes (e.g. /readyz) verifying the health of database, storage, and streaming subsystems.

func (*Handler) StreamLogs

func (h *Handler) StreamLogs(c *gin.Context)

StreamLogs streams server logs to clients via SSE.

func (*Handler) StreamWS

func (h *Handler) StreamWS(c *gin.Context)

StreamWS handles binary WebCodecs streaming over WebSocket. Protocol Specification:

  1. 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
  1. 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> ...)

Directories

Path Synopsis
Package docs Code generated by swaggo/swag.
Package docs Code generated by swaggo/swag.

Jump to

Keyboard shortcuts

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