api

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 60 Imported by: 0

Documentation

Overview

Package api provides the AltMount REST API.

@title			AltMount API
@version		1.0
@description	REST API for AltMount — Usenet WebDAV server with NZB queue, health monitoring, ARR integration, FUSE/rclone mounting, and Stremio addon.
@termsOfService	http://altmount.kipsilabs.top

@contact.name	AltMount
@contact.url	https://github.com/javi11/altmount/issues

@license.name	MIT

@host		localhost:8080
@BasePath	/api

@securityDefinitions.apikey	ApiKeyAuth
@in							query
@name						apikey

@securityDefinitions.http	BearerAuth
@scheme						bearer
@bearerFormat				JWT

@tag.name			Queue
@tag.description	NZB download queue management
@tag.name			Health
@tag.description	File health monitoring and repair
@tag.name			Files
@tag.description	File metadata, streams, and NZB export
@tag.name			Import
@tag.description	Manual file imports and directory scanning
@tag.name			Providers
@tag.description	NNTP provider management
@tag.name			ARRs
@tag.description	Sonarr/Radarr integration
@tag.name			Config
@tag.description	Configuration management
@tag.name			System
@tag.description	System stats, health, and maintenance
@tag.name			FUSE
@tag.description	FUSE mount management
@tag.name			Stremio
@tag.description	Stremio addon and NZB stream endpoints
@tag.name			Auth
@tag.description	Authentication and registration
@tag.name			User
@tag.description	Current user management

Index

Constants

View Source
const (
	ErrCodeInternalServer = "INTERNAL_SERVER_ERROR"
	ErrCodeBadRequest     = "BAD_REQUEST"
	ErrCodeNotFound       = "NOT_FOUND"
	ErrCodeValidation     = "VALIDATION_ERROR"
	ErrCodeConflict       = "CONFLICT"
	ErrCodeUnauthorized   = "UNAUTHORIZED"
	ErrCodeForbidden      = "FORBIDDEN"
)

Standard error codes

Variables

This section is empty.

Functions

func ApplyLogLevel

func ApplyLogLevel(level string)

ApplyLogLevel applies the log level to the global logger

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses a duration string, supporting 'd' for days

func ParseTimeParamFiber

func ParseTimeParamFiber(c *fiber.Ctx, param string) (*time.Time, error)

ParseTimeParamFiber extracts time parameter from Fiber context

func RegisterLogLevelHandler

func RegisterLogLevelHandler(ctx context.Context, configManager *config.Manager, debugMode *bool)

RegisterLogLevelHandler registers handler for log level configuration changes

func RegisterRCloneRoutes

func RegisterRCloneRoutes(apiGroup fiber.Router, handlers *RCloneHandlers)

RegisterRCloneRoutes registers RClone-related routes

func RequireAdminPrivileges

func RequireAdminPrivileges(c *fiber.Ctx, user interface{ IsAdminUser() bool }) bool

Helper function to check for admin privileges and respond with error if not admin. Returns true if user is admin, false otherwise (and sends error response).

func RespondBadRequest

func RespondBadRequest(c *fiber.Ctx, message, details string) error

RespondBadRequest sends a 400 Bad Request error.

func RespondConflict

func RespondConflict(c *fiber.Ctx, message, details string) error

RespondConflict sends a 409 Conflict error.

func RespondCreated

func RespondCreated(c *fiber.Ctx, data any) error

RespondCreated sends a 201 Created response with data.

func RespondError

func RespondError(c *fiber.Ctx, status int, code, message, details string) error

RespondError sends an error response with a custom status code.

func RespondForbidden

func RespondForbidden(c *fiber.Ctx, message, details string) error

RespondForbidden sends a 403 Forbidden error.

func RespondInternalError

func RespondInternalError(c *fiber.Ctx, message, details string) error

RespondInternalError sends a 500 Internal Server Error. In production mode, internal details are suppressed to avoid leaking implementation info.

func RespondMessage

func RespondMessage(c *fiber.Ctx, message string) error

RespondMessage sends a successful response with a message only.

func RespondNoContent

func RespondNoContent(c *fiber.Ctx) error

RespondNoContent sends a 204 No Content response.

func RespondNotFound

func RespondNotFound(c *fiber.Ctx, resource, details string) error

RespondNotFound sends a 404 Not Found error.

func RespondServiceUnavailable

func RespondServiceUnavailable(c *fiber.Ctx, message, details string) error

RespondServiceUnavailable sends a 503 Service Unavailable error.

func RespondSuccess

func RespondSuccess(c *fiber.Ctx, data any) error

RespondSuccess sends a successful response with data.

func RespondSuccessWithMeta

func RespondSuccessWithMeta(c *fiber.Ctx, data any, meta *APIMeta) error

RespondSuccessWithMeta sends a successful response with data and pagination metadata.

func RespondUnauthorized

func RespondUnauthorized(c *fiber.Ctx, message, details string) error

RespondUnauthorized sends a 401 Unauthorized error.

func RespondValidationError

func RespondValidationError(c *fiber.Ctx, message, details string) error

RespondValidationError sends a 400 Bad Request error for validation failures.

Types

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

APIError represents an error response

type APIMeta

type APIMeta struct {
	Total  int `json:"total"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
	Count  int `json:"count"`
}

APIMeta represents metadata for paginated responses

type APIResponse

type APIResponse struct {
	Success bool      `json:"success"`
	Data    any       `json:"data,omitempty"`
	Error   *APIError `json:"error,omitempty"`
	Meta    *APIMeta  `json:"meta,omitempty"`
}

APIResponse represents a standard API response wrapper

type ArrsDeletedFile

type ArrsDeletedFile struct {
	Path string `json:"path"`
}

type ArrsDeletedFiles

type ArrsDeletedFiles []ArrsDeletedFile

func (*ArrsDeletedFiles) UnmarshalJSON

func (df *ArrsDeletedFiles) UnmarshalJSON(data []byte) error

type ArrsEpisodeResponse

type ArrsEpisodeResponse struct {
	ID            int64   `json:"id"`
	InstanceID    int64   `json:"instance_id"`
	SeriesID      int64   `json:"series_id"`
	EpisodeID     int64   `json:"episode_id"`
	SeriesTitle   string  `json:"series_title"`
	SeasonNumber  int     `json:"season_number"`
	EpisodeNumber int     `json:"episode_number"`
	EpisodeTitle  *string `json:"episode_title"`
	FilePath      string  `json:"file_path"`
	FileSize      *int64  `json:"file_size"`
	Quality       *string `json:"quality"`
	AirDate       *string `json:"air_date"`
	TVDbID        *int64  `json:"tvdb_id"`
	IMDbID        *string `json:"imdb_id"`
	LastUpdated   string  `json:"last_updated"`
}

ArrsEpisodeResponse represents an episode in API responses

type ArrsInstanceRequest

type ArrsInstanceRequest struct {
	Name              string `json:"name"`
	Type              string `json:"type"`
	URL               string `json:"url"`
	APIKey            string `json:"api_key"`
	Category          string `json:"category"`
	Enabled           bool   `json:"enabled"`
	SyncIntervalHours int    `json:"sync_interval_hours"`
}

ArrsInstanceRequest represents a request to create/update an arrs instance

type ArrsInstanceResponse

type ArrsInstanceResponse struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	URL      string `json:"url"`
	Category string `json:"category"`
	Enabled  bool   `json:"enabled"`
}

ArrsInstanceResponse represents an arrs instance in API responses

type ArrsMovieResponse

type ArrsMovieResponse struct {
	ID          int64   `json:"id"`
	InstanceID  int64   `json:"instance_id"`
	MovieID     int64   `json:"movie_id"`
	Title       string  `json:"title"`
	Year        *int    `json:"year"`
	FilePath    string  `json:"file_path"`
	FileSize    *int64  `json:"file_size"`
	Quality     *string `json:"quality"`
	IMDbID      *string `json:"imdb_id"`
	TMDbID      *int64  `json:"tmdb_id"`
	LastUpdated string  `json:"last_updated"`
}

ArrsMovieResponse represents a movie in API responses

type ArrsStatsResponse

type ArrsStatsResponse struct {
	TotalInstances   int     `json:"total_instances"`
	EnabledInstances int     `json:"enabled_instances"`
	TotalRadarr      int     `json:"total_radarr"`
	EnabledRadarr    int     `json:"enabled_radarr"`
	TotalSonarr      int     `json:"total_sonarr"`
	EnabledSonarr    int     `json:"enabled_sonarr"`
	DueForSync       int     `json:"due_for_sync"`
	LastSync         *string `json:"last_sync"`
}

ArrsStatsResponse represents arrs statistics

type ArrsWebhookRequest

type ArrsWebhookRequest struct {
	EventType string `json:"eventType"`
	FilePath  string `json:"filePath,omitempty"`
	// For upgrades/renames, the file path might be in other fields or need to be inferred
	Movie struct {
		FolderPath string `json:"folderPath"`
	} `json:"movie"`
	MovieFile struct {
		Path string `json:"path"`
	} `json:"movieFile"`
	Series struct {
		Path string `json:"path"`
	} `json:"series"`
	EpisodeFile struct {
		Path string `json:"path"`
	} `json:"episodeFile"`
	DeletedFiles ArrsDeletedFiles `json:"deletedFiles,omitempty"`
}

ArrsWebhookRequest represents a webhook payload from Radarr/Sonarr

type AuthResponse

type AuthResponse struct {
	User        *UserResponse `json:"user,omitempty"`
	RedirectURL string        `json:"redirect_url,omitempty"`
	Message     string        `json:"message,omitempty"`
}

AuthResponse represents authentication response data

type AuthUpdater

type AuthUpdater struct {
	// contains filtered or unexported fields
}

AuthUpdater provides methods to update API authentication

func NewAuthUpdater

func NewAuthUpdater(server *Server) *AuthUpdater

NewAuthUpdater creates a new API auth updater

func (*AuthUpdater) UpdateAuth

func (u *AuthUpdater) UpdateAuth(username, password string) error

UpdateAuth updates API authentication credentials (OAuth only)

type BatchExportRequest

type BatchExportRequest struct {
	RootPath string `json:"root_path"`
}

BatchExportRequest represents the batch export request body

type ComponentHealth

type ComponentHealth struct {
	Status  string `json:"status"` // "healthy", "degraded", "unhealthy"
	Message string `json:"message,omitempty"`
	Details string `json:"details,omitempty"`
}

ComponentHealth represents health of a system component

type Config

type Config struct {
	Prefix string // API path prefix (default: "/api")
}

Config represents API server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default API configuration

type ConfigAPIResponse

type ConfigAPIResponse struct {
	*config.Config
	WebDAV          WebDAVAPIResponse     `json:"webdav"`
	Import          ImportAPIResponse     `json:"import"`
	RClone          RCloneAPIResponse     `json:"rclone"`
	SABnzbd         SABnzbdAPIResponse    `json:"sabnzbd"`
	Providers       []ProviderAPIResponse `json:"providers"`
	APIKey          string                `json:"api_key,omitempty"`      // User's API key for authentication
	DownloadKey     string                `json:"download_key,omitempty"` // SHA256 of the API key, used for download/stream URLs
	ProfilerEnabled bool                  `json:"profiler_enabled"`
}

ConfigAPIResponse wraps config.Config with sensitive data handling

func ToConfigAPIResponse

func ToConfigAPIResponse(cfg *config.Config, apiKey string) *ConfigAPIResponse

ToConfigAPIResponse converts config.Config to ConfigAPIResponse with sensitive data masked

type ConfigManager

type ConfigManager interface {
	GetConfig() *config.Config
	GetConfigGetter() config.ConfigGetter
	UpdateConfig(config *config.Config) error
	ValidateConfig(config *config.Config) error
	ValidateConfigUpdate(config *config.Config) error
	OnConfigChange(callback config.ChangeCallback)
	ReloadConfig() error
	SaveConfig() error
	NeedsLibrarySync() bool
	GetPreviousMountPath() string
	ClearLibrarySyncFlag()
}

ConfigManager interface defines methods for configuration management

type DailyStat

type DailyStat struct {
	Day       string `json:"day"`
	Completed int    `json:"completed"`
	Failed    int    `json:"failed"`
}

DailyStat represents statistics for a single day

type DryRunSyncResult

type DryRunSyncResult struct {
	OrphanedMetadataCount  int  `json:"orphaned_metadata_count"`   // Number of orphaned metadata files
	OrphanedLibraryFiles   int  `json:"orphaned_library_files"`    // Number of orphaned library files (symlinks/STRM)
	DatabaseRecordsToClean int  `json:"database_records_to_clean"` // Number of database records to clean
	WouldCleanup           bool `json:"would_cleanup"`             // Whether cleanup would occur based on config
}

DryRunSyncResult represents the results of a library sync dry run

type FileEntry

type FileEntry struct {
	Name    string    `json:"name"`
	Path    string    `json:"path"`
	IsDir   bool      `json:"is_dir"`
	Size    int64     `json:"size"`
	ModTime time.Time `json:"mod_time"`
}

FileEntry represents a file or directory in the system browser

type FileMetadataResponse

type FileMetadataResponse struct {
	FileSize          int64                  `json:"file_size"`
	SourceNzbPath     string                 `json:"source_nzb_path"`
	Status            string                 `json:"status"`
	SegmentCount      int                    `json:"segment_count"`
	AvailableSegments *int                   `json:"available_segments"`
	Encryption        string                 `json:"encryption"`
	CreatedAt         string                 `json:"created_at"`
	ModifiedAt        string                 `json:"modified_at"`
	PasswordProtected bool                   `json:"password_protected"`
	Segments          []SegmentInfoResponse  `json:"segments"`
	NestedSources     []NestedSourceResponse `json:"nested_sources,omitempty"`
}

FileMetadataResponse represents file metadata information in API responses

type FuseManager

type FuseManager struct {
	// contains filtered or unexported fields
}

FuseManager handles the lifecycle of the FUSE server

func NewFuseManager

func NewFuseManager(factory MountFactory) *FuseManager

NewFuseManager creates a new FUSE manager. mountFactory is used to create fresh fuse.Server instances during auto-recovery.

func (*FuseManager) Stop

func (m *FuseManager) Stop()

Stop stops the FUSE mount and health monitor if running

type HealthCheckRequest

type HealthCheckRequest struct {
	FilePath    string                  `json:"file_path"`
	LibraryPath *string                 `json:"library_path,omitempty"`
	MaxRetries  *int                    `json:"max_retries,omitempty"`
	SourceNzb   *string                 `json:"source_nzb_path,omitempty"`
	Priority    database.HealthPriority `json:"priority,omitempty"`
}

HealthCheckRequest represents request to add file for manual health checking

type HealthCleanupRequest

type HealthCleanupRequest struct {
	OlderThan   *time.Time             `json:"older_than"`
	Status      *database.HealthStatus `json:"status"`
	DeleteFiles bool                   `json:"delete_files"` // Whether to also delete the physical files
}

HealthCleanupRequest represents request to cleanup health records

type HealthItemResponse

type HealthItemResponse struct {
	ID               int64                   `json:"id"`
	FilePath         string                  `json:"file_path"`
	LibraryPath      *string                 `json:"library_path,omitempty"`
	Status           database.HealthStatus   `json:"status"`
	LastChecked      *time.Time              `json:"last_checked"`
	LastError        *string                 `json:"last_error"`
	RetryCount       int                     `json:"retry_count"`
	MaxRetries       int                     `json:"max_retries"`
	SourceNzbPath    *string                 `json:"source_nzb_path"`
	ErrorDetails     *string                 `json:"error_details"`
	RepairRetryCount int                     `json:"repair_retry_count"`
	MaxRepairRetries int                     `json:"max_repair_retries"`
	CreatedAt        time.Time               `json:"created_at"`
	UpdatedAt        time.Time               `json:"updated_at"`
	ScheduledCheckAt *time.Time              `json:"scheduled_check_at,omitempty"`
	Priority         database.HealthPriority `json:"priority"`
	// Failure masking fields
	StreamingFailureCount int  `json:"streaming_failure_count"`
	IsMasked              bool `json:"is_masked"`
}

HealthItemResponse represents a health record in API responses

func ToHealthItemResponse

func ToHealthItemResponse(item *database.FileHealth) *HealthItemResponse

ToHealthItemResponse converts database.FileHealth to HealthItemResponse

type HealthListRequest

type HealthListRequest struct {
	Status *database.HealthStatus `json:"status"`
	Since  *time.Time             `json:"since"`
	Pagination
}

HealthListRequest represents request parameters for listing health records

type HealthRepairRequest

type HealthRepairRequest struct {
	ResetRepairRetryCount bool `json:"reset_repair_retry_count,omitempty"`
}

HealthRepairRequest represents request to trigger repair for a corrupted file

type HealthRetryRequest

type HealthRetryRequest struct {
	ResetRetryCount bool `json:"reset_retry_count,omitempty"`
}

HealthRetryRequest represents request to retry a corrupted file

type HealthStatsResponse

type HealthStatsResponse struct {
	Total           int `json:"total"`
	Pending         int `json:"pending"`
	Corrupted       int `json:"corrupted"`
	Healthy         int `json:"healthy"`
	RepairTriggered int `json:"repair_triggered"`
	Checking        int `json:"checking"`
}

HealthStatsResponse represents health statistics in API responses

func ToHealthStatsResponse

func ToHealthStatsResponse(stats map[database.HealthStatus]int) *HealthStatsResponse

ToHealthStatsResponse converts health stats map to HealthStatsResponse

type HealthWorkerStatusResponse

type HealthWorkerStatusResponse struct {
	Status                 string     `json:"status"`
	LastRunTime            *time.Time `json:"last_run_time,omitempty"`
	NextRunTime            *time.Time `json:"next_run_time,omitempty"`
	TotalRunsCompleted     int64      `json:"total_runs_completed"`
	TotalFilesChecked      int64      `json:"total_files_checked"`
	TotalFilesHealthy      int64      `json:"total_files_healthy"`
	TotalFilesCorrupted    int64      `json:"total_files_corrupted"`
	CurrentRunStartTime    *time.Time `json:"current_run_start_time,omitempty"`
	CurrentRunFilesChecked int        `json:"current_run_files_checked"`
	LastError              *string    `json:"last_error,omitempty"`
	ErrorCount             int64      `json:"error_count"`
}

HealthWorkerStatusResponse represents the current status of the health worker

type ImportAPIResponse

type ImportAPIResponse struct {
	MaxProcessorWorkers            int                   `json:"max_processor_workers"`
	QueueProcessingIntervalSeconds int                   `json:"queue_processing_interval_seconds"` // Interval in seconds
	AllowedFileExtensions          []string              `json:"allowed_file_extensions"`
	MaxImportConnections           int                   `json:"max_import_connections"`
	MaxDownloadPrefetch            int                   `json:"max_download_prefetch"`
	ReadTimeoutSeconds             int                   `json:"read_timeout_seconds"`
	SegmentSamplePercentage        int                   `json:"segment_sample_percentage"` // Percentage of segments to check (1-100)
	ImportStrategy                 config.ImportStrategy `json:"import_strategy"`
	ImportDir                      *string               `json:"import_dir"`
	WatchDir                       *string               `json:"watch_dir"`

	WatchIntervalSeconds     *int  `json:"watch_interval_seconds,omitempty"`
	AllowNestedRarExtraction *bool `json:"allow_nested_rar_extraction,omitempty"`
	RenameToNzbName          *bool `json:"rename_to_nzb_name,omitempty"`
	FilterSampleFiles        *bool `json:"filter_sample_files,omitempty"`
}

ImportAPIResponse handles Import config for API responses

func ToImportAPIResponse

func ToImportAPIResponse(importConfig config.ImportConfig) ImportAPIResponse

type ImportHistoryResponse

type ImportHistoryResponse struct {
	ID          int64     `json:"id"`
	NzbID       *int64    `json:"nzb_id"`
	NzbName     string    `json:"nzb_name"`
	FileName    string    `json:"file_name"`
	FileSize    int64     `json:"file_size"`
	VirtualPath string    `json:"virtual_path"`
	LibraryPath *string   `json:"library_path,omitempty"`
	Category    *string   `json:"category"`
	CompletedAt time.Time `json:"completed_at"`
}

ImportHistoryResponse represents a persistent import record in API responses

func ToImportHistoryResponse

func ToImportHistoryResponse(h *database.ImportHistory) *ImportHistoryResponse

ToImportHistoryResponse converts database.ImportHistory to ImportHistoryResponse

type LibrarySyncHandlers

type LibrarySyncHandlers struct {
	// contains filtered or unexported fields
}

LibrarySyncHandlers holds the library sync-related request handlers

func NewLibrarySyncHandlers

func NewLibrarySyncHandlers(librarySyncWorker *health.LibrarySyncWorker, configManager ConfigManager) *LibrarySyncHandlers

NewLibrarySyncHandlers creates a new instance of library sync handlers

type LogEntry

type LogEntry struct {
	Time    time.Time      `json:"time"`
	Level   string         `json:"level"`
	Message string         `json:"msg"`
	Attrs   map[string]any `json:"attrs,omitempty"`
}

LogEntry represents a single structured log entry from the JSON log file.

type LoginRequest

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LoginRequest represents direct authentication login request

type ManualImportRequest

type ManualImportRequest struct {
	FilePath     string  `json:"file_path"`
	RelativePath *string `json:"relative_path,omitempty"`
}

ManualImportRequest represents a request to manually import a file by path

type ManualImportResponse

type ManualImportResponse struct {
	QueueID int64  `json:"queue_id"`
	Message string `json:"message"`
}

ManualImportResponse represents the response from manually importing a file

type ManualScanRequest

type ManualScanRequest struct {
	Path string `json:"path"`
}

ManualScanRequest represents a request to start a manual directory scan

type MonitoredFile

type MonitoredFile struct {
	// contains filtered or unexported fields
}

MonitoredFile wraps an afero.File to track read progress and support cancellation

func (*MonitoredFile) Close

func (m *MonitoredFile) Close() error

func (*MonitoredFile) Read

func (m *MonitoredFile) Read(p []byte) (n int, err error)

func (*MonitoredFile) Seek

func (m *MonitoredFile) Seek(offset int64, whence int) (int64, error)

type MountFactory

type MountFactory func(path string) *fuse.Server

MountFactory creates a new FUSE server for (re)mounting.

type NestedSegmentResponse

type NestedSegmentResponse struct {
	SegmentSize int64  `json:"segment_size"`
	StartOffset int64  `json:"start_offset"`
	EndOffset   int64  `json:"end_offset"`
	MessageID   string `json:"message_id"`
}

NestedSegmentResponse represents one segment within a nested source volume

type NestedSourceResponse

type NestedSourceResponse struct {
	VolumeIndex     int                     `json:"volume_index"`
	InnerLength     int64                   `json:"inner_length"`
	InnerVolumeSize int64                   `json:"inner_volume_size"`
	Encrypted       bool                    `json:"encrypted"`
	SegmentCount    int                     `json:"segment_count"`
	Segments        []NestedSegmentResponse `json:"segments"`
}

NestedSourceResponse represents one inner-RAR volume in a nested archive

type Pagination

type Pagination struct {
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

Pagination represents pagination parameters

func DefaultPagination

func DefaultPagination() Pagination

DefaultPagination returns default pagination settings

func ParsePaginationFiber

func ParsePaginationFiber(c *fiber.Ctx) Pagination

ParsePaginationFiber extracts pagination parameters from Fiber context

type PoolMetricsResponse

type PoolMetricsResponse struct {
	BytesDownloaded             int64                    `json:"bytes_downloaded"`
	BytesDownloaded24h          int64                    `json:"bytes_downloaded_24h"`
	BytesUploaded               int64                    `json:"bytes_uploaded"`
	ArticlesDownloaded          int64                    `json:"articles_downloaded"`
	ArticlesPosted              int64                    `json:"articles_posted"`
	TotalErrors                 int64                    `json:"total_errors"`
	ProviderErrors              map[string]int64         `json:"provider_errors"`
	ProviderBytes               map[string]int64         `json:"provider_bytes"`
	DownloadSpeedBytesPerSec    float64                  `json:"download_speed_bytes_per_sec"`
	MaxDownloadSpeedBytesPerSec float64                  `json:"max_download_speed_bytes_per_sec"`
	UploadSpeedBytesPerSec      float64                  `json:"upload_speed_bytes_per_sec"`
	Timestamp                   time.Time                `json:"timestamp"`
	Providers                   []ProviderStatusResponse `json:"providers"`
}

PoolMetricsResponse represents NNTP pool metrics in API responses

type ProviderAPIResponse

type ProviderAPIResponse struct {
	ID                       string     `json:"id"`
	Host                     string     `json:"host"`
	Port                     int        `json:"port"`
	Username                 string     `json:"username"`
	MaxConnections           int        `json:"max_connections"`
	TLS                      bool       `json:"tls"`
	InsecureTLS              bool       `json:"insecure_tls"`
	ProxyURL                 string     `json:"proxy_url,omitempty"`
	PasswordSet              bool       `json:"password_set"`
	Enabled                  bool       `json:"enabled"`
	IsBackupProvider         bool       `json:"is_backup_provider"`
	InflightRequests         int        `json:"inflight_requests"`
	LastRTTMs                int64      `json:"last_rtt_ms"`
	LastSpeedTestMbps        float64    `json:"last_speed_test_mbps"`
	LastSpeedTestTime        *time.Time `json:"last_speed_test_time,omitempty"`
	SkipPing                 bool       `json:"skip_ping"`
	KeepaliveIntervalSeconds int        `json:"keepalive_interval_seconds"`
	KeepaliveCommand         string     `json:"keepalive_command,omitempty"`
}

ProviderAPIResponse sanitizes Provider config for API responses

type ProviderCreateRequest

type ProviderCreateRequest struct {
	Host             string `json:"host"`
	Port             int    `json:"port"`
	Username         string `json:"username"`
	Password         string `json:"password"`
	MaxConnections   int    `json:"max_connections"`
	TLS              bool   `json:"tls"`
	InsecureTLS      bool   `json:"insecure_tls"`
	ProxyURL         string `json:"proxy_url,omitempty"`
	Enabled          bool   `json:"enabled"`
	IsBackupProvider bool   `json:"is_backup_provider"`
}

ProviderCreateRequest represents a request to create a new provider

type ProviderReorderRequest

type ProviderReorderRequest struct {
	ProviderIDs []string `json:"provider_ids"`
}

ProviderReorderRequest represents a request to reorder providers

type ProviderSpeedTestResponse

type ProviderSpeedTestResponse struct {
	SpeedMBps float64 `json:"speed_mbps"`
	Duration  float64 `json:"duration_seconds"`
}

type ProviderStatusResponse

type ProviderStatusResponse struct {
	ID                      string     `json:"id"`
	Host                    string     `json:"host"`
	Username                string     `json:"username"`
	UsedConnections         int        `json:"used_connections"`
	MaxConnections          int        `json:"max_connections"`
	State                   string     `json:"state"`
	ErrorCount              int64      `json:"error_count"`
	LastConnectionAttempt   time.Time  `json:"last_connection_attempt"`
	LastSuccessfulConnect   time.Time  `json:"last_successful_connect"`
	FailureReason           string     `json:"failure_reason"`
	LastSpeedTestMbps       float64    `json:"last_speed_test_mbps"`
	LastSpeedTestTime       *time.Time `json:"last_speed_test_time,omitempty"`
	CurrentSpeedBytesPerSec float64    `json:"current_speed_bytes_per_sec"`
	PingMs                  int64      `json:"ping_ms"`
	MissingCount            int64      `json:"missing_count"`
	MissingRatePerMinute    float64    `json:"missing_rate_per_minute"`
	MissingWarning          bool       `json:"missing_warning"`
	ByteCount               int64      `json:"byte_count"`
	ByteCount24h            int64      `json:"byte_count_24h"`
}

ProviderStatusResponse represents NNTP provider connection status in API responses

type ProviderTestRequest

type ProviderTestRequest struct {
	Host        string `json:"host"`
	Port        int    `json:"port"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	TLS         bool   `json:"tls"`
	InsecureTLS bool   `json:"insecure_tls"`
	ProxyURL    string `json:"proxy_url,omitempty"`
}

ProviderTestRequest represents a request to test provider connectivity

type ProviderUpdateRequest

type ProviderUpdateRequest struct {
	Host             *string `json:"host,omitempty"`
	Port             *int    `json:"port,omitempty"`
	Username         *string `json:"username,omitempty"`
	Password         *string `json:"password,omitempty"`
	MaxConnections   *int    `json:"max_connections,omitempty"`
	TLS              *bool   `json:"tls,omitempty"`
	InsecureTLS      *bool   `json:"insecure_tls,omitempty"`
	ProxyURL         *string `json:"proxy_url,omitempty"`
	Enabled          *bool   `json:"enabled,omitempty"`
	IsBackupProvider *bool   `json:"is_backup_provider,omitempty"`
}

ProviderUpdateRequest represents a request to update an existing provider

type QueueHistoricalStatsResponse

type QueueHistoricalStatsResponse struct {
	Last24Hours QueueHistoryRange `json:"last_24_hours"`
	Last7Days   QueueHistoryRange `json:"last_7_days"`
	Last30Days  QueueHistoryRange `json:"last_30_days"`
	Last365Days QueueHistoryRange `json:"last_365_days"`
	Daily       []DailyStat       `json:"daily"`
}

QueueHistoricalStatsResponse represents historical queue statistics

func ToQueueHistoricalStatsResponse

func ToQueueHistoricalStatsResponse(stats []*database.ImportDailyStat, hourlyStats []*database.ImportHourlyStat) *QueueHistoricalStatsResponse

ToQueueHistoricalStatsResponse converts database.ImportDailyStat slice to QueueHistoricalStatsResponse

type QueueHistoryRange

type QueueHistoryRange struct {
	Completed  int     `json:"completed"`
	Failed     int     `json:"failed"`
	Percentage float64 `json:"percentage"`
}

QueueHistoryRange represents statistics for a specific time range

type QueueItemResponse

type QueueItemResponse struct {
	ID           int64                  `json:"id"`
	NzbPath      string                 `json:"nzb_path"`
	TargetPath   string                 `json:"target_path"`
	Category     *string                `json:"category"`
	Priority     database.QueuePriority `json:"priority"`
	Status       database.QueueStatus   `json:"status"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
	StartedAt    *time.Time             `json:"started_at"`
	CompletedAt  *time.Time             `json:"completed_at"`
	RetryCount   int                    `json:"retry_count"`
	MaxRetries   int                    `json:"max_retries"`
	ErrorMessage *string                `json:"error_message"`
	BatchID      *string                `json:"batch_id"`
	Metadata     *string                `json:"metadata"`
	FileSize     *int64                 `json:"file_size"`
	Percentage   *int                   `json:"percentage,omitempty"`   // Progress percentage (0-100), only for items being processed
	StoragePath  *string                `json:"storage_path,omitempty"` // Internal FUSE mount path (populated after completion)
}

QueueItemResponse represents a queue item in API responses

func ToQueueItemResponse

func ToQueueItemResponse(item *database.ImportQueueItem) *QueueItemResponse

ToQueueItemResponse converts database.ImportQueueItem to QueueItemResponse

type QueueListRequest

type QueueListRequest struct {
	Status *database.QueueStatus `json:"status"`
	Since  *time.Time            `json:"since"`
	Pagination
}

QueueListRequest represents request parameters for listing queue items

type QueueStatsResponse

type QueueStatsResponse struct {
	TotalQueued         int       `json:"total_queued"`
	TotalProcessing     int       `json:"total_processing"`
	TotalCompleted      int       `json:"total_completed"`
	TotalFailed         int       `json:"total_failed"`
	AvgProcessingTimeMs *int      `json:"avg_processing_time_ms"`
	LastUpdated         time.Time `json:"last_updated"`
}

QueueStatsResponse represents queue statistics in API responses

func ToQueueStatsResponse

func ToQueueStatsResponse(stats *database.QueueStats) *QueueStatsResponse

ToQueueStatsResponse converts database.QueueStats to QueueStatsResponse

type RCloneAPIResponse

type RCloneAPIResponse struct {
	// Encryption
	PasswordSet bool `json:"password_set"`
	SaltSet     bool `json:"salt_set"`

	RCEnabled bool `json:"rc_enabled"`

	RCUrl string `json:"rc_url"`

	VFSName string `json:"vfs_name"`

	RCPort int `json:"rc_port"`

	RCUser    string            `json:"rc_user"`
	RCPassSet bool              `json:"rc_pass_set"`
	RCOptions map[string]string `json:"rc_options"`

	// Mount Configuration
	MountEnabled bool              `json:"mount_enabled"`
	MountOptions map[string]string `json:"mount_options"`

	// Mount-Specific Settings
	AllowOther    bool   `json:"allow_other"`
	AllowNonEmpty bool   `json:"allow_non_empty"`
	Links         bool   `json:"links"`
	ReadOnly      bool   `json:"read_only"`
	Timeout       string `json:"timeout"`
	Syslog        bool   `json:"syslog"`

	// System and filesystem options
	LogLevel    string `json:"log_level"`
	UID         int    `json:"uid"`
	GID         int    `json:"gid"`
	Umask       string `json:"umask"`
	BufferSize  string `json:"buffer_size"`
	AttrTimeout string `json:"attr_timeout"`
	Transfers   int    `json:"transfers"`

	// VFS Cache Settings
	CacheDir             string `json:"cache_dir"`
	VFSCacheMode         string `json:"vfs_cache_mode"`
	VFSCacheMaxSize      string `json:"vfs_cache_max_size"`
	VFSCacheMaxAge       string `json:"vfs_cache_max_age"`
	ReadChunkSize        string `json:"read_chunk_size"`
	ReadChunkSizeLimit   string `json:"read_chunk_size_limit"`
	VFSReadAhead         string `json:"vfs_read_ahead"`
	DirCacheTime         string `json:"dir_cache_time"`
	VFSCacheMinFreeSpace string `json:"vfs_cache_min_free_space"`
	VFSDiskSpaceTotal    string `json:"vfs_disk_space_total"`
	VFSReadChunkStreams  int    `json:"vfs_read_chunk_streams"`

	// Advanced Settings
	NoModTime          bool `json:"no_mod_time"`
	NoChecksum         bool `json:"no_checksum"`
	AsyncRead          bool `json:"async_read"`
	VFSFastFingerprint bool `json:"vfs_fast_fingerprint"`
	UseMmap            bool `json:"use_mmap"`
}

RCloneAPIResponse sanitizes RClone config for API responses

type RCloneHandlers

type RCloneHandlers struct {
	// contains filtered or unexported fields
}

RCloneHandlers handles RClone-related API endpoints

func NewRCloneHandlers

func NewRCloneHandlers(mountService *rclone.MountService, configGetter config.ConfigGetter) *RCloneHandlers

NewRCloneHandlers creates new RClone handlers

func (*RCloneHandlers) ClearRCloneCache

func (h *RCloneHandlers) ClearRCloneCache(c *fiber.Ctx) error

ClearRCloneCache removes the rclone VFS cache directory and recreates it empty.

func (*RCloneHandlers) GetMountStatus

func (h *RCloneHandlers) GetMountStatus(c *fiber.Ctx) error

GetMountStatus returns the current mount status

func (*RCloneHandlers) StartMount

func (h *RCloneHandlers) StartMount(c *fiber.Ctx) error

StartMount starts the rclone mount

func (*RCloneHandlers) StopMount

func (h *RCloneHandlers) StopMount(c *fiber.Ctx) error

StopMount stops the rclone mount

func (*RCloneHandlers) TestMountConfig

func (h *RCloneHandlers) TestMountConfig(c *fiber.Ctx) error

TestMountConfig tests the mount configuration

func (*RCloneHandlers) TestRCloneConnection

func (h *RCloneHandlers) TestRCloneConnection(c *fiber.Ctx) error

TestRCloneConnection tests the RClone RC connection

type RegisterRequest

type RegisterRequest struct {
	Username string `json:"username"`
	Email    string `json:"email,omitempty"`
	Password string `json:"password"`
}

RegisterRequest represents user registration request

type SABnzbdAPIResponse

type SABnzbdAPIResponse struct {
	Enabled               bool                     `json:"enabled"`
	CompleteDir           string                   `json:"complete_dir"`
	DownloadClientBaseURL string                   `json:"download_client_base_url"`
	Categories            []config.SABnzbdCategory `json:"categories"`
	FallbackHost          string                   `json:"fallback_host"`
	FallbackAPIKey        string                   `json:"fallback_api_key"`     // Obfuscated if set
	FallbackAPIKeySet     bool                     `json:"fallback_api_key_set"` // Indicates if API key is set
}

SABnzbdAPIResponse sanitizes SABnzbd config for API responses

type SABnzbdAddResponse

type SABnzbdAddResponse struct {
	Status bool     `json:"status"`
	NzoIds []string `json:"nzo_ids,omitempty"`
	Error  *string  `json:"error,omitempty"`
}

SABnzbdAddResponse represents the response from adding a download

type SABnzbdCategory

type SABnzbdCategory struct {
	Name     string `json:"name"`
	Order    int    `json:"order"`
	PP       string `json:"pp"`
	Script   string `json:"script"`
	Dir      string `json:"dir"`
	Newzbin  string `json:"newzbin"`
	Priority int    `json:"priority"`
}

SABnzbdCategory represents a download category configuration

type SABnzbdCompleteHistoryResponse

type SABnzbdCompleteHistoryResponse struct {
	History SABnzbdHistoryObject `json:"history"`
}

SABnzbdCompleteHistoryResponse represents the complete history response structure

type SABnzbdConfig

type SABnzbdConfig struct {
	Misc       SABnzbdMiscConfig `json:"misc"`
	Categories []SABnzbdCategory `json:"categories"`
	Servers    []SABnzbdServer   `json:"servers"`
}

SABnzbdConfig represents the SABnzbd configuration structure

type SABnzbdConfigResponse

type SABnzbdConfigResponse struct {
	Status  bool          `json:"status"`
	Version string        `json:"version"`
	Config  SABnzbdConfig `json:"config"`
}

SABnzbdConfigResponse represents the configuration response

type SABnzbdDeleteResponse

type SABnzbdDeleteResponse struct {
	Status bool    `json:"status"`
	Error  *string `json:"error,omitempty"`
}

SABnzbdDeleteResponse represents the response from deleting an item

type SABnzbdHistoryObject

type SABnzbdHistoryObject struct {
	Slots             []SABnzbdHistorySlot `json:"slots"`
	TotalSize         string               `json:"total_size"`
	MonthSize         string               `json:"month_size"`
	WeekSize          string               `json:"week_size"`
	DaySize           string               `json:"day_size"`
	Ppslots           int                  `json:"ppslots"`
	Noofslots         int                  `json:"noofslots"`
	LastHistoryUpdate int                  `json:"last_history_update"`
	Version           string               `json:"version"`
}

SABnzbdHistoryObject represents the nested history object in the complete response

type SABnzbdHistoryResponse

type SABnzbdHistoryResponse struct {
	Status    bool                 `json:"status"`
	Version   string               `json:"version"`
	Paused    bool                 `json:"paused"`
	NoOfSlots int                  `json:"noofslots"`
	Slots     []SABnzbdHistorySlot `json:"slots"`
	TotalSize string               `json:"total_size"`
	MonthSize string               `json:"month_size"`
	WeekSize  string               `json:"week_size"`
	DaySize   string               `json:"day_size"`
}

SABnzbdHistoryResponse represents the history response structure

type SABnzbdHistorySlot

type SABnzbdHistorySlot struct {
	Index        int      `json:"index"`
	NzoID        string   `json:"nzo_id"`
	Name         string   `json:"name"`
	Category     string   `json:"category"`
	Cat          string   `json:"cat"`
	PP           string   `json:"pp"`
	Script       string   `json:"script"`
	Report       string   `json:"report"`
	URL          string   `json:"url"`
	Status       string   `json:"status"`
	NzbName      string   `json:"nzb_name"`
	Download     string   `json:"download"`
	Path         string   `json:"path"`
	Storage      string   `json:"storage"`
	Postproc     string   `json:"postproc"`
	Downloaded   int64    `json:"downloaded"`
	Completetime int64    `json:"completetime"`
	NzbAvg       string   `json:"nzb_avg"`
	Script_log   string   `json:"script_log"`
	Script_line  string   `json:"script_line"`
	DuplicateKey string   `json:"duplicate_key"`
	Fail_message string   `json:"fail_message"`
	Url_info     string   `json:"url_info"`
	Bytes        int64    `json:"bytes"`
	Meta         []string `json:"meta"`
	Series       string   `json:"series"`
	Md5sum       string   `json:"md5sum"`
	Password     string   `json:"password"`
	ActionLine   string   `json:"action_line"`
	Size         string   `json:"size"`
	Loaded       bool     `json:"loaded"`
	Retry        int      `json:"retry"`
	StateLog     []string `json:"stage_log"`
}

SABnzbdHistorySlot represents a single item in the download history

func ToSABnzbdHistorySlot

func ToSABnzbdHistorySlot(item *database.ImportQueueItem, index int, finalPath string) SABnzbdHistorySlot

ToSABnzbdHistorySlot converts an AltMount ImportQueueItem to SABnzbd history format

type SABnzbdMiscConfig

type SABnzbdMiscConfig struct {
	CompleteDir            string `json:"complete_dir"`
	PreCheck               int    `json:"pre_check"`
	HistoryRetention       string `json:"history_retention"`
	HistoryRetentionOption string `json:"history_retention_option"`
	HistoryRetentionNumber int    `json:"history_retention_number"`
}

SABnzbdMiscConfig represents miscellaneous configuration settings

type SABnzbdQueueObject

type SABnzbdQueueObject struct {
	Paused    bool               `json:"paused"`
	Slots     []SABnzbdQueueSlot `json:"slots"`
	Noofslots int                `json:"noofslots"`
	Status    string             `json:"status"`
	Mbleft    string             `json:"mbleft"`
	Mb        string             `json:"mb"`
	Kbpersec  string             `json:"kbpersec"`
	Speed     string             `json:"speed"`
	Version   string             `json:"version"`
}

SABnzbdQueueObject represents the nested queue object in the response

type SABnzbdQueueResponse

type SABnzbdQueueResponse struct {
	Status bool               `json:"status"`
	Queue  SABnzbdQueueObject `json:"queue"`
}

SABnzbdQueueResponse represents the queue response structure

type SABnzbdQueueSlot

type SABnzbdQueueSlot struct {
	Index      int    `json:"index"`
	NzoID      string `json:"nzo_id"`
	Priority   string `json:"priority"`
	Filename   string `json:"filename"`
	Cat        string `json:"cat"`
	Category   string `json:"category"`
	Percentage string `json:"percentage"`
	Status     string `json:"status"`
	Timeleft   string `json:"timeleft"`
	Eta        string `json:"eta"`
	Size       string `json:"size"`
	Sizeleft   string `json:"sizeleft"`
	Mb         string `json:"mb"`
	Mbleft     string `json:"mbleft"`
}

SABnzbdQueueSlot represents a single item in the download queue

func ToSABnzbdQueueSlot

func ToSABnzbdQueueSlot(item *database.ImportQueueItem, index int, progressBroadcaster *progress.ProgressBroadcaster) SABnzbdQueueSlot

ToSABnzbdQueueSlot converts an AltMount ImportQueueItem to SABnzbd format

type SABnzbdResponse

type SABnzbdResponse struct {
	Status  bool    `json:"status"`
	Queue   any     `json:"queue,omitempty"`
	History any     `json:"history,omitempty"`
	Config  any     `json:"config,omitempty"`
	Version any     `json:"version,omitempty"`
	Error   *string `json:"error,omitempty"`
}

SABnzbdResponse represents the standard SABnzbd API response wrapper

type SABnzbdServer

type SABnzbdServer struct {
	Name         string `json:"name"`
	DisplayName  string `json:"displayname"`
	Host         string `json:"host"`
	Port         int    `json:"port"`
	Timeout      int    `json:"timeout"`
	Username     string `json:"username"`
	Password     string `json:"password"`
	Connections  int    `json:"connections"`
	SSL          int    `json:"ssl"`
	SSLVerify    int    `json:"ssl_verify"`
	SSLCiphers   string `json:"ssl_ciphers"`
	Enable       int    `json:"enable"`
	Required     int    `json:"required"`
	Optional     int    `json:"optional"`
	Retention    int    `json:"retention"`
	ExpireDate   string `json:"expire_date"`
	Quota        string `json:"quota"`
	UsageAtStart int    `json:"usage_at_start"`
	Priority     int    `json:"priority"`
	Notes        string `json:"notes"`
}

SABnzbdServer represents a news server configuration

type SABnzbdStatusResponse

type SABnzbdStatusResponse struct {
	Status          bool    `json:"status"`
	Version         string  `json:"version"`
	Uptime          string  `json:"uptime"`
	Color           string  `json:"color"`
	Darwin          bool    `json:"darwin"`
	Nt              bool    `json:"nt"`
	Pid             int     `json:"pid"`
	NewRelURL       string  `json:"new_rel_url"`
	ActiveDownload  bool    `json:"active_download"`
	Paused          bool    `json:"paused"`
	PauseInt        int     `json:"pause_int"`
	Remaining       string  `json:"remaining"`
	MbLeft          float64 `json:"mbleft"`
	Diskspace1      string  `json:"diskspace1"`
	Diskspace2      string  `json:"diskspace2"`
	DiskspaceTotal1 string  `json:"diskspacetotal1"`
	DiskspaceTotal2 string  `json:"diskspacetotal2"`
	Loadavg         string  `json:"loadavg"`
	Cache           struct {
		Max  int `json:"max"`
		Left int `json:"left"`
		Art  int `json:"art"`
	} `json:"cache"`
	Folders []string           `json:"folders"`
	Slots   []SABnzbdQueueSlot `json:"slots"`
}

SABnzbdStatusResponse represents the full status response

type SABnzbdVersionResponse

type SABnzbdVersionResponse struct {
	Status  bool   `json:"status"`
	Version string `json:"version"`
}

SABnzbdVersionResponse represents the version response

type ScanStatusResponse

type ScanStatusResponse struct {
	Status      string     `json:"status"`
	Path        string     `json:"path,omitempty"`
	StartTime   *time.Time `json:"start_time,omitempty"`
	FilesFound  int        `json:"files_found"`
	FilesAdded  int        `json:"files_added"`
	CurrentFile string     `json:"current_file,omitempty"`
	LastError   *string    `json:"last_error,omitempty"`
}

ScanStatusResponse represents the current status of a manual scan operation

type SegmentInfoResponse

type SegmentInfoResponse struct {
	SegmentSize int64  `json:"segment_size"`
	StartOffset int64  `json:"start_offset"`
	EndOffset   int64  `json:"end_offset"`
	MessageID   string `json:"message_id"`
	Available   bool   `json:"available"`
}

SegmentInfoResponse represents segment information in API responses

type SegmentsInfo

type SegmentsInfo struct {
	TotalSegments   int  `json:"total_segments"`
	MissingSegments int  `json:"missing_segments"`
	CheckedAll      bool `json:"checked_all"`
}

SegmentsInfo provides details about segment checking results

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the API server

func NewServer

func NewServer(
	config *Config,
	queueRepo *database.Repository,
	healthRepo *database.HealthRepository,
	authService *auth.Service,
	userRepo *database.UserRepository,
	configManager ConfigManager,
	metadataReader *metadata.MetadataReader,
	metadataService *metadata.MetadataService,
	nzbFilesystem *nzbfilesystem.NzbFilesystem,
	poolManager pool.Manager,
	importService *importer.Service,
	arrsService *arrs.Service,
	mountService *rclone.MountService,
	progressBroadcaster *progress.ProgressBroadcaster,
	streamTracker *StreamTracker,
	segcacheMgr *segcache.Manager,
) *Server

NewServer creates a new API server that can optionally register routes on the provided mux (for backwards compatibility)

func (*Server) AutoStartFuse

func (s *Server) AutoStartFuse()

AutoStartFuse automatically starts the FUSE mount if enabled in config

func (*Server) GetProgressBroadcaster

func (s *Server) GetProgressBroadcaster() *progress.ProgressBroadcaster

GetProgressBroadcaster returns the progress broadcaster for use by the importer service

func (*Server) IsReady

func (s *Server) IsReady() bool

IsReady returns true if the server is ready to accept requests

func (*Server) ServeHealthSSE

func (s *Server) ServeHealthSSE(w http.ResponseWriter, r *http.Request)

ServeHealthSSE is a native net/http SSE handler for GET /api/health/stream. It bypasses adaptor.FiberApp which cannot stream responses (blocks on Response.Body() reading the SSE pipe until EOF that never comes).

func (*Server) ServeLogsSSE

func (s *Server) ServeLogsSSE(w http.ResponseWriter, r *http.Request)

ServeLogsSSE is a native net/http SSE handler for GET /api/logs/stream. It bypasses adaptor.FiberApp which cannot stream responses (blocks on Response.Body() reading the SSE pipe until EOF that never comes).

func (*Server) ServeQueueSSE

func (s *Server) ServeQueueSSE(w http.ResponseWriter, r *http.Request)

ServeQueueSSE is a native net/http SSE handler for GET /api/queue/stream. It bypasses adaptor.FiberApp which cannot stream responses (blocks on Response.Body() reading the SSE pipe until EOF that never comes).

func (*Server) SetHealthWorker

func (s *Server) SetHealthWorker(healthWorker *health.HealthWorker)

SetHealthWorker sets the health worker reference for the server

func (*Server) SetLibrarySyncWorker

func (s *Server) SetLibrarySyncWorker(librarySyncWorker *health.LibrarySyncWorker)

SetLibrarySyncWorker sets the library sync worker reference for the server

func (*Server) SetLogFilePath

func (s *Server) SetLogFilePath(path string)

SetLogFilePath sets the path to the JSON log file used by the logs endpoints.

func (*Server) SetRcloneClient

func (s *Server) SetRcloneClient(rcloneClient rclonecli.RcloneRcClient)

SetRcloneClient sets the rclone client reference for the server

func (*Server) SetReady

func (s *Server) SetReady(ready bool)

SetReady sets the server as ready to accept requests

func (*Server) SetupRoutes

func (s *Server) SetupRoutes(app *fiber.App)

SetupFiberRoutes configures API routes directly on the Fiber app

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context)

Shutdown shuts down the API server and its managed resources

type StreamHandler

type StreamHandler struct {
	// contains filtered or unexported fields
}

StreamHandler handles HTTP streaming requests for files in NzbFilesystem Uses http.ServeContent for automatic Range request handling, ETag support, and proper HTTP caching semantics

func NewStreamHandler

func NewStreamHandler(fs *nzbfilesystem.NzbFilesystem, userRepo *database.UserRepository, streamTracker *StreamTracker) *StreamHandler

NewStreamHandler creates a new stream handler with the provided filesystem and user repository

func (*StreamHandler) GetHTTPHandler

func (h *StreamHandler) GetHTTPHandler() http.Handler

GetHTTPHandler returns an http.Handler that serves files from NzbFilesystem This handler: - Requires authentication via download_key parameter - Preserves context for logging and health tracking - Uses http.ServeContent for automatic Range request handling - Supports ETag and Last-Modified for caching - Provides proper Content-Type detection

type StreamTracker

type StreamTracker struct {
	// contains filtered or unexported fields
}

StreamTracker tracks active streams

func NewStreamTracker

func NewStreamTracker(metricsTracker usenet.MetricsTracker) *StreamTracker

NewStreamTracker creates a new stream tracker

func (*StreamTracker) Add

func (t *StreamTracker) Add(filePath, source, userName, clientIP, userAgent string, totalSize int64) string

Add adds a new stream and returns its ID (implements nzbfilesystem.StreamTracker)

func (*StreamTracker) AddStream

func (t *StreamTracker) AddStream(filePath, source, userName, clientIP, userAgent string, totalSize int64) *nzbfilesystem.ActiveStream

AddStream adds a new stream and returns the stream object for updates

func (*StreamTracker) GetAll

GetAll returns all active streams, aggregated by file, user, and source

func (*StreamTracker) GetHistory

func (t *StreamTracker) GetHistory() []nzbfilesystem.ActiveStream

GetHistory returns the recent stream history

func (*StreamTracker) GetStream

func (t *StreamTracker) GetStream(id string) *nzbfilesystem.ActiveStream

GetStream returns an active stream by ID

func (*StreamTracker) IncArticlesDownloaded

func (t *StreamTracker) IncArticlesDownloaded()

IncArticlesDownloaded satisfies the usenet.MetricsTracker interface

func (*StreamTracker) IncArticlesPosted

func (t *StreamTracker) IncArticlesPosted()

IncArticlesPosted satisfies the usenet.MetricsTracker interface

func (*StreamTracker) KillStream

func (t *StreamTracker) KillStream(id string) bool

KillStream cancels the context associated with a stream

func (*StreamTracker) Remove

func (t *StreamTracker) Remove(id string)

Remove removes a stream by ID and adds it to history

func (*StreamTracker) SetCancelFunc

func (t *StreamTracker) SetCancelFunc(id string, cancel context.CancelFunc)

SetCancelFunc sets the cancellation function for a stream

func (*StreamTracker) StartCleanup

func (t *StreamTracker) StartCleanup(ctx context.Context)

StartCleanup starts a background goroutine that periodically removes stale streams. Call this once during server startup. The cleanup runs every 5 minutes. The goroutine stops when the context is cancelled.

func (*StreamTracker) Stop

func (t *StreamTracker) Stop()

func (*StreamTracker) UpdateBufferedOffset

func (t *StreamTracker) UpdateBufferedOffset(id string, offset int64)

UpdateBufferedOffset updates the buffered offset for a stream by ID

func (*StreamTracker) UpdateCurrentOffset

func (t *StreamTracker) UpdateCurrentOffset(id string, offset int64)

UpdateCurrentOffset updates the current playback offset for a stream by ID

func (*StreamTracker) UpdateDownloadProgress

func (t *StreamTracker) UpdateDownloadProgress(id string, bytesDownloaded int64)

UpdateDownloadProgress updates the bytes downloaded for a stream by ID

func (*StreamTracker) UpdateProgress

func (t *StreamTracker) UpdateProgress(id string, bytesRead int64)

UpdateProgress updates the bytes sent for a stream by ID

type StremioCleanupService

type StremioCleanupService struct {
	// contains filtered or unexported fields
}

StremioCleanupService periodically removes expired Stremio-originated queue items along with their associated .meta files and temp NZB files.

func NewStremioCleanupService

func NewStremioCleanupService(
	queueRepo *database.Repository,
	metadataService *metadata.MetadataService,
	configGetter config.ConfigGetter,
) *StremioCleanupService

NewStremioCleanupService creates a new StremioCleanupService.

func (*StremioCleanupService) StartCleanup

func (s *StremioCleanupService) StartCleanup(ctx context.Context)

StartCleanup launches a background goroutine that runs cleanup every hour. The goroutine stops when ctx is cancelled.

type StremioStream

type StremioStream struct {
	URL   string `json:"url"`
	Title string `json:"title"`
	Name  string `json:"name"`
}

StremioStream represents a single stream entry in the Stremio addon format.

type StremioStreamsResponse

type StremioStreamsResponse struct {
	Streams     []StremioStream `json:"streams"`
	QueueItemID int64           `json:"_queue_item_id"`
	QueueStatus string          `json:"_queue_status"`
}

StremioStreamsResponse is the response returned by the Stremio stream endpoint. The _queue_item_id and _queue_status fields are AltMount extensions that Stremio ignores.

type SystemCleanupRequest

type SystemCleanupRequest struct {
	QueueOlderThan  *time.Time `json:"queue_older_than"`
	HealthOlderThan *time.Time `json:"health_older_than"`
	DryRun          bool       `json:"dry_run,omitempty"`
}

SystemCleanupRequest represents request for system cleanup

type SystemCleanupResponse

type SystemCleanupResponse struct {
	QueueItemsRemoved    int  `json:"queue_items_removed"`
	HealthRecordsRemoved int  `json:"health_records_removed"`
	DryRun               bool `json:"dry_run"`
}

SystemCleanupResponse represents cleanup operation results

type SystemHealthResponse

type SystemHealthResponse struct {
	Status     string                     `json:"status"` // "healthy", "degraded", "unhealthy"
	Timestamp  time.Time                  `json:"timestamp"`
	Components map[string]ComponentHealth `json:"components"`
}

SystemHealthResponse represents system health check result

type SystemInfoResponse

type SystemInfoResponse struct {
	Version   string    `json:"version,omitempty"`
	GitCommit string    `json:"git_commit,omitempty"`
	StartTime time.Time `json:"start_time"`
	Uptime    string    `json:"uptime"`
	GoVersion string    `json:"go_version,omitempty"`
}

SystemInfoResponse represents system information

type SystemRestartRequest

type SystemRestartRequest struct {
	Force bool `json:"force,omitempty"` // Force restart even if unsafe
}

SystemRestartRequest represents request for system restart

type SystemRestartResponse

type SystemRestartResponse struct {
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
}

SystemRestartResponse represents restart operation result

type SystemStatsResponse

type SystemStatsResponse struct {
	Queue  QueueStatsResponse  `json:"queue"`
	Health HealthStatsResponse `json:"health"`
	System SystemInfoResponse  `json:"system"`
}

SystemStatsResponse represents combined system statistics

type TestConnectionRequest

type TestConnectionRequest struct {
	Type   string `json:"type"`
	URL    string `json:"url"`
	APIKey string `json:"api_key"`
}

TestConnectionRequest represents a request to test connection

type TestProviderResponse

type TestProviderResponse struct {
	Success      bool   `json:"success"`
	ErrorMessage string `json:"error_message,omitempty"`
	RTTMs        int64  `json:"rtt_ms,omitempty"`
}

type UpdateChannel

type UpdateChannel string

UpdateChannel represents the Docker image channel for updates.

const (
	UpdateChannelLatest UpdateChannel = "latest"
	UpdateChannelDev    UpdateChannel = "dev"
)

type UpdateStatusResponse

type UpdateStatusResponse struct {
	CurrentVersion  string        `json:"current_version"`
	GitCommit       string        `json:"git_commit,omitempty"`
	Channel         UpdateChannel `json:"channel"`
	LatestVersion   string        `json:"latest_version,omitempty"`
	UpdateAvailable bool          `json:"update_available"`
	ReleaseURL      string        `json:"release_url,omitempty"`
	DockerAvailable bool          `json:"docker_available"`
}

UpdateStatusResponse represents the current update status.

type UploadAndCheckRequest

type UploadAndCheckRequest struct {
	FilePath         string  `json:"file_path"`
	CheckAllSegments bool    `json:"check_all_segments,omitempty"`
	MaxRetries       *int    `json:"max_retries,omitempty"`
	SourceNzb        *string `json:"source_nzb_path,omitempty"`
}

UploadAndCheckRequest represents request to check health of a file by metadata path

type UploadAndCheckResponse

type UploadAndCheckResponse struct {
	FilePath     string                `json:"file_path"`
	HealthStatus database.HealthStatus `json:"health_status"`
	CheckResult  string                `json:"check_result"`
	ErrorMessage *string               `json:"error_message,omitempty"`
	CheckedAt    time.Time             `json:"checked_at"`
	SegmentsInfo *SegmentsInfo         `json:"segments_info,omitempty"`
}

UploadAndCheckResponse represents response from immediate health check

type UserResponse

type UserResponse struct {
	ID        string `json:"id"`
	Email     string `json:"email,omitempty"`
	Name      string `json:"name"`
	AvatarURL string `json:"avatar_url,omitempty"`
	Provider  string `json:"provider"`
	APIKey    string `json:"api_key,omitempty"`
	IsAdmin   bool   `json:"is_admin"`
	LastLogin string `json:"last_login,omitempty"`
}

UserResponse represents user data for API responses

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WebDAVAPIResponse

type WebDAVAPIResponse struct {
	Port     int    `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"` // Masked if set
	Host     string `json:"host"`
}

WebDAVAPIResponse sanitizes WebDAV config for API responses

Jump to

Keyboard shortcuts

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