api

package
v0.0.1-alpha5 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: MIT Imports: 43 Imported by: 0

Documentation

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

View Source
const (
	ErrMsgInternalServer = "An internal server error occurred"
	ErrMsgBadRequest     = "Invalid request format"
	ErrMsgNotFound       = "Resource not found"
	ErrMsgValidation     = "Request validation failed"
	ErrMsgConflict       = "Resource conflict"
	ErrMsgUnauthorized   = "Authentication required"
	ErrMsgForbidden      = "Access forbidden"
)

Standard error messages

Variables

This section is empty.

Functions

func ApplyLogLevel

func ApplyLogLevel(level string)

ApplyLogLevel applies the log level to the global logger

func ParseTimeParam

func ParseTimeParam(r *http.Request, param string) (*time.Time, error)

ParseTimeParam extracts time parameter from query string

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 WriteBadRequest

func WriteBadRequest(w http.ResponseWriter, message string, details string)

WriteBadRequest writes a bad request response

func WriteForbidden

func WriteForbidden(w http.ResponseWriter, message string, details string)

WriteForbidden writes a forbidden response

func WriteInternalError

func WriteInternalError(w http.ResponseWriter, message string, details string)

WriteInternalError writes an internal server error response

func WriteSuccess

func WriteSuccess(w http.ResponseWriter, data interface{}, meta interface{})

WriteSuccess writes a success response

func WriteUnauthorized

func WriteUnauthorized(w http.ResponseWriter, message string, details string)

WriteUnauthorized writes an unauthorized response

Types

type APIError

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

APIError represents an error response

func NewAPIError

func NewAPIError(code, message, details string) *APIError

NewAPIError creates a new API error

type APIErrorResponse

type APIErrorResponse struct {
	Success bool      `json:"success"`
	Error   *APIError `json:"error"`
}

APIErrorResponse represents a structured error response

func NewAPIErrorResponse

func NewAPIErrorResponse(code, message, details string) *APIErrorResponse

NewAPIErrorResponse creates a new API 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    interface{} `json:"data,omitempty"`
	Error   *APIError   `json:"error,omitempty"`
	Meta    *APIMeta    `json:"meta,omitempty"`
}

APIResponse represents a standard API response wrapper

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"`
	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"`
	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 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 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
	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
}

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
	UpdateConfig(config *config.Config) error
	ValidateConfig(config *config.Config) error
	ValidateConfigUpdate(config *config.Config) error
	OnConfigChange(callback config.ChangeCallback)
	ReloadConfig() error
	SaveConfig() error
}

ConfigManager interface defines methods for configuration management

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"`
}

FileMetadataResponse represents file metadata information in API responses

type HealthCheckRequest

type HealthCheckRequest struct {
	FilePath   string  `json:"file_path"`
	MaxRetries *int    `json:"max_retries,omitempty"`
	SourceNzb  *string `json:"source_nzb_path,omitempty"`
	Priority   bool    `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"`
}

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"`
}

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"`
	PendingManualChecks    int        `json:"pending_manual_checks"`
	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"`
	ImportCacheSizeMB              int                   `json:"import_cache_size_mb"`
	SegmentSamplePercentage        int                   `json:"segment_sample_percentage"` // Percentage of segments to check (1-100)
	ImportStrategy                 config.ImportStrategy `json:"import_strategy"`
	ImportDir                      *string               `json:"import_dir,omitempty"`
}

ImportAPIResponse handles Import config for API responses

func ToImportAPIResponse

func ToImportAPIResponse(importConfig config.ImportConfig) ImportAPIResponse

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) *LibrarySyncHandlers

NewLibrarySyncHandlers creates a new instance of library sync handlers

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 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 ParsePagination

func ParsePagination(r *http.Request) Pagination

ParsePagination extracts pagination parameters from query string

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"`
	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"`
	DownloadSpeedBytesPerSec float64                  `json:"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"`
	PasswordSet      bool   `json:"password_set"`
	Enabled          bool   `json:"enabled"`
	IsBackupProvider bool   `json:"is_backup_provider"`
}

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"`
	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 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"`
}

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"`
}

ProviderTestRequest represents a request to test provider connectivity

type ProviderTestResponse

type ProviderTestResponse struct {
	Success      bool   `json:"success"`
	ErrorMessage string `json:"error_message,omitempty"`
}

ProviderTestResponse represents the result of testing 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"`
	Enabled          *bool   `json:"enabled,omitempty"`
	IsBackupProvider *bool   `json:"is_backup_provider,omitempty"`
}

ProviderUpdateRequest represents a request to update an existing provider

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
}

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"`

	// RC (Remote Control) Configuration
	RCEnabled bool              `json:"rc_enabled"`
	RCUrl     string            `json:"rc_url"`
	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"`
	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) 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"`
	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"`
	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, basePath 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"`
}

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"`
	Percentage string `json:"percentage"`
	Status     string `json:"status"`
	Timeleft   string `json:"timeleft"`
	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   interface{} `json:"queue,omitempty"`
	History interface{} `json:"history,omitempty"`
	Config  interface{} `json:"config,omitempty"`
	Version interface{} `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,
	mediaRepo *database.MediaRepository,
	authService *auth.Service,
	userRepo *database.UserRepository,
	configManager ConfigManager,
	metadataReader *metadata.MetadataReader,
	nzbFilesystem *nzbfilesystem.NzbFilesystem,
	poolManager pool.Manager,
	importService *importer.Service,
	arrsService *arrs.Service,
	mountService *rclone.MountService,
	progressBroadcaster *progress.ProgressBroadcaster,
) *Server

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

func (*Server) GetProgressBroadcaster

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

GetProgressBroadcaster returns the progress broadcaster for use by the importer service

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

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

SetRcloneClient sets the rclone client reference for the server

func (*Server) SetupRoutes

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

SetupFiberRoutes configures API routes directly on the Fiber app

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) *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 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"`
	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"`
}

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

Jump to

Keyboard shortcuts

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