database

package
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DB *gorm.DB

Functions

func CleanupOldData

func CleanupOldData() error

CleanupOldData removes old data based on retention policies

func Close

func Close() error

Close closes the database connection

func GetAllModels

func GetAllModels() []interface{}

GetAllModels returns all models for auto-migration

func GetDatabaseStats

func GetDatabaseStats() (map[string]interface{}, error)

GetDatabaseStats returns database statistics

func GetSystemSetting

func GetSystemSetting(key string) (string, error)

GetSystemSetting gets a system setting by key

func Initialize

func Initialize() error

Initialize sets up the database connection and runs migrations

func InvalidateUserCache added in v1.6.0

func InvalidateUserCache(userID uuid.UUID) error

InvalidateUserCache calls the hook to invalidate user cache if set

func IsMultiUserMode

func IsMultiUserMode() bool

Helper functions IsMultiUserMode checks if multi-user mode is enabled

func MigrateSingleUserData added in v1.4.1

func MigrateSingleUserData(adminUserID uuid.UUID) error

MigrateSingleUserData migrates rmapi config and archived files to first admin user

func MigrateToMultiUser

func MigrateToMultiUser() error

MigrateToMultiUser handles the migration from single-user to multi-user mode

func RunAutoMigrations added in v1.5.2

func RunAutoMigrations(logPrefix string) error

RunAutoMigrations runs GORM auto-migration for all models (public wrapper)

func RunMigrations added in v1.4.1

func RunMigrations(logPrefix string) error

RunMigrations runs any pending database migrations using gormigrate

func SaveUserRmapiConfig added in v1.6.0

func SaveUserRmapiConfig(userID uuid.UUID, configContent string) error

SaveUserRmapiConfig saves the rmapi configuration content to the database (global helper)

func SetSystemSetting

func SetSystemSetting(key, value string, updatedBy *uuid.UUID) error

SetSystemSetting sets a system setting

func SetUserCacheCleanupHook added in v1.6.5

func SetUserCacheCleanupHook(hook UserCacheCleanupFunc)

SetUserCacheCleanupHook sets the function to call when user cache files need cleanup

func SetUserCacheInvalidateHook added in v1.6.0

func SetUserCacheInvalidateHook(hook UserCacheInvalidateFunc)

SetUserCacheInvalidateHook sets the function to call when user cache needs invalidation

Types

type APIKey

type APIKey struct {
	ID        uuid.UUID  `gorm:"type:uuid;primaryKey" json:"id"`
	UserID    uuid.UUID  `gorm:"type:uuid;not null;index" json:"user_id"`
	Name      string     `gorm:"not null" json:"name"`
	KeyHash   string     `gorm:"not null;index" json:"-"`            // Never return actual key
	KeyPrefix string     `gorm:"size:16;not null" json:"key_prefix"` // First 16 chars for display
	IsActive  bool       `gorm:"default:true" json:"is_active"`
	LastUsed  *time.Time `json:"last_used,omitempty"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

APIKey represents an API key for a user

func (*APIKey) BeforeCreate

func (a *APIKey) BeforeCreate(tx *gorm.DB) error

type APIKeyService

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

APIKeyService provides API key-related database operations

func NewAPIKeyService

func NewAPIKeyService(db *gorm.DB) *APIKeyService

NewAPIKeyService creates a new API key service

func (*APIKeyService) CleanupExpiredAPIKeys

func (s *APIKeyService) CleanupExpiredAPIKeys() error

CleanupExpiredAPIKeys removes expired API keys

func (*APIKeyService) CreateAPIKeyFromValue

func (s *APIKeyService) CreateAPIKeyFromValue(userID uuid.UUID, name string, apiKey string, expiresAt *time.Time) (*APIKey, error)

CreateAPIKeyFromValue creates an API key record from an existing key value (for migrations)

func (*APIKeyService) DeactivateAPIKey

func (s *APIKeyService) DeactivateAPIKey(keyID uuid.UUID, userID uuid.UUID) error

DeactivateAPIKey deactivates an API key

func (*APIKeyService) DeleteAPIKey

func (s *APIKeyService) DeleteAPIKey(keyID uuid.UUID, userID uuid.UUID) error

DeleteAPIKey permanently deletes an API key

func (*APIKeyService) GenerateAPIKey

func (s *APIKeyService) GenerateAPIKey(userID uuid.UUID, name string, expiresAt *time.Time) (*APIKey, string, error)

GenerateAPIKey creates a new API key for a user

func (*APIKeyService) GetAPIKeyByID

func (s *APIKeyService) GetAPIKeyByID(keyID uuid.UUID, userID uuid.UUID) (*APIKey, error)

GetAPIKeyByID retrieves an API key by ID (for the owner)

func (*APIKeyService) GetAPIKeyStats

func (s *APIKeyService) GetAPIKeyStats() (map[string]interface{}, error)

GetAPIKeyStats returns API key statistics

func (*APIKeyService) GetActiveUserAPIKeys

func (s *APIKeyService) GetActiveUserAPIKeys(userID uuid.UUID) ([]APIKey, error)

GetActiveUserAPIKeys retrieves all active API keys for a user

func (*APIKeyService) GetUserAPIKeys

func (s *APIKeyService) GetUserAPIKeys(userID uuid.UUID) ([]APIKey, error)

GetUserAPIKeys retrieves all API keys for a user

func (*APIKeyService) UpdateAPIKeyName

func (s *APIKeyService) UpdateAPIKeyName(keyID uuid.UUID, userID uuid.UUID, newName string) error

UpdateAPIKeyName updates the name of an API key

func (*APIKeyService) ValidateAPIKey

func (s *APIKeyService) ValidateAPIKey(apiKey string) (*User, error)

ValidateAPIKey validates an API key and returns the associated user

func (*APIKeyService) ValidateAPIKeyConstantTime

func (s *APIKeyService) ValidateAPIKeyConstantTime(providedKey string) (*User, error)

ValidateAPIKeyConstantTime validates an API key with constant time comparison

type BackupJob added in v1.4.1

type BackupJob struct {
	ID             uuid.UUID  `gorm:"type:uuid;primaryKey" json:"id"`
	AdminUserID    uuid.UUID  `gorm:"type:uuid;not null;index" json:"admin_user_id"`
	Status         string     `gorm:"size:50;not null;default:pending" json:"status"`
	Progress       int        `gorm:"default:0" json:"progress"`
	IncludeFiles   bool       `gorm:"default:true" json:"include_files"`
	IncludeConfigs bool       `gorm:"default:true" json:"include_configs"`
	UserIDs        string     `gorm:"type:text" json:"user_ids,omitempty"`
	FilePath       string     `gorm:"size:1000" json:"file_path,omitempty"`
	Filename       string     `gorm:"size:255" json:"filename,omitempty"`
	FileSize       int64      `json:"file_size,omitempty"`
	ErrorMessage   string     `gorm:"type:text" json:"error_message,omitempty"`
	StartedAt      *time.Time `json:"started_at,omitempty"`
	CompletedAt    *time.Time `json:"completed_at,omitempty"`
	ExpiresAt      *time.Time `json:"expires_at,omitempty"`
	CreatedAt      time.Time  `json:"created_at"`

	// Association
	AdminUser User `gorm:"foreignKey:AdminUserID;constraint:OnDelete:CASCADE" json:"-"`
}

BackupJob represents a background backup operation

func (*BackupJob) BeforeCreate added in v1.4.1

func (b *BackupJob) BeforeCreate(tx *gorm.DB) error

type DatabaseConfig

type DatabaseConfig struct {
	Type     string // "sqlite" or "postgres"
	Host     string
	Port     int
	User     string
	Password string
	DBName   string
	SSLMode  string
	DataDir  string // For SQLite
}

DatabaseConfig holds database configuration

func GetDatabaseConfig

func GetDatabaseConfig() *DatabaseConfig

GetDatabaseConfig reads database configuration from environment variables

type Document

type Document struct {
	ID           uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID       uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	DocumentName string    `gorm:"not null" json:"document_name"`
	LocalPath    string    `gorm:"size:1000" json:"local_path,omitempty"`
	RemotePath   string    `gorm:"size:1000" json:"remote_path,omitempty"`
	DocumentType string    `gorm:"size:50" json:"document_type,omitempty"`
	FileSize     int64     `json:"file_size,omitempty"`
	Status       string    `gorm:"size:50;default:uploaded" json:"status"`
	UploadDate   time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"upload_date"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

Document represents a document uploaded/downloaded by a user

func (*Document) BeforeCreate

func (d *Document) BeforeCreate(tx *gorm.DB) error

type FolderCache

type FolderCache struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID      uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	FolderPath  string    `gorm:"size:1000;not null" json:"folder_path"`
	FolderData  string    `gorm:"type:text" json:"folder_data"` // JSON data
	LastUpdated time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"last_updated"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

FolderCache represents cached folder data for a user

func (*FolderCache) BeforeCreate

func (f *FolderCache) BeforeCreate(tx *gorm.DB) error

func (FolderCache) TableName

func (FolderCache) TableName() string

Add unique constraint for user_id + folder_path

type LoginAttempt

type LoginAttempt struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	IPAddress   string    `gorm:"size:45;not null;index" json:"ip_address"`
	Username    string    `gorm:"index" json:"username,omitempty"`
	Success     bool      `gorm:"default:false" json:"success"`
	AttemptedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;index" json:"attempted_at"`
	UserAgent   string    `gorm:"type:text" json:"user_agent,omitempty"`
}

LoginAttempt represents a login attempt for rate limiting

func (*LoginAttempt) BeforeCreate

func (l *LoginAttempt) BeforeCreate(tx *gorm.DB) error

type RestoreExtractionJob added in v1.5.4

type RestoreExtractionJob struct {
	ID              uuid.UUID  `gorm:"type:uuid;primaryKey" json:"id"`
	AdminUserID     uuid.UUID  `gorm:"type:uuid;not null;index" json:"admin_user_id"`
	RestoreUploadID uuid.UUID  `gorm:"type:uuid;not null;index" json:"restore_upload_id"`
	Status          string     `gorm:"size:50;not null;default:pending" json:"status"`
	Progress        int        `gorm:"default:0" json:"progress"`
	StatusMessage   string     `gorm:"type:text" json:"status_message,omitempty"`
	ErrorMessage    string     `gorm:"type:text" json:"error_message,omitempty"`
	ExtractedPath   string     `gorm:"size:1000" json:"extracted_path,omitempty"`
	StartedAt       *time.Time `json:"started_at,omitempty"`
	CompletedAt     *time.Time `json:"completed_at,omitempty"`
	CreatedAt       time.Time  `json:"created_at"`

	// Associations
	AdminUser     User          `gorm:"foreignKey:AdminUserID;constraint:OnDelete:CASCADE" json:"-"`
	RestoreUpload RestoreUpload `gorm:"foreignKey:RestoreUploadID;constraint:OnDelete:CASCADE" json:"-"`
}

RestoreExtractionJob represents a background tar extraction operation for restore

func (*RestoreExtractionJob) BeforeCreate added in v1.5.4

func (r *RestoreExtractionJob) BeforeCreate(tx *gorm.DB) error

type RestoreUpload added in v1.4.1

type RestoreUpload struct {
	ID          uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	AdminUserID uuid.UUID `gorm:"type:uuid;not null;index" json:"admin_user_id"`
	Filename    string    `gorm:"size:255;not null" json:"filename"`
	FilePath    string    `gorm:"size:1000;not null" json:"file_path"`
	FileSize    int64     `json:"file_size"`
	Status      string    `gorm:"size:50;not null;default:uploaded" json:"status"`
	ExpiresAt   time.Time `gorm:"not null" json:"expires_at"`
	CreatedAt   time.Time `json:"created_at"`

	// Association
	AdminUser User `gorm:"foreignKey:AdminUserID;constraint:OnDelete:CASCADE" json:"-"`
}

RestoreUpload represents an uploaded restore file waiting for confirmation

func (*RestoreUpload) BeforeCreate added in v1.4.1

func (r *RestoreUpload) BeforeCreate(tx *gorm.DB) error

type SystemSetting

type SystemSetting struct {
	Key         string     `gorm:"primaryKey" json:"key"`
	Value       string     `gorm:"type:text" json:"value"`
	Description string     `gorm:"type:text" json:"description,omitempty"`
	UpdatedAt   time.Time  `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
	UpdatedBy   *uuid.UUID `gorm:"type:uuid" json:"updated_by,omitempty"`

	// Association
	UpdatedByUser *User `gorm:"foreignKey:UpdatedBy" json:"-"`
}

SystemSetting represents system-wide configuration

type User

type User struct {
	ID       uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	Username string    `gorm:"uniqueIndex;not null" json:"username"`
	Email    string    `gorm:"uniqueIndex;not null" json:"email"`
	Password string    `gorm:"not null" json:"-"` // Never return password in JSON
	IsAdmin  bool      `gorm:"default:false" json:"is_admin"`
	IsActive bool      `gorm:"default:true" json:"is_active"`

	// User-specific settings
	RmapiHost              string  `gorm:"column:rmapi_host" json:"rmapi_host,omitempty"`
	DefaultRmdir           string  `gorm:"column:default_rmdir;default:/" json:"default_rmdir"`
	FolderRefreshPercent   int     `gorm:"column:folder_refresh_percent;default:0" json:"folder_refresh_percent"`
	CoverpageSetting       string  `gorm:"column:coverpage_setting" json:"coverpage_setting"`
	ConflictResolution     string  `gorm:"column:conflict_resolution;default:abort" json:"conflict_resolution"`
	FolderDepthLimit       int     `gorm:"column:folder_depth_limit;default:0" json:"folder_depth_limit"`
	FolderExclusionList    string  `gorm:"column:folder_exclusion_list" json:"folder_exclusion_list"`
	PageResolution         string  `gorm:"column:page_resolution" json:"page_resolution,omitempty"`
	PageDPI                float64 `gorm:"column:page_dpi" json:"page_dpi,omitempty"`
	ConversionOutputFormat string  `gorm:"column:conversion_output_format;default:epub" json:"conversion_output_format,omitempty"`
	RmapiConfig            string  `gorm:"column:rmapi_config;type:text" json:"-"` // Never return config in JSON

	// PDF processing settings
	PDFBackgroundRemoval *bool `gorm:"column:pdf_background_removal" json:"pdf_background_removal"`

	// Password reset
	ResetToken        string    `gorm:"index" json:"-"`
	ResetTokenExpires time.Time `json:"-"`

	// OIDC integration
	OidcSubject *string `gorm:"column:oidc_subject;uniqueIndex" json:"oidc_subject,omitempty"`

	// Timestamps
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	LastLogin *time.Time `json:"last_login,omitempty"`

	// Associations
	APIKeys      []APIKey      `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	Sessions     []UserSession `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	FoldersCache []FolderCache `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
	Documents    []Document    `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
}

User represents a user account in the system

func CreateDefaultAdminUser

func CreateDefaultAdminUser(username, email, password string) (*User, error)

CreateDefaultAdminUser creates a default admin user if none exists

func GetCurrentUser

func GetCurrentUser(userID uuid.UUID) (*User, error)

GetCurrentUser gets the current user from the database by ID

func GetUserByEmail

func GetUserByEmail(email string) (*User, error)

GetUserByEmail gets a user by email

func GetUserByEmailWithoutOIDC added in v1.4.1

func GetUserByEmailWithoutOIDC(email string) (*User, error)

GetUserByEmailWithoutOIDC gets a user by email without an OIDC subject

func GetUserByOIDCSubject added in v1.4.1

func GetUserByOIDCSubject(oidcSubject string) (*User, error)

GetUserByOIDCSubject gets a user by OIDC subject

func GetUserByUsername

func GetUserByUsername(username string) (*User, error)

GetUserByUsername gets a user by username

func GetUserByUsernameWithoutOIDC added in v1.4.1

func GetUserByUsernameWithoutOIDC(username string) (*User, error)

GetUserByUsernameWithoutOIDC gets a user by username without an OIDC subject

func (*User) BeforeCreate

func (u *User) BeforeCreate(tx *gorm.DB) error

BeforeCreate sets UUID and randomized folder refresh minute if not already set

type UserCacheCleanupFunc added in v1.6.5

type UserCacheCleanupFunc func(userID uuid.UUID)

UserCacheCleanupFunc is a function type for cleaning up user cache files

type UserCacheInvalidateFunc added in v1.6.0

type UserCacheInvalidateFunc func(userID uuid.UUID) error

UserCacheInvalidateFunc is a function type for invalidating user cache

type UserService

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

UserService provides user-related database operations

func NewUserService

func NewUserService(db *gorm.DB) *UserService

NewUserService creates a new user service

func (*UserService) ActivateUser

func (s *UserService) ActivateUser(userID uuid.UUID) error

ActivateUser reactivates a user

func (*UserService) AuthenticateUser

func (s *UserService) AuthenticateUser(username, password string) (*User, error)

AuthenticateUser validates user credentials and returns user if valid

func (*UserService) CleanupExpiredResetTokens

func (s *UserService) CleanupExpiredResetTokens() error

CleanupExpiredResetTokens removes expired reset tokens

func (*UserService) CleanupExpiredSessions

func (s *UserService) CleanupExpiredSessions() error

CleanupExpiredSessions removes expired sessions

func (*UserService) CreateUser

func (s *UserService) CreateUser(username, email, password string, isAdmin bool) (*User, error)

CreateUser creates a new user with hashed password

func (*UserService) DeactivateUser

func (s *UserService) DeactivateUser(userID uuid.UUID) error

DeactivateUser deactivates a user instead of deleting

func (*UserService) DeleteUser

func (s *UserService) DeleteUser(userID uuid.UUID) error

DeleteUser permanently deletes a user and all associated data

func (*UserService) GeneratePasswordResetToken

func (s *UserService) GeneratePasswordResetToken(email string) (string, error)

GeneratePasswordResetToken generates a reset token for password recovery

func (*UserService) GetAllUsers

func (s *UserService) GetAllUsers() ([]User, error)

GetAllUsers retrieves all users (for admin)

func (*UserService) GetUserByID

func (s *UserService) GetUserByID(userID uuid.UUID) (*User, error)

GetUserByID retrieves a user by ID

func (*UserService) GetUserStats

func (s *UserService) GetUserStats(userID uuid.UUID) (map[string]interface{}, error)

GetUserStats returns user statistics

func (*UserService) SaveUserRmapiConfig added in v1.6.0

func (s *UserService) SaveUserRmapiConfig(userID uuid.UUID, configContent string) error

SaveUserRmapiConfig saves the rmapi configuration content to the database

func (*UserService) SetUserAdmin

func (s *UserService) SetUserAdmin(userID uuid.UUID, isAdmin bool) error

SetUserAdmin sets or removes admin privileges

func (*UserService) UpdateUserPassword

func (s *UserService) UpdateUserPassword(userID uuid.UUID, newPassword string) error

UpdateUserPassword updates a user's password

func (*UserService) UpdateUserSettings

func (s *UserService) UpdateUserSettings(userID uuid.UUID, settings map[string]interface{}) error

UpdateUserSettings updates user-specific settings

func (*UserService) ValidatePasswordResetToken

func (s *UserService) ValidatePasswordResetToken(token string) (*User, error)

ValidatePasswordResetToken validates a reset token and returns the user

type UserSession

type UserSession struct {
	ID        uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID    uuid.UUID `gorm:"type:uuid;not null;index" json:"user_id"`
	TokenHash string    `gorm:"not null;index" json:"-"`
	ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	LastUsed  time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"last_used"`
	UserAgent string    `gorm:"type:text" json:"user_agent,omitempty"`
	IPAddress string    `gorm:"size:45" json:"ip_address,omitempty"`

	// Association
	User User `gorm:"foreignKey:UserID" json:"-"`
}

UserSession represents a user's login session

func (*UserSession) BeforeCreate

func (s *UserSession) BeforeCreate(tx *gorm.DB) error

Jump to

Keyboard shortcuts

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