filtering

package
v0.26.2 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// CacheMaxAge is the maximum age of the filter cache before it's considered stale.
	CacheMaxAge = 24 * time.Hour
)
View Source
const FilterIdentifier = "ublock-combined"

FilterIdentifier is the identifier used when storing/loading compiled filters.

View Source
const GitHubReleaseURL = "https://github.com/bnema/ublock-webkit-filters/releases/latest/download"

GitHubReleaseURL is the base URL for downloading filter files.

Variables

View Source
var FilterFiles = struct {
	Manifest string
	Combined []string
}{
	Manifest: "manifest.json",
	Combined: []string{
		"combined-part1.json",
		"combined-part2.json",
		"combined-part3.json",
	},
}

FilterFiles defines the files to download from GitHub releases.

Functions

This section is empty.

Types

type CombinedInfo

type CombinedInfo struct {
	TotalRules int      `json:"total_rules"`
	Files      []string `json:"files"`
}

CombinedInfo contains metadata for the combined (merged) filter set.

type CompileResult

type CompileResult struct {
	Filter *webkit.UserContentFilter
	Err    error
}

CompileResult holds the result of a filter compilation.

type DownloadProgress

type DownloadProgress struct {
	File       string
	Current    int
	Total      int
	BytesTotal int64
}

DownloadProgress reports download progress.

type Downloader

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

Downloader handles downloading filter files from GitHub releases.

func NewDownloader

func NewDownloader(cacheDir string) *Downloader

NewDownloader creates a new Downloader. cacheDir is where downloaded JSON files will be stored.

func (*Downloader) ClearCache

func (d *Downloader) ClearCache() error

ClearCache removes all cached filter files.

func (*Downloader) DownloadFilters

func (d *Downloader) DownloadFilters(ctx context.Context, onProgress func(DownloadProgress)) ([]string, error)

DownloadFilters downloads filter JSON files from GitHub releases. Returns the paths to the downloaded files.

func (*Downloader) FetchManifest

func (d *Downloader) FetchManifest(ctx context.Context) (*Manifest, error)

FetchManifest downloads the latest manifest.json from GitHub.

func (*Downloader) GetCachedFilterPaths

func (d *Downloader) GetCachedFilterPaths() []string

GetCachedFilterPaths returns paths to cached filter JSON files. Returns nil if any files are missing.

func (*Downloader) GetCachedManifest

func (d *Downloader) GetCachedManifest() (*Manifest, error)

GetCachedManifest reads the locally cached manifest.json. Returns nil if no cached manifest exists.

func (*Downloader) HasCachedFilters

func (d *Downloader) HasCachedFilters() bool

HasCachedFilters checks if all filter JSON files are cached.

func (*Downloader) IsCacheStale

func (d *Downloader) IsCacheStale(maxAge time.Duration) bool

IsCacheStale checks if the cached manifest is older than maxAge. Returns true if cache is stale or doesn't exist.

func (*Downloader) NeedsUpdate

func (d *Downloader) NeedsUpdate(ctx context.Context) (bool, error)

NeedsUpdate checks if filters need to be updated based on manifest version.

type FetchIdentifiersResult

type FetchIdentifiersResult struct {
	Identifiers []string
	Err         error
}

FetchIdentifiersResult holds the result of fetching filter identifiers.

type FilterDownloader

type FilterDownloader interface {
	// GetCachedManifest reads the locally cached manifest.json.
	GetCachedManifest() (*Manifest, error)

	// FetchManifest downloads the latest manifest.json from the remote source.
	FetchManifest(ctx context.Context) (*Manifest, error)

	// DownloadFilters downloads filter JSON files from the remote source.
	DownloadFilters(ctx context.Context, onProgress func(DownloadProgress)) ([]string, error)

	// NeedsUpdate checks if filters need to be updated based on manifest version.
	NeedsUpdate(ctx context.Context) (bool, error)

	// ClearCache removes all cached filter files.
	ClearCache() error

	// HasCachedFilters checks if all filter JSON files are cached.
	HasCachedFilters() bool

	// GetCachedFilterPaths returns paths to cached filter JSON files.
	GetCachedFilterPaths() []string

	// IsCacheStale checks if the cached manifest is older than maxAge.
	IsCacheStale(maxAge time.Duration) bool
}

FilterDownloader abstracts the filter download operations. This interface enables testing without requiring network access.

type FilterState

type FilterState string

FilterState represents the current state of the content filter system.

const (
	// StateUninitialized means the filter manager has not been initialized yet.
	StateUninitialized FilterState = "uninitialized"
	// StateLoading means filters are being downloaded or compiled.
	StateLoading FilterState = "loading"
	// StateActive means filters are loaded and active.
	StateActive FilterState = "active"
	// StateDisabled means filtering is disabled by configuration.
	StateDisabled FilterState = "disabled"
	// StateError means an error occurred during filter loading.
	StateError FilterState = "error"
)

type FilterStatus

type FilterStatus struct {
	State   FilterState
	Message string
	Version string
}

FilterStatus represents the current status of the content filter system. Used for UI toast notifications and status reporting.

type FilterStore

type FilterStore interface {
	// Compile compiles a JSON filter file and stores it with the given identifier.
	Compile(ctx context.Context, identifier string, jsonPath string) (*webkit.UserContentFilter, error)

	// Load loads a previously compiled filter by its identifier.
	Load(ctx context.Context, identifier string) (*webkit.UserContentFilter, error)

	// Remove removes a compiled filter by its identifier.
	Remove(ctx context.Context, identifier string) error

	// HasCompiledFilter checks if a compiled filter exists for the given identifier.
	HasCompiledFilter(ctx context.Context, identifier string) bool

	// FetchIdentifiers returns all stored filter identifiers.
	FetchIdentifiers(ctx context.Context) ([]string, error)

	// Path returns the storage path for compiled filters.
	Path() string
}

FilterStore abstracts the WebKit UserContentFilterStore operations. This interface enables testing without requiring GTK/WebKit.

type ListInfo

type ListInfo struct {
	Name         string `json:"name"`
	SourceURL    string `json:"source_url"`
	RulesCount   int    `json:"rules_count"`
	SkippedCount int    `json:"skipped_count"`
}

ListInfo contains metadata for a single filter list.

type LoadResult

type LoadResult struct {
	Filter *webkit.UserContentFilter
	Err    error
}

LoadResult holds the result of loading a compiled filter.

type Manager

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

Manager orchestrates the content filter lifecycle. It handles downloading, compiling, loading, and applying filters to WebViews.

func NewManager

func NewManager(cfg ManagerConfig) (*Manager, error)

NewManager creates a new filter Manager.

func (*Manager) ApplyTo

func (m *Manager) ApplyTo(ctx context.Context, ucm *webkit.UserContentManager)

ApplyTo adds the active filter to a WebView's UserContentManager. Safe to call even if filters are not yet loaded (no-op in that case).

func (*Manager) CheckForUpdates

func (m *Manager) CheckForUpdates(ctx context.Context) error

CheckForUpdates checks if newer filters are available and downloads them. This should be called periodically in the background.

func (*Manager) Clear

func (m *Manager) Clear(ctx context.Context) error

Clear removes all compiled and cached filters.

func (*Manager) Disable

func (m *Manager) Disable(ctx context.Context)

Disable disables content filtering.

func (*Manager) Enable

func (m *Manager) Enable(ctx context.Context)

Enable enables content filtering.

func (*Manager) GetFilter

func (m *Manager) GetFilter() *webkit.UserContentFilter

GetFilter returns the currently loaded filter, or nil if none.

func (*Manager) Initialize

func (m *Manager) Initialize(ctx context.Context) error

Initialize performs fast initialization. This is called BEFORE GTK starts, so we cannot use GIO async operations. Just sets up state - actual filter loading happens in LoadAsync after GTK starts.

func (*Manager) IsEnabled

func (m *Manager) IsEnabled() bool

IsEnabled returns whether content filtering is enabled.

func (*Manager) LoadAsync

func (m *Manager) LoadAsync(ctx context.Context)

LoadAsync loads or downloads filters in the background. Call this after the browser window is shown (GTK main loop running). First tries to load from cache, then downloads if needed.

func (*Manager) SetStatusCallback

func (m *Manager) SetStatusCallback(cb func(FilterStatus))

SetStatusCallback sets a callback for status changes (e.g., for toast notifications).

func (*Manager) Status

func (m *Manager) Status() FilterStatus

Status returns the current filter status.

type ManagerConfig

type ManagerConfig struct {
	StoreDir   string // Where to store compiled filter bytecode
	JSONDir    string // Where to cache downloaded JSON files
	Enabled    bool   // Whether filtering is enabled
	AutoUpdate bool   // Whether to auto-update filters

	// Optional: custom implementations for testing
	Store      FilterStore      // If nil, creates default Store
	Downloader FilterDownloader // If nil, creates default Downloader
}

ManagerConfig holds configuration for the filter manager.

type Manifest

type Manifest struct {
	Version     string              `json:"version"`
	GeneratedAt time.Time           `json:"generated_at"`
	Lists       map[string]ListInfo `json:"lists"`
	Combined    CombinedInfo        `json:"combined"`
}

Manifest represents the manifest.json from ublock-webkit-filters releases. It contains metadata about the filter lists and their rule counts.

type Store

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

Store wraps webkit.UserContentFilterStore with Go-friendly async operations.

func NewStore

func NewStore(storagePath string) *Store

NewStore creates a new Store at the given path. The path is where WebKit will store compiled filter bytecode.

func (*Store) Compile

func (s *Store) Compile(ctx context.Context, identifier, jsonPath string) (*webkit.UserContentFilter, error)

Compile compiles a JSON filter file and stores it with the given identifier. This is an async operation that may take several seconds for large filter sets. The JSON file must be in Safari Content Blocker format.

func (*Store) FetchIdentifiers

func (s *Store) FetchIdentifiers(ctx context.Context) ([]string, error)

FetchIdentifiers returns all stored filter identifiers.

func (*Store) HasCompiledFilter

func (s *Store) HasCompiledFilter(ctx context.Context, identifier string) bool

HasCompiledFilter checks if a compiled filter exists for the given identifier.

func (*Store) Load

func (s *Store) Load(ctx context.Context, identifier string) (*webkit.UserContentFilter, error)

Load loads a previously compiled filter by its identifier. This is fast (~50ms) as it loads pre-compiled bytecode.

func (*Store) Path

func (s *Store) Path() string

Path returns the storage path for compiled filters.

func (*Store) Remove

func (s *Store) Remove(ctx context.Context, identifier string) error

Remove removes a compiled filter by its identifier.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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