imaging

package
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: GPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxImageWidth  = 10000
	MaxImageHeight = 10000
)

MaxImageWidth and MaxImageHeight are the stored-image dimension caps. They are exported so callers that downscale can report the limit they fitted to.

Variables

This section is empty.

Functions

func CanonicalUploadRoot added in v0.23.0

func CanonicalUploadRoot(uploadDir string) (canonicalRoot string, resultErr error)

CanonicalUploadRoot resolves and opens the configured uploads directory, returning the canonical absolute root named by that verified capability. Long-lived workflows capture this once before their first write and use the returned path for every write, compensating cleanup, and durable retry. A later retarget of a configured symlink therefore cannot redirect cleanup.

func CreateVariantFromRoot added in v0.23.0

func CreateVariantFromRoot(
	uploadRoot *os.Root,
	mediaUUID, filename, variantType string,
) (*VariantResult, *RootFileCreation, error)

CreateVariantFromRoot creates one standard variant without resolving an ordinary filesystem path. Both the original read and the exclusive variant publish stay bound to uploadRoot, even if its former pathname is renamed or replaced while a multi-file import is in progress.

func DeleteMediaFiles added in v0.23.0

func DeleteMediaFiles(uploadDir, mediaUUID string) error

DeleteMediaFiles removes every directory that can contain files for one media UUID. The UUID and each joined path are validated before removal.

Every directory is attempted even after a failure. Returning errors.Join of all failures prevents one unwritable variant from hiding additional orphaned directories and gives callers enough information to retain a durable retry.

func DeleteMediaFilesFromCanonicalRoot added in v0.23.0

func DeleteMediaFilesFromCanonicalRoot(uploadDir, mediaUUID string) error

DeleteMediaFilesFromCanonicalRoot removes media files only when uploadDir is still the canonical, non-symlink root recorded by a durable cleanup queue. The equality check happens inside the same capability-opening operation as deletion, so replacing the queued directory with a symlink between an outer validation and this call cannot retarget cleanup outside the persisted root.

func DeleteMediaFilesFromRoot added in v0.23.0

func DeleteMediaFilesFromRoot(uploadRoot *os.Root, mediaUUID string) error

DeleteMediaFilesFromRoot removes one media UUID through an already verified caller-owned root capability. Keeping the capability open binds cleanup to the directory that received the writes even if its canonical pathname is renamed and replaced before compensation runs.

func IsCanonicalMediaUUID added in v0.23.0

func IsCanonicalMediaUUID(value string) bool

IsCanonicalMediaUUID reports whether value is a canonical hyphenated UUID. It is deliberately stricter than uuid.Parse, which also accepts unhyphenated and URN forms. Media UUIDs become directory names, so deletion accepts one unambiguous representation only.

func OpenExistingUploadRoot added in v0.23.0

func OpenExistingUploadRoot(uploadDir string) (*os.Root, error)

OpenExistingUploadRoot resolves an already existing uploads directory and returns the same verified root capability as OpenUploadRoot without creating anything. A missing directory is reported as a nil root so read-only preflights can prove storage freshness without mutating the filesystem.

func OpenUploadRoot added in v0.23.0

func OpenUploadRoot(uploadDir string) (*os.Root, error)

OpenUploadRoot resolves the configured uploads directory and returns a verified root capability. Callers that perform a multi-file operation keep this handle open, use Name as the canonical cleanup identity, and never need to re-resolve a mutable configured symlink between individual writes.

func SameRootFile added in v0.23.0

func SameRootFile(current, recorded fs.FileInfo) bool

SameRootFile reports whether current is still the exact file recorded in identity.

os.SameFile compares only the device and inode numbers, and a filesystem is free to hand the inode number of a deleted file straight back to the next file created in its place. On Linux that happens routinely: removing a file and recreating it at the same path usually reuses the inode, so a check built on os.SameFile alone accepts the replacement as the recorded file and then deletes, or vouches for, content it does not own. Requiring the recorded size and modification time to match as well closes that window, since a replacement writes its own bytes at its own time.

Directories cannot use this: an import adds entries to a directory it owns after recording it, which moves both size and modification time. Their replacement is caught instead by the per-file checks of the entries inside.

func ValidateImage added in v0.23.0

func ValidateImage(reader io.Reader) (width, height int, mimeType string, resultErr error)

ValidateImage fully decodes an untrusted image after enforcing the same byte, dimension, and pixel limits as ProcessImage. It performs no filesystem writes.

func ValidateMediaCleanupTarget added in v0.23.0

func ValidateMediaCleanupTarget(uploadDir, mediaUUID string) (resultErr error)

ValidateMediaCleanupTarget proves that a media UUID and configured uploads root are safe to use before a caller performs an irreversible database delete. It does not remove files. DeleteMediaFiles repeats the validation when cleanup actually runs, closing any replacement race between the two operations.

func ValidateOpenUploadRootIdentity added in v0.23.0

func ValidateOpenUploadRootIdentity(uploadRoot *os.Root, canonicalRoot string) error

ValidateOpenUploadRootIdentity proves that an open capability still names the directory reachable at canonicalRoot. Call this immediately before any operation that must use ordinary canonical paths rather than root-relative access, such as image variant generation.

Types

type ProcessOptions added in v0.23.0

type ProcessOptions struct {
	// DownscaleOversized fits an oversized image inside the caps instead of
	// rejecting it. Intended for trusted local files (content migrations), not
	// for untrusted uploads, which must keep the strict reject.
	DownscaleOversized bool
}

ProcessOptions controls how ProcessImageWithOptions treats an image that exceeds the dimension caps.

type ProcessResult

type ProcessResult struct {
	Width    int
	Height   int
	MimeType string
	Size     int64
	FilePath string

	// Downscaled reports whether the image was fitted to the caps. When true,
	// OriginalWidth and OriginalHeight hold the pre-fit dimensions so callers
	// can tell the user what happened.
	Downscaled     bool
	OriginalWidth  int
	OriginalHeight int
}

ProcessResult contains the result of processing an uploaded image.

type Processor

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

Processor handles image processing operations using pure Go libraries.

func NewProcessor

func NewProcessor(uploadDir string) *Processor

NewProcessor creates a new image processor.

func (*Processor) CreateAllVariants

func (p *Processor) CreateAllVariants(sourcePath, uuid, filename string) ([]*VariantResult, error)

CreateAllVariants creates all standard variants for an image. It continues processing even if individual variants fail, returning all successfully created variants along with any errors encountered.

func (*Processor) CreateVariant

func (p *Processor) CreateVariant(sourcePath, uuid, filename string, config model.ImageVariantConfig, variantType string) (*VariantResult, error)

CreateVariant creates a resized variant of an image.

func (*Processor) DeleteMediaFiles

func (p *Processor) DeleteMediaFiles(uuid string) error

DeleteMediaFiles removes all files associated with a media item.

func (*Processor) DetectMimeType

func (p *Processor) DetectMimeType(data []byte) string

DetectMimeType detects the MIME type of image data.

func (*Processor) GetImageDimensions

func (p *Processor) GetImageDimensions(path string) (width, height int, err error)

GetImageDimensions returns the dimensions of an image file.

func (*Processor) IsImage

func (p *Processor) IsImage(mimeType string) bool

IsImage checks if a MIME type represents an image that can be processed.

func (*Processor) IsSupportedType

func (p *Processor) IsSupportedType(mimeType string) bool

IsSupportedType checks if a MIME type is supported for upload.

func (*Processor) ProcessImage

func (p *Processor) ProcessImage(reader io.Reader, uuid, filename string) (*ProcessResult, error)

ProcessImage reads an uploaded image file and returns its metadata. It saves the original file and returns processing results.

Oversized images are rejected. This is the entry point for untrusted uploads; callers handling trusted local files can opt into downscaling with ProcessImageWithOptions.

func (*Processor) ProcessImageWithOptions added in v0.23.0

func (p *Processor) ProcessImageWithOptions(reader io.Reader, uuid, filename string, opts ProcessOptions) (*ProcessResult, error)

ProcessImageWithOptions reads an image file and returns its metadata, saving the processed original.

With opts.DownscaleOversized the image is fitted inside the dimension caps rather than rejected, so a content migration does not lose an oversized photo. maxDecodablePixels still applies: past that point the file is refused whatever the caller asked for, because the decode itself is the risk.

func (*Processor) SaveMediaImage added in v0.23.0

func (p *Processor) SaveMediaImage(storageDir, mediaUUID, filename string, data []byte) (string, error)

SaveMediaImage writes one image into a declared media storage directory. It is used by internal generators that already hold encoded image bytes but still need the same UUID validation and root-relative filesystem boundary as uploaded and migrated images.

type RootFileCreation added in v0.23.0

type RootFileCreation struct {
	File      RootFileIdentity
	Directory *RootFileIdentity
}

RootFileCreation contains the published file identity and, when this write atomically reserved its UUID directory, that directory's identity as well.

type RootFileIdentity added in v0.23.0

type RootFileIdentity struct {
	Path string
	Info fs.FileInfo
}

RootFileIdentity identifies a file created through an already-open root. Callers retain the FileInfo snapshot so compensating cleanup can distinguish their file from a same-path replacement created by another actor.

For a file, Info describes the published contents — it is taken through the writing descriptor after the last byte lands, so SameRootFile can compare size and modification time as well as the inode number.

type VariantResult

type VariantResult struct {
	Type     string
	Width    int
	Height   int
	Size     int64
	FilePath string
}

VariantResult contains the result of creating an image variant.

Jump to

Keyboard shortcuts

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